from gym import make
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Adam
import random
from collections import deque

N_STEP = 200
GAMMA = 0.9
BETA = 1e-1

def transform_state(state):
    return np.array(state)

class ActorA2C(nn.Module):
    def __init__(self, state_dim, action_dim, hidden_dim):
        super(ActorA2C, self).__init__()
        self.activation = nn.ReLU()
        self.input = nn.Linear(state_dim, hidden_dim)
        self.hidden = nn.Sequential(
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
        )
        self.mu_output = nn.Linear(hidden_dim, action_dim)
        self.var_output = nn.Linear(hidden_dim, action_dim)
        self.var_activation = nn.Softplus()

    def forward(self, state):
        base = self.activation(self.hidden(self.activation(self.input(state))))
        mu = self.mu_output(base)
        var = self.var_activation(self.var_output(base))
        return mu, var

class A2C:
    def __init__(self, state_dim, action_dim, hidden_dim=256):
        self.gamma = GAMMA ** N_STEP
        self.actor = ActorA2C(state_dim, action_dim, hidden_dim)
        self.critic = nn.Sequential(
            nn.Linear(state_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, 1),
        )
        self.critic_optim = Adam(self.critic.parameters(), lr=5e-3)
        self.actor_optim = Adam(self.actor.parameters(), lr=5e-4)
        self.critic_loss = nn.MSELoss()
        self.loss = torch.tensor(0.0)

    def update(self, transition):
        state, action, next_state, reward, done = transition
        reward = torch.tensor(reward).view(1).float()
        if not done:
            with torch.no_grad():
                reward += self.gamma * self.critic(torch.tensor(next_state).float())
        state = torch.tensor(state).float()
        mu, var = self.actor(state)
        val = self.critic(state)
        critic_loss = self.critic_loss(val, reward)
        advantage = reward - val.detach()
        action = torch.tensor(action).float()
        p1 = - ((mu - action) ** 2) / (2 * var.clamp(min=1e-3))
        p2 = - torch.log(torch.sqrt(2 * np.pi * var))
        log_pi = p1 + p2
        actor_loss = - (advantage * log_pi).mean()
        entropy_loss = BETA * (-(torch.log(2 * np.pi * var) + 1) / 2).mean()
        self.loss += critic_loss + actor_loss + entropy_loss

    def step(self):
        self.actor_optim.zero_grad()
        self.critic_optim.zero_grad()
        self.loss.backward()
        self.critic_optim.step()
        self.actor_optim.step()
        self.loss = torch.tensor(0.0)

    def act(self, state):
        # Remember: agent is not deterministic, sample actions from distribution (e.g. Gaussian)
        with torch.no_grad():
            state = torch.tensor(state).float()
            mu, var = self.actor(state)
            mu = mu.data.numpy()
            sigma = torch.sqrt(var).data.numpy()
            return np.random.normal(mu, sigma)

    def act_agent(self, state):
        with torch.no_grad():
            state = transform_state(state)
            mu, _ = self.actor(torch.tensor(state).float())
            return mu.detach().numpy()

    def save(self):

        torch.save(self.actor, "agent.pkl")

def test(agent, env):
    episodes = 75
    total_reward = 0
    for i in range(episodes):
        state = env.reset()
        done = False
        while not done:
            action = agent.act_agent(state)
            next_state, reward, done, _ = env.step(action)
            total_reward += reward
            state = next_state
    average_reward = total_reward / episodes
    env.close()
    return average_reward

if __name__ == "__main__":
    env = make("Pendulum-v0")
    np.random.seed(42)
    torch.manual_seed(42)
    random.seed(42)
    env.seed(42)
    algo = A2C(state_dim=3, action_dim=1)
    episodes = 10000
    best_score = -2000

    for i in range(episodes):
        state = transform_state(env.reset())
        total_reward = 0
        steps = 0
        done = False
        reward_buffer = deque(maxlen=N_STEP)
        state_buffer = deque(maxlen=N_STEP)
        action_buffer = deque(maxlen=N_STEP)
        while not done:
            action = algo.act(state)
            next_state, reward, done, _ = env.step(action)
            next_state = transform_state(next_state)
            total_reward += reward
            steps += 1
            reward_buffer.append(reward)
            state_buffer.append(state)
            action_buffer.append(action)
            if len(reward_buffer) == N_STEP:
                rb = list(reward_buffer)
                for k in range(1, N_STEP):
                    algo.update((state_buffer[k], action_buffer[k], next_state,
                                 sum([(GAMMA ** i) * r for i, r in enumerate(rb[k:])]), done))
                action_buffer.clear()
                reward_buffer.clear()
                state_buffer.clear()
                algo.step()
            state = next_state
        print((i, total_reward))

        if (i % 20) == 0 and i != 0:
            score = test(algo, env)
            if score >= best_score:
                best_score = score
                print("new best score")
                print((i, score))
                algo.save()


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        # arr = []
        # while head is not None:
        #     arr.append(head.val)
        # print(arr)

        slow = head
        fast = head
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

s = Solution()
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(4)

l1.next = l2
l2.next = l3
l3.next = l2

ans = s.hasCycle(l1)
print(ans)

# https://leetcode.com/problems/linked-list-cycle/

Python Leetcode Algorithms/4. LinkedList/3. LinkedList_Cycle.py


import os
import pathlib
import time

import numpy as np

from tensorflow.core.protobuf import config_pb2
from tensorflow.python.checkpoint import checkpoint as trackable_utils
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.training import checkpoint_utils
from tensorflow.python.training import saver as saver_lib

def _create_checkpoints(sess, checkpoint_dir):
  checkpoint_prefix = os.path.join(checkpoint_dir, "model")
  checkpoint_state_name = "checkpoint"
  v1 = variable_scope.get_variable("var1", [1, 10])
  v2 = variable_scope.get_variable("var2", [10, 10])
  v3 = variable_scope.get_variable("var3", [100, 100])
  with variable_scope.variable_scope("useful_scope"):
    v4 = variable_scope.get_variable("var4", [9, 9])
  sess.run(variables.global_variables_initializer())
  v1_value, v2_value, v3_value, v4_value = sess.run([v1, v2, v3, v4])
  saver = saver_lib.Saver()
  saver.save(
      sess,
      checkpoint_prefix,
      global_step=0,
      latest_filename=checkpoint_state_name)
  return v1_value, v2_value, v3_value, v4_value

def _create_partition_checkpoints(sess, checkpoint_dir):
  checkpoint_prefix = os.path.join(checkpoint_dir, "model")
  checkpoint_state_name = "checkpoint"
  with variable_scope.variable_scope("scope"):
    v1 = variable_scope.get_variable(
        name="var1",
        shape=[100, 100],
        initializer=init_ops.truncated_normal_initializer(0.5),
        partitioner=partitioned_variables.min_max_variable_partitioner(
            max_partitions=5, axis=0, min_slice_size=8 << 10))
  sess.run(variables.global_variables_initializer())
  v1_value = sess.run(v1._get_variable_list())
  saver = saver_lib.Saver()
  saver.save(
      sess,
      checkpoint_prefix,
      global_step=0,
      latest_filename=checkpoint_state_name)
  return v1_value

class CheckpointsTest(test.TestCase):

  def testNoCheckpoints(self):
    checkpoint_dir = self.get_temp_dir() + "/no_checkpoints"
    with self.assertRaises(errors_impl.OpError):
      self.assertAllEqual(
          checkpoint_utils.load_variable(checkpoint_dir, "var1"), [])

  def testNoTensor(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      _, _, _, _ = _create_checkpoints(session, checkpoint_dir)
    with self.assertRaises(errors_impl.OpError):
      self.assertAllEqual(
          checkpoint_utils.load_variable(checkpoint_dir, "var5"), [])

  def testGetTensor(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, v2, v3, v4 = _create_checkpoints(session, checkpoint_dir)
    self.assertAllEqual(
        checkpoint_utils.load_variable(checkpoint_dir, "var1"), v1)
    self.assertAllEqual(
        checkpoint_utils.load_variable(checkpoint_dir, "var2"), v2)
    self.assertAllEqual(
        checkpoint_utils.load_variable(checkpoint_dir, "var3"), v3)
    self.assertAllEqual(
        checkpoint_utils.load_variable(checkpoint_dir, "useful_scope/var4"), v4)

  def testGetAllVariables(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      _create_checkpoints(session, checkpoint_dir)
    self.assertEqual(
        checkpoint_utils.list_variables(checkpoint_dir),
        [("useful_scope/var4", [9, 9]), ("var1", [1, 10]), ("var2", [10, 10]),
         ("var3", [100, 100])])

  def testFSPath(self):
    checkpoint_dir = pathlib.Path(self.get_temp_dir())
    with self.cached_session() as session:
      v1, v2, v3, v4 = _create_checkpoints(session, checkpoint_dir)  # pylint: disable=unused-variable

    reader = checkpoint_utils.load_checkpoint(checkpoint_dir)
    self.assertAllEqual(reader.get_tensor("var1"), v1)

    self.assertAllEqual(
        checkpoint_utils.load_variable(checkpoint_dir, "var1"), v1)

    self.assertEqual(
        checkpoint_utils.list_variables(checkpoint_dir),
        [("useful_scope/var4", [9, 9]), ("var1", [1, 10]), ("var2", [10, 10]),
         ("var3", [100, 100])])

  def testInitFromCheckpoint(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, v2, v3, v4 = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope("some_scope"):
          my1 = variable_scope.get_variable("my1", [1, 10])
          with variable_scope.variable_scope("some_other_scope"):
            my2 = variable_scope.get_variable("my2", [10, 10])
            with variable_scope.variable_scope("other_useful_scope"):
              my4 = variable_scope.get_variable("var4", [9, 9])
        my3 = variable_scope.get_variable("my3", [100, 100])
        my3b = variable_scope.get_variable("my3b", [100, 100])

        checkpoint_utils.init_from_checkpoint(checkpoint_dir, {
            "var1": "some_scope/my1",
            "useful_scope/": "some_scope/some_other_scope/other_useful_scope/",
        })
        checkpoint_utils.init_from_checkpoint(checkpoint_dir, [
            ("var2", "some_scope/some_other_scope/my2"),
            ("var3", my3),
            ("var3", my3b),
        ])

        session.run(variables.global_variables_initializer())
        self.assertAllEqual(my1.eval(session), v1)
        self.assertAllEqual(my2.eval(session), v2)
        self.assertAllEqual(my3.eval(session), v3)
        self.assertAllEqual(my3b.eval(session), v3)
        self.assertAllEqual(my4.eval(session), v4)

        # Check that tensors are not explicitly in the graph.
        self.assertLess(len(str(session.graph.as_graph_def())), 32000)

  def testInitialValueComesFromCheckpoint(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, _, _, _ = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope(
            "some_scope", initializer=init_ops.zeros_initializer()):
          my1 = variable_scope.get_variable("my1", [1, 10])

        before = my1.initialized_value()

        checkpoint_utils.init_from_checkpoint(checkpoint_dir, {"var1": my1})

        after = my1.initialized_value()

        self.assertAllEqual(session.run(before), [[0.0] * 10])
        self.assertAllEqual(session.run(after), v1)

        session.run(variables.global_variables_initializer())

        self.assertAllEqual(session.run(my1), v1)
        self.assertAllEqual(session.run(my1.initialized_value()), v1)
        self.assertAllClose(session.run(before), v1)
        self.assertAllClose(session.run(after), v1)
        with self.assertRaises(AssertionError):
          self.assertAllClose(v1, [[0.0] * 10])

  def testInitWithScopeDoesNotCaptureSuffixes(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      _, _, _, v4 = _create_checkpoints(session, checkpoint_dir)

    with ops.Graph().as_default() as g:
      with variable_scope.variable_scope("useful_scope"):
        my4 = variable_scope.get_variable("var4", [9, 9])
      with variable_scope.variable_scope("useful_scope_1"):
        my5_init = [[1.0, 2.0], [3.0, 4.0]]
        my5 = variable_scope.get_variable("var5", initializer=my5_init)

      checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                            {"useful_scope/": "useful_scope/"})
      with self.session(graph=g) as session:
        session.run(variables.global_variables_initializer())
        self.assertAllEqual(my4.eval(session), v4)
        self.assertAllEqual(my5.eval(session), my5_init)

  def testRestoreRunsOnSameDevice(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      _create_checkpoints(session, checkpoint_dir)

    with ops.Graph().as_default():
      with ops.device("/job:ps"):
        with variable_scope.variable_scope("useful_scope"):
          variable_scope.get_variable("var4", [9, 9])

      checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                            {"useful_scope/": "useful_scope/"})

  def testInitFromRootCheckpoint(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, v2, v3, v4 = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope("some_scope"):
          my1 = variable_scope.get_variable("var1", [1, 10])
          my2 = variable_scope.get_variable("var2", [10, 10])
          my3 = variable_scope.get_variable("var3", [100, 100])
          with variable_scope.variable_scope("useful_scope"):
            my4 = variable_scope.get_variable("var4", [9, 9])

        checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                              {"/": "some_scope/",})

        session.run(variables.global_variables_initializer())
        self.assertAllEqual(my1.eval(session), v1)
        self.assertAllEqual(my2.eval(session), v2)
        self.assertAllEqual(my3.eval(session), v3)
        self.assertAllEqual(my4.eval(session), v4)

  def testInitToRootCheckpoint(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, v2, v3, v4 = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        my1 = variable_scope.get_variable("var1", [1, 10])
        my2 = variable_scope.get_variable("var2", [10, 10])
        my3 = variable_scope.get_variable("var3", [100, 100])
        with variable_scope.variable_scope("useful_scope"):
          my4 = variable_scope.get_variable("var4", [9, 9])

        checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                              {"/": "/",})

        session.run(variables.global_variables_initializer())
        self.assertAllEqual(my1.eval(session), v1)
        self.assertAllEqual(my2.eval(session), v2)
        self.assertAllEqual(my3.eval(session), v3)
        self.assertAllEqual(my4.eval(session), v4)

  def testInitFromPartitionVar(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1 = _create_partition_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope("some_scope"):
          my1 = variable_scope.get_variable(
              name="my1",
              shape=[100, 100],
              initializer=init_ops.zeros_initializer(),
              partitioner=partitioned_variables.min_max_variable_partitioner(
                  max_partitions=5, axis=0, min_slice_size=8 << 10))
          my1_var_list = my1._get_variable_list()
        # Create another variable with different partitions than the variable in
        # the checkpoint.
        with variable_scope.variable_scope("some_other_scope"):
          my2 = variable_scope.get_variable(
              name="var1",
              shape=[100, 100],
              initializer=init_ops.zeros_initializer(),
              partitioner=partitioned_variables.min_max_variable_partitioner(
                  max_partitions=5, axis=0, min_slice_size=16 << 10))
          my2_var_list = my2._get_variable_list()

        checkpoint_utils.init_from_checkpoint(checkpoint_dir, {
            "scope/var1": "some_scope/my1",
            "scope/": "some_other_scope/"})

        session.run(variables.global_variables_initializer())
        my1_values = session.run(my1_var_list)
        self.assertAllEqual(my1_values, v1)
        my2_values = session.run(my2_var_list)
        # Verify we created different number of partitions.
        self.assertNotEqual(len(my2_values), len(v1))
        # Verify the values were correctly initialized inspite of different
        # partitions.
        full_my2_values = np.concatenate(my2_values, axis=0)
        full_v1_values = np.concatenate(v1, axis=0)
        self.assertAllEqual(full_my2_values, full_v1_values)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope("some_scope"):
          my1 = variable_scope.get_variable(
              name="my1",
              shape=[100, 100],
              initializer=init_ops.truncated_normal_initializer(0.5),
              partitioner=partitioned_variables.min_max_variable_partitioner(
                  max_partitions=5, axis=0, min_slice_size=8 << 10))
          my1_var_list = my1._get_variable_list()

        checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                              {"scope/var1": my1_var_list,})

        session.run(variables.global_variables_initializer())
        my1_values = session.run(my1_var_list)
        self.assertAllEqual(my1_values, v1)

  def testInitFromCheckpointMissing(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      _, _, _, _ = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        with variable_scope.variable_scope("some_scope"):
          _ = variable_scope.get_variable("my1", [10, 10])
          _ = variable_scope.get_variable(
              "my2", [1, 10],
              dtype=dtypes.int64,
              initializer=init_ops.zeros_initializer())

        # No directory.
        with self.assertRaises(errors_impl.OpError):
          checkpoint_utils.init_from_checkpoint("no_dir",
                                                {"var1": "some_scope/my1"})

        # No variable in checkpoint.
        with self.assertRaises(ValueError):
          checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                                {"no_var": "some_scope/my1"})

        # No variable in the graph.
        with self.assertRaises(ValueError):
          checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                                {"var3": "some_scope/no_var"})

        # Shape mismatch.
        with self.assertRaises(ValueError):
          checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                                {"var1": "some_scope/my1"})

        # Variable 'my1' and 'my2' are missing in given checkpoint scope.
        with self.assertRaises(ValueError):
          checkpoint_utils.init_from_checkpoint(
              checkpoint_dir, {"useful_scope/": "some_scope/"})

        # Mapping is not to scope name.
        with self.assertRaises(ValueError):
          checkpoint_utils.init_from_checkpoint(checkpoint_dir,
                                                {"useful_scope": "some_scope/"})

  def testNoAdditionalReadOpsForResourceVariables(self):
    checkpoint_dir = self.get_temp_dir()
    with self.cached_session() as session:
      v1, _, _, _ = _create_checkpoints(session, checkpoint_dir)

    # New graph and session.
    with ops.Graph().as_default() as g:
      with self.session(graph=g) as session:
        my1 = resource_variable_ops.ResourceVariable([[0.0] * 10], name="my1")

        with ops.name_scope("init_from_checkpoint"):
          checkpoint_utils.init_from_checkpoint(checkpoint_dir, {"var1": my1})

        # Basic sanity checks:
        session.run(variables.global_variables_initializer())
        self.assertAllEqual(session.run(my1), v1)

    ops_in_init_from_checkpoint_scope = [
        op for op in g.get_operations()
        if (op.name.startswith("init_from_checkpoint/") and
            not op.name.startswith("init_from_checkpoint/checkpoint_initializer"
                                  ) and
            op.type != "AssignVariableOp" and
            op.type != "Identity")
    ]
    self.assertEqual(ops_in_init_from_checkpoint_scope, [])

class CheckpointIteratorTest(test.TestCase):

  @test_util.run_in_graph_and_eager_modes
  def testReturnsEmptyIfNoCheckpointsFound(self):
    checkpoint_dir = os.path.join(self.get_temp_dir(), "no_checkpoints_found")

    num_found = 0
    for _ in checkpoint_utils.checkpoints_iterator(checkpoint_dir, timeout=0):
      num_found += 1
    self.assertEqual(num_found, 0)

  @test_util.run_in_graph_and_eager_modes
  def testReturnsSingleCheckpointIfOneCheckpointFound(self):
    checkpoint_dir = os.path.join(self.get_temp_dir(), "one_checkpoint_found")
    if not gfile.Exists(checkpoint_dir):
      gfile.MakeDirs(checkpoint_dir)

    save_path = os.path.join(checkpoint_dir, "model.ckpt")

    a = resource_variable_ops.ResourceVariable(5)
    self.evaluate(a.initializer)
    checkpoint = trackable_utils.Checkpoint(a=a)
    checkpoint.save(file_prefix=save_path)

    num_found = 0
    for _ in checkpoint_utils.checkpoints_iterator(checkpoint_dir, timeout=0):
      num_found += 1
    self.assertEqual(num_found, 1)

  @test_util.run_in_graph_and_eager_modes
  def testWorksWithFSPath(self):
    checkpoint_dir = pathlib.Path(self.get_temp_dir()) / "one_checkpoint_found"
    if not gfile.Exists(checkpoint_dir):
      gfile.MakeDirs(checkpoint_dir)

    save_path = checkpoint_dir / "model.ckpt"

    a = resource_variable_ops.ResourceVariable(5)
    self.evaluate(a.initializer)
    checkpoint = trackable_utils.Checkpoint(a=a)
    checkpoint.save(file_prefix=save_path)

    num_found = 0
    for _ in checkpoint_utils.checkpoints_iterator(checkpoint_dir, timeout=0):
      num_found += 1
    self.assertEqual(num_found, 1)

  @test_util.run_v1_only("Tests v1-style checkpoint sharding")
  def testReturnsSingleCheckpointIfOneShardedCheckpoint(self):
    checkpoint_dir = os.path.join(self.get_temp_dir(),
                                  "one_checkpoint_found_sharded")
    if not gfile.Exists(checkpoint_dir):
      gfile.MakeDirs(checkpoint_dir)

    global_step = variables.Variable(0, name="v0")

    # This will result in 3 different checkpoint shard files.
    with ops.device("/cpu:0"):
      variables.Variable(10, name="v1")
    with ops.device("/cpu:1"):
      variables.Variable(20, name="v2")

    saver = saver_lib.Saver(sharded=True)

    with session_lib.Session(
        target="",
        config=config_pb2.ConfigProto(device_count={"CPU": 2})) as session:

      session.run(variables.global_variables_initializer())
      save_path = os.path.join(checkpoint_dir, "model.ckpt")
      saver.save(session, save_path, global_step=global_step)

    num_found = 0
    for _ in checkpoint_utils.checkpoints_iterator(checkpoint_dir, timeout=0):
      num_found += 1
    self.assertEqual(num_found, 1)

  @test_util.run_in_graph_and_eager_modes
  def testTimeoutFn(self):
    timeout_fn_calls = [0]
    def timeout_fn():
      timeout_fn_calls[0] += 1
      return timeout_fn_calls[0] > 3

    results = list(
        checkpoint_utils.checkpoints_iterator(
            "/non-existent-dir", timeout=0.1, timeout_fn=timeout_fn))
    self.assertEqual([], results)
    self.assertEqual(4, timeout_fn_calls[0])

@test_util.run_all_in_graph_and_eager_modes
class WaitForNewCheckpointTest(test.TestCase):

  def testReturnsNoneAfterTimeout(self):
    start = time.time()
    ret = checkpoint_utils.wait_for_new_checkpoint(
        "/non-existent-dir", "foo", timeout=1.0, seconds_to_sleep=0.5)
    end = time.time()
    self.assertIsNone(ret)

    # We've waited one second.
    self.assertGreater(end, start + 0.5)

    # The timeout kicked in.
    self.assertLess(end, start + 1.1)

if __name__ == "__main__":
  test.main()


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

import numpy as np
from collections import Counter
from contextlib import closing
from marisa_trie import Trie, RecordTrie
from multiprocessing.pool import Pool

from wiki_extractor import WikiExtractor
from wiki_dump_reader import WikiDumpReader

_extractor = None

class EntityDB(object):
    def __init__(self, title_dict, redirect_dict, inlink_arr):
        self._title_dict = title_dict
        self._redirect_dict = redirect_dict
        self._inlink_arr = inlink_arr

    def __len__(self):
        return len(self._title_dict)

    def __contains__(self, key):
        return key in self._title_dict

    def resolve_redirect(self, title):
        try:
            index = self._redirect_dict[title][0][0]
            title = self._title_dict.restore_key(index)

        except KeyError:
            pass

        return title

    def get_inlink_count(self, title, resolve_redirect=False):
        if resolve_redirect:
            title = self.resolve_redirect(title)

        try:
            index = self._title_dict[title]
            return self._inlink_arr[index]

        except KeyError:
            return 0

    @staticmethod
    def build(dump_file, pool_size, chunk_size):
        dump_reader = WikiDumpReader(dump_file)

        global _extractor
        _extractor = WikiExtractor()

        titles = []
        redirects = {}
        title_counter = Counter()

        with closing(Pool(pool_size)) as pool:
            for (page, links) in pool.imap_unordered(
                _process_page, dump_reader, chunksize=chunk_size
            ):
                titles.append(page.title)
                if page.is_redirect:
                    redirects[page.title] = page.redirect

                for link_obj in links:
                    title_counter[link_obj.title] += 1

        title_dict = Trie(titles)

        redirect_items = []
        for (title, dest_title) in redirects.iteritems():
            if dest_title in title_dict:
                redirect_items.append((title, (title_dict[dest_title],)))

        redirect_dict = RecordTrie('<I', redirect_items)

        for (title, count) in title_counter.items():
            dest_obj = redirect_dict.get(title)
            if dest_obj is not None:
                title_counter[title_dict.restore_key(dest_obj[0][0])] += count
                del title_counter[title]

        inlink_arr = np.zeros(len(title_dict), dtype=np.int)
        for (title, count) in title_counter.items():
            title_index = title_dict.get(title)
            if title_index is not None:
                inlink_arr[title_index] = count

        return EntityDB(title_dict, redirect_dict, inlink_arr)

    def save(self, out_file):
        self._title_dict.save(out_file + '_title.trie')
        self._redirect_dict.save(out_file + '_redirect.trie')
        np.save(out_file + '_prior.npy', self._inlink_arr)

    @staticmethod
    def load(in_file, mmap=True):
        title_dict = Trie()
        redirect_dict = RecordTrie('<I')

        title_dict.mmap(in_file + '_title.trie')
        redirect_dict.mmap(in_file + '_redirect.trie')
        inlink_arr = np.load(in_file + '_prior.npy', mmap_mode='r')

        return EntityDB(title_dict, redirect_dict, inlink_arr)

def _process_page(page):
    return (page, [l for p in _extractor.extract_paragraphs(page) for l in p.wiki_links])


import sys
input = sys.stdin.readline

def do():
  N = int(input())
  memo = [0]*(31)
  memo[2] = 3
  for i in range(4, N + 1):
    if (i % 2 == 0):
      memo[i] = 3*memo[i - 2] + 2*sum(memo[0:i - 2:2]) + 2
  print(memo[N])

do()

다이나믹 프로그래밍/2133_타일 채우기.py


import os

from CBLClient.Client import Client
from CBLClient.Args import Args
from utilities.cluster_config_utils import sg_ssl_enabled

class ReplicatorConfiguration(object):
    _client = None
    baseUrl = None

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

        # If no base url was specified, raise an exception
        if not self.base_url:
            raise Exception("No base_url specified")

        self._client = Client(base_url)

    def configure(self, source_db, target_url=None, target_db=None, replication_type="push_pull", continuous=False,
                  channels=None, documentIDs=None, replicator_authenticator=None, headers=None, max_timeout_interval=None, retries=None, encryptor=None):
        args = Args()
        args.setMemoryPointer("source_db", source_db)
        args.setString("replication_type", replication_type)
        args.setBoolean("continuous", continuous)

        if retries is not None:
            args.setString("max_retries", retries)
        if max_timeout_interval is not None:
            args.setString("max_timeout", max_timeout_interval)
        if channels is not None:
            args.setArray("channels", channels)
        if documentIDs is not None:
            args.setArray("documentIDs", documentIDs)
        if replicator_authenticator is not None:
            args.setMemoryPointer("authenticator", replicator_authenticator)
        if headers is not None:
            args.setDictionary("headers", headers)
        if target_db is None:
            args.setString("target_url", target_url)
            return self._client.invokeMethod("replicator_configureRemoteDbUrl", args)
        if encryptor is not None:
            args.setMemoryPointer("encryptor", encryptor)
        else:
            args.setMemoryPointer("target_db", target_db)
            return self._client.invokeMethod("replicator_configureLocalDb", args)

        cluster_config = os.environ["CLUSTER_CONFIG"]
        if sg_ssl_enabled(cluster_config):
            args.setString("pinnedservercert", "sg_cert")

    def builderCreate(self, source_db, target_db=None, target_url=None):
        args = Args()
        args.setMemoryPointer("sourceDb", source_db)
        if target_db:
            args.setMemoryPointer("targetDb", target_db)
        elif target_url:
            args.setMemoryPointer("targetURI", target_url)
        else:
            raise Exception("Pass either target_db or target_url.")
        return self._client.invokeMethod("replicatorConfiguration_builderCreate", args)

    def create(self, replicatorBuilder):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicatorBuilder)
        return self._client.invokeMethod("replicatorConfiguration_create",
                                         args)

    def copy(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_copy", args)

    def getAuthenticator(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getAuthenticator",
                                         args)

    def getChannels(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getChannels",
                                         args)

    def getConflictResolver(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getConflictResolver",
                                         args)

    def getDatabase(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getDatabase",
                                         args)

    def getDocumentIDs(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getDocumentIDs",
                                         args)

    def getPinnedServerCertificate(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getPinnedServerCertificate",
                                         args)

    def getReplicatorType(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getReplicatorType",
                                         args)

    def getTarget(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_getTarget", args)

    def isContinuous(self, configuration):
        args = Args()
        args.setMemoryPointer("configuration", configuration)
        return self._client.invokeMethod("replicatorConfiguration_isContinuous",
                                         args)

    def setAuthenticator(self, replicator_builder, authenticator):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setMemoryPointer("authenticator", authenticator)
        return self._client.invokeMethod("replicatorConfiguration_setAuthenticator",
                                         args)

    def setChannels(self, replicator_builder, channels):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setArray("channels", channels)
        return self._client.invokeMethod("replicatorConfiguration_setChannels",
                                         args)

    def setConflictResolver(self, replicator_builder, conflict_resolver):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setMemoryPointer("conflictResolver", conflict_resolver)
        return self._client.invokeMethod("replicatorConfiguration_setConflictResolver",
                                         args)

    def setContinuous(self, replicator_builder, continuous):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setBoolean("continuous", continuous)
        return self._client.invokeMethod("replicatorConfiguration_setContinuous",
                                         args)

    def setDocumentIDs(self, replicator_builder, document_ids):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setArray("documentIds", document_ids)
        return self._client.invokeMethod("replicatorConfiguration_setDocumentIDs",
                                         args)

    def setPinnedServerCertificate(self, replicator_builder, cert):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setArray("cert", cert)
        return self._client.invokeMethod("replicatorConfiguration_setPinnedServerCertificate",
                                         args)

    def setReplicatorType(self, replicator_builder, repl_type):
        args = Args()
        args.setMemoryPointer("replicatorBuilder", replicator_builder)
        args.setMemoryPointer("replType", repl_type)
        return self._client.invokeMethod("replicatorConfiguration_setReplicatorType",
                                         args)


from telebot.handler_backends import State, StatesGroup
from telebot.storage import StateMemoryStorage
from keyboards.inline.inline_button import Inline
from keyboards.reply.reply_button import Reply
from telebot.types import  Message, CallbackQuery
from database.model_functions.user import UserMethods
from database.model_functions.hotel_photos import HotelPhotos_methods
from loader import bot
from re import search
from pprint import pprint
from .process_data import ProcessData
from api_parse.parse_api_and_unpack import API
from api_parse.api_utils import API_UTILS
from loader import logger

state_storage = StateMemoryStorage()
API_UTILS = API_UTILS()

class UserData(StatesGroup):
    city = State()
    date = State()
    adults_children = State()
    price = State()
    distance = State()
    photos = State()
    photos_amount = State()
    api_response = State()
    finalize_results = State()
@bot.message_handler(state="*", commands=["cancel"])
def cancel_state(message: Message) -> None:
    bot.send_message(message.from_user.id, "You can enter the command again.")
    bot.set_state(message.from_user.id, None, message.chat.id)

@bot.message_handler(state=UserData.city)
def city_get(message: Message) -> None:
    logger.info("City Function")
    city, chat_id, from_user_id = message.text, message.chat.id, message.from_user.id

    url, headers = API_UTILS.location_url, API_UTILS.headers
    query_string = {"q": city}
    location_response = API.request_to_api(url=url, headers=headers, query_string=query_string)
    city_data = API.unpack_locationv3_json(json_str=location_response.text, city_group=city)
    if city_data:
        markup = Inline().add_buttons(text=city_data["fullName"], callback=city_data["gaiaId"])
        bot.send_message(chat_id, "Please be a bit more precise!", reply_markup=markup)

    bot.set_state(from_user_id, UserData.date, chat_id)
    with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
        data["city_chosen"] = city

@bot.message_handler(state=UserData.date)
def get_date(message: Message) -> None:
    logger.info("Date Function")
    dates = message.text.split()
    check_date = ProcessData.check_dates_validity(dates=dates)
    if not check_date:
        bot.send_message(message.from_user.id, "Wrong format of date. Try again.")
        bot.set_state(message.from_user.id, UserData.date, message.chat.id)

    # with bot.retrieve_data(message.from_user.id, message.chat.id) as user_data:
    #     user_data["date"] = dates
    else:
        ProcessData.save_data(user_id=message.from_user.id, chat_id=message.chat.id, dict_key="date", data=check_date)
        bot.send_message(message.chat.id,
                         "Now, enter how many adults and children are needed."
                         "\nFormat: Adults Children\n"
                         "If there are more than two children please split the age by a comma.й\nExample 1: 2 5,6\n"
                         "Example 2:  2 (No children)")
        bot.set_state(message.from_user.id, UserData.adults_children, message.chat.id)
    # TODO add calendar

@bot.message_handler(state=UserData.adults_children)
def adults_children(message: Message) -> None:
    logger.info("Getting adults")
    adults_children_object = message.text.split()
    pattern = r'[A-Za-z]'
    find = search(pattern, message.text)
    if find:
        bot.send_message(message.from_user.id, "This parameter only takes digits and commas.\nTry again.")
        bot.set_state(message.from_user.id, UserData.adults_children, message.chat.id)
    else:
        if len(adults_children_object) == 1:
            adults = adults_children_object[0]
            children_object = list()
        else:
            adults = adults_children_object[0]
            children_object = adults_children_object[1].split(",")
        rooms_object = ProcessData.create_rooms_object(adults=adults, children_ages=children_object)
        with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
            command  = data["command"]
        if command == "/bestdeal":
            bot.set_state(message.from_user.id, UserData.price, message.chat.id)
            bot.send_message(message.from_user.id, "Please enter the minimum and maximum price of the hotel.\nFormat: Min Max(50 100)\nSend 0 for setting the price automatically.")
        else:
            markup = Inline().add_buttons(text=["Yes", "No"], callback=["photo_yes", "photo_no"])
            bot.send_message(message.from_user.id, "Would you like to upload photos?", reply_markup=markup)
            bot.set_state(message.from_user.id, UserData.photos, message.chat.id)
        ProcessData.save_data(user_id=message.from_user.id, chat_id=message.chat.id,
                              dict_key="adults_children", data=rooms_object)

@bot.message_handler(state=UserData.price)
def get_price(message: Message) -> None:

    logger.info("Getting price")
    pattern = r'[A-Za-z]'
    find = search(pattern, message.text)
    if find:
        bot.send_message(message.from_user.id,
                         "This parameter only takes digits.\nTry again.")
        bot.set_state(message.from_user.id, UserData.adults_children, message.chat.id)
    else:
        with bot.retrieve_data(message.from_user.id, message.chat.id) as data:

            if data["filter"] == "PRICE_HIGH_TO_LOW" and message.text == "0":
                min_price, max_price = 100, 1500
            elif data["command"] == "/bestdeal" and message.text == "0":
                min_price, max_price = 1, 500
            elif message.text == "0":
                min_price, max_price = 100, 150
            else:
                min_price, max_price = message.text.split()
        price_object = {"price": {"max": max_price, "min": min_price}}
        bot.send_message(chat_id=message.chat.id, text="Please enter the distance from center in miles.")
        bot.set_state(message.from_user.id, UserData.distance, message.chat.id)
        ProcessData.save_data(user_id=message.from_user.id, chat_id=message.chat.id, dict_key="price", data=price_object)

@bot.message_handler(state=UserData.distance)
def get_distance(message: Message) -> None:
    with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
        data["filter"] = f"DISTANCE ({message.text})"

    markup = Inline().add_buttons(text=["Yes", "No"], callback=["photo_yes", "photo_no"])
    bot.send_message(message.from_user.id, "Would you like to upload photos?", reply_markup=markup)
@bot.message_handler(state=UserData.photos_amount)
def photos_amount(message: Message) -> None:
    logger.info("Photos Amount")
    if not message.text.isdigit():
        bot.send_message(message.from_user.id, "This parameter only takes digits.\nTry again.")
        bot.set_state(message.from_user.id, UserData.photos_amount, message.chat.id)
    else:
        with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
            data["photos_amount"] = int(message.text)

    markup = Reply.add_buttons(text="Start searching")
    bot.send_message(message.chat.id, text="Start?", reply_markup=markup)
    bot.set_state(message.from_user.id, UserData.api_response, message.chat.id)

@bot.message_handler(state=UserData.api_response)
def process_data(message: Message) -> None:
    logger.info("Processing data")
    url, headers = API_UTILS.properties_url, API_UTILS.headers
    headers["content-type"] = "application/json"
    with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
        photos_upload = data.get("photos")
        results_number = 500
        sort, city_name, command, date_of_command = data["filter"], data["city_chosen"], data["command"], data["date_of_command"]
        payload = ProcessData.finalize_payload(data=data, sort=sort, result_size=results_number)
        results = API.post_request(url=url, payload=payload, headers=headers)

    if results:
        hotels_founds = API.unpack_propertiesv2_json(response=results, results_amount=results_number,
                                                    city=city_name, photo_upload=photos_upload, user_id=message.from_user.id)
        if hotels_founds:
            UserMethods.create_record(user_id=message.from_user.id, user_name=message.from_user.username,
                               command=command, date_of_command=date_of_command, hotel_ids=hotels_founds)
            bot.send_message(message.chat.id, "The search has finished.")
        # if not detailed_results:
        #     bot.send_message(message.from_user.id, "Похоже, что у сервера сейчас проблема. Пожалуйста, напишите автору бота.")
    else:
        bot.send_message(message.from_user.id, "We were not able to find results for your parameters. || This message can happen due to server errors as well.")
    bot.set_state(message.from_user.id, None, message.chat.id)

""" BUTTON CALLBACKS"""
@bot.callback_query_handler(func=lambda call: call.data.isdigit())
def date_callback(call: CallbackQuery) -> None:

    logger.info("Extra city callback")
    if call.data.isdigit():
        with bot.retrieve_data(call.from_user.id, call.from_user.id) as data:
            data["city"] = call.data
        bot.send_message(call.from_user.id,
                         'Please enter the date of checking in and checking out to your hotel.\nFormat:  DD/MM/YY DD/MM/YY\nExample: 22/10/22 30/10/22')

@bot.callback_query_handler(func=lambda call: call.data == "photo_yes")
def photos_yes(call: CallbackQuery) -> None:
    logger.info("Photos Yes callback")
    photos = True
    bot.send_message(call.from_user.id,
                     "Please enter the amount of photos you would like to enter.\nMaximum 9 photos.")
    bot.set_state(call.from_user.id, UserData.photos_amount, call.from_user.id)
    with bot.retrieve_data(call.from_user.id, call.from_user.id) as data:
        data["photos"] = photos

@bot.callback_query_handler(func= lambda call: call.data == "photo_no")
def photos_no(call: CallbackQuery) -> None:
    logger.info("NO PHOTOS CALLBACK")
    photos = False
    markup = Reply.add_buttons(text="Start searching")
    bot.send_message(call.from_user.id, text="Start?", reply_markup=markup)
    bot.set_state(call.from_user.id, UserData.api_response, call.from_user.id)
    ProcessData.save_data(user_id=call.from_user.id, dict_key="photos_amount", chat_id=call.from_user.id, data=photos)

@bot.callback_query_handler(func= lambda call: call.data.startswith("show_photo"))
def show_extra_photos(call: CallbackQuery) -> None:
    logger.info("SHOWING EXTRA PHOTOS")
    property_id = call.data.split("_")[2]
    with bot.retrieve_data(call.from_user.id, call.from_user.id) as data:
        photos_amount = data["photos_amount"]

    photos = HotelPhotos_methods.select_photo_links(hotel_id=property_id, photo_amount=photos_amount)
    bot.send_media_group(call.from_user.id, photos)


from pdfBuilder import PdfBuilder
import os

# here we define the commands to be used
# commands are passed to subprocess.Popen which prefers a list of
# arguments to a string
PDFLATEX = ["pdflatex", "-interaction=nonstopmode", "-synctex=1"]
BIBTEX = ["bibtex"]

class thesisBuilder(PdfBuilder):
    def __init__(self, *args):
        super(thesisBuilder, self).__init__(*args)

        # now we do the initialization for this builder
        self.name = "thesisBuilder"

    def commands(self):
        self.display("\n\nthesisBuilder: ")

        # first run of pdflatex
        # this tells LaTeXTools to run:
        #  pdflatex -interaction=nonstopmode -synctex=1 tex_root
        # note that we append the base_name of the file to the command here
        yield(PDFLATEX + [self.base_name], "Running pdflatex...")
        #yield(PDFLATEX + [thesis.tex], "Running pdflatex...")

        # LaTeXTools has run pdflatex and returned control to the builder
        # here we just add text saying the step is done, to give some feedback
        self.display("done.\n")

        # now run bibtex
        chapters =   ["chapters/cameroontrust/cameroontrust_paper",
                     "chapters/conclusion/conclusion",
                     "chapters/congogbv/congogbv",
                     "chapters/introduction/introduction",
                     "chapters/n2a_impact/n2a_impact",
                     "chapters/slfootball/slfootball",
                     "chapters/acknowledgements/acknowledgements",
                     "chapters/summary_dutch/summary_dutch",
                     "chapters/summary_english/summary_english"
                     ]
        self.display("Running bibtex...\n")
        for file in chapters:
            yield(BIBTEX + [file],"  (%s)\n" % file)
            self.display("done.\n")

        # second run of pdflatex
        yield(
            PDFLATEX + [self.base_name],
            #PDFLATEX + [thesis.tex],
            "Running pdflatex again..."
        )

        self.display("done!\n")

        # third run of pdflatex
        yield(
            PDFLATEX + [self.base_name],
            #PDFLATEX + [self.base_name]
            "Running pdflatex for the last time..."
        )

        self.display("done.\n")


import os

from thumbor.optimizers import BaseOptimizer

class Optimizer(BaseOptimizer):

    def should_run(self, image_extension, buffer):
        return 'jpg' in image_extension or 'jpeg' in image_extension

    def optimize(self, buffer, input_file, output_file):
        jpegtran_path = self.context.config.JPEGTRAN_PATH
        command = '%s -copy all -optimize %s-outfile %s %s ' % (
            jpegtran_path,
            '-progressive ' if self.context.config.PROGRESSIVE_JPEG else '',
            output_file,
            input_file,
        )
        os.system(command)


import json
import random

class WordChain:
    _source = "wordlist.json"

    def __init__(self, match_length: int = 1):
        with open(self._source) as words:
            wordlist = json.load(words)
            initial_word = random.choice(wordlist)
            self.wordlist = set(wordlist)
        self.chain = [initial_word]
        self.match_length = match_length

    def length(self):
        return len(self.chain)

    def append(self, word: str):
        if word not in self.wordlist:
            raise Exception("Incorrect word.")
        if word in self.chain:
            raise Exception("Word already used.")
        if self.chain[-1][-self.match_length:] != word[:self.match_length]:
            raise Exception("Cannot chain word to previous one")
        self.chain.append(word)


import pytest

from fastapi.testclient import TestClient
from experiments.class_depends import app

client = TestClient(app)

def test_hello_class_attr():
    resp = client.get("/class_attr")
    assert resp.status_code == 200
    assert resp.json() == "hello"

def test_init_attr():
    resp = client.get("/init_attr")
    assert resp.status_code == 200
    assert resp.json() == 10

@pytest.mark.xfail
def test_class_method_depends():
    """does not work"""
    resp = client.get("/class_method_depends?names=bob&names=joe")
    assert resp.status_code == 200
    assert resp.json() == "hello bob, joe"

def test_class_method_and_depends():
    resp = client.get("/class_method_and_depends?names=bob&names=joe")
    assert resp.status_code == 200
    assert resp.json() == "hello bob, joe"


# -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.

import os
from os.path import expanduser
import sys
import glob
import atexit
import logging
import readline
import traceback

from viper.common.out import print_error
# from viper.common.out import print_output  # currently not used
from viper.common.colors import cyan, magenta, white, bold, blue, red
from viper.common.version import __version__
from viper.core.session import __sessions__
from viper.core.plugins import __modules__
from viper.core.project import __project__, get_project_list
from viper.core.ui.commands import Commands
from viper.core.database import Database
from viper.core.config import __config__, console_output

log = logging.getLogger("viper")

cfg = __config__
cfg.parse_http_client()

def logo():
    print("""         _
        (_)
   _   _ _ ____  _____  ____
  | | | | |  _ \\| ___ |/ ___)
   \\ V /| | |_| | ____| |
    \\_/ |_|  __/|_____)_| v{}
          |_|
    """.format(__version__))

    db = Database()
    count = db.get_sample_count()

    try:
        db.find("all")
    except Exception:
        sys.exit()

    if __project__.name:
        name = __project__.name
    else:
        name = "default"

    print(magenta("You have " + bold(count)) +
          magenta(" files in your " + bold(name)) +
          magenta(" repository."))

    modules_count = len(__modules__)
    if modules_count == 0:
        print("")
        print(red(bold("You do not have any modules installed!")))
        print(red("If you wish to download community modules from GitHub run:"))
        print(red(bold("    update-modules")))
    else:
        print(magenta("You have " + bold(modules_count)) +
              magenta(" modules installed."))

class Console(object):

    def __init__(self):
        # This will keep the main loop active as long as it's set to True.
        self.active = True
        self.cmd = Commands()

    def parse(self, data):
        root = ""
        args = []

        # Split words by white space.
        words = data.split()
        # First word is the root command.
        root = words[0]

        # If there are more words, populate the arguments list.
        if len(words) > 1:
            args = words[1:]

        return (root, args)

    def keywords(self, data):
        # Check if $self is in the user input data.
        if "$self" in data:
            # Check if there is an open session.
            if __sessions__.is_set():
                # If a session is opened, replace $self with the path to
                # the file which is currently being analyzed.
                data = data.replace("$self", __sessions__.current.file.path)
            else:
                print("No open session")
                return None

        return data

    def stop(self):
        # Stop main loop.
        self.active = False

    def start(self):
        # log start
        log.info("Starting viper")

        # Logo.
        logo()

        # Setup shell auto-complete.
        def complete(text, state):
            # filesystem path completion only makes sense for a few commands/modules
            fs_path_completion = False

            # clean up user input so far (no leading/trailing/duplicate spaces)
            line = " ".join(readline.get_line_buffer().split())
            words = line.split(" ")  # split words; e.g. store -f /tmp -> ["store", "-f", "/tmp"]

            if words[0] in [i for i in self.cmd.commands]:
                # handle completion for commands

                # enable filesystem path completion for certain commands (e.g. export, store)
                if words[0] in [x for x in self.cmd.commands if self.cmd.commands[x]["fs_path_completion"]]:
                    fs_path_completion = True

                options = [key for key in self.cmd.commands[words[0]]["parser_args"]]

                # enable tab completion for projects --switch
                if words[0] == "projects":
                    if "--switch" in words or "-s" in words:
                        options += get_project_list()

                        # enable tab completion for copy (list projects)
                if words[0] == "copy":
                    options += get_project_list()

                completions = [i for i in options if i.startswith(text) and i not in words]

            elif words[0] in [i for i in __modules__]:
                # handle completion for modules
                if len(words) == 1:
                    # only the module name is give so far - present all args and the subparsers (if any)
                    options = [key for key in __modules__[words[0]]["parser_args"]]
                    options += [key for key in __modules__[words[0]]["subparser_args"]]

                elif len(words) == 2:
                    # 1 complete word and one either complete or incomplete that specifies the subparser or an arg
                    if words[1] in list(__modules__[words[0]]["parser_args"]):
                        # full arg for a module is given
                        options = [key for key in __modules__[words[0]]["parser_args"]]

                    elif words[1] in list(__modules__[words[0]]["subparser_args"]):
                        # subparser is specified - get all subparser args
                        options = [key for key in __modules__[words[0]]["subparser_args"][words[1]]]

                    else:
                        options = [key for key in __modules__[words[0]]["parser_args"]]
                        options += [key for key in __modules__[words[0]]["subparser_args"]]

                else:  # more that 2 words
                    if words[1] in list(__modules__[words[0]]["subparser_args"]):
                        # subparser is specified - get all subparser args
                        options = [key for key in __modules__[words[0]]["subparser_args"][words[1]]]
                    else:
                        options = [key for key in __modules__[words[0]]["parser_args"]]

                completions = [i for i in options if i.startswith(text) and i not in words]

            else:
                # initial completion for both commands and modules
                completions = [i for i in self.cmd.commands if i.startswith(text)]
                completions += [i for i in __modules__ if i.startswith(text)]

            if state < len(completions):
                return completions[state]

            if fs_path_completion:
                # completion for paths only if it makes sense
                if text.startswith("~"):
                    text = "{0}{1}".format(expanduser("~"), text[1:])
                return (glob.glob(text + "*") + [None])[state]

            return

        # Auto-complete on tabs.
        readline.set_completer_delims(" \t\n;")
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete)

        # Save commands in history file.
        def save_history(path):
            readline.write_history_file(path)

        # If there is an history file, read from it and load the history
        # so that they can be loaded in the shell.
        # Now we are storing the history file in the local project folder
        history_path = os.path.join(__project__.path, "history")

        if os.path.exists(history_path):
            readline.read_history_file(history_path)

        readline.set_history_length(10000)

        # Register the save history at program"s exit.
        atexit.register(save_history, path=history_path)

        # Main loop.
        while self.active:
            # If there is an open session, we include the path to the opened
            # file in the shell prompt.
            # TODO: perhaps this block should be moved into the session so that
            # the generation of the prompt is done only when the session"s
            # status changes.
            prefix = ""
            if __project__.name:
                prefix = bold(cyan(__project__.name)) + " "

            if __sessions__.is_set():
                stored = ""
                filename = ""
                if __sessions__.current.file:
                    filename = __sessions__.current.file.name
                    if not Database().find(key="sha256", value=__sessions__.current.file.sha256):
                        stored = magenta(" [not stored]", True)

                misp = ""
                if __sessions__.current.misp_event:
                    misp = " [MISP"
                    if __sessions__.current.misp_event.event.id:
                        misp += " {}".format(__sessions__.current.misp_event.event.id)
                    else:
                        misp += " New Event"
                    if __sessions__.current.misp_event.off:
                        misp += " (Offline)"
                    misp += "]"

                prompt = (prefix + cyan("viper ", True) +
                          white(filename, True) + blue(misp, True) + stored + cyan(" > ", True))
            # Otherwise display the basic prompt.
            else:
                prompt = prefix + cyan("viper > ", True)

            # force str (Py3) / unicode (Py2) for prompt
            if sys.version_info <= (3, 0):
                prompt = prompt.encode("utf-8")
            else:
                prompt = str(prompt)

            # Wait for input from the user.
            try:
                data = input(prompt).strip()
            except KeyboardInterrupt:
                print("")
            # Terminate on EOF.
            except EOFError:
                self.stop()
                print("")
                continue
            # Parse the input if the user provided any.
            else:
                # If there are recognized keywords, we replace them with
                # their respective value.
                data = self.keywords(data)
                # Skip if the input is empty.
                if not data:
                    continue

                # Check for output redirection
                # If there is a > in the string, we assume the user wants to output to file.
                if ">" in data:
                    data, console_output["filename"] = data.split(">", 1)
                    if ";" in console_output["filename"]:
                        console_output["filename"], more_commands = console_output["filename"].split(";", 1)
                        data = "{};{}".format(data, more_commands)
                    print("Writing output to {0}".format(console_output["filename"].strip()))

                # If the input starts with an exclamation mark, we treat the
                # input as a bash command and execute it.
                # At this point the keywords should be replaced.
                if data.startswith("!"):
                    os.system(data[1:])
                    continue

                # Try to split commands by ; so that you can sequence multiple
                # commands at once.
                # For example:
                # viper > find name *.pdf; open --last 1; pdf id
                # This will automatically search for all PDF files, open the first entry
                # and run the pdf module against it.
                split_commands = data.split(";")
                for split_command in split_commands:
                    split_command = split_command.strip()
                    if not split_command:
                        continue

                    # If it's an internal command, we parse the input and split it
                    # between root command and arguments.
                    root, args = self.parse(split_command)

                    # Check if the command instructs to terminate.
                    if root in ("exit", "quit"):
                        self.stop()
                        continue

                    try:
                        # If the root command is part of the embedded commands list we
                        # execute it.
                        if root in self.cmd.commands:
                            self.cmd.commands[root]["obj"](*args)
                            del(self.cmd.output[:])
                        # If the root command is part of loaded modules, we initialize
                        # the module and execute it.
                        elif root in __modules__:
                            module = __modules__[root]["obj"]()
                            module.set_commandline(args)
                            module.run()

                            if cfg.modules.store_output and __sessions__.is_set():
                                try:
                                    Database().add_analysis(__sessions__.current.file.sha256, split_command, module.output)
                                except Exception:
                                    pass
                            del(module.output[:])
                        else:
                            print("Command not recognized.")
                    except KeyboardInterrupt:
                        pass
                    except Exception:
                        print_error("The command {0} raised an exception:".format(bold(root)))
                        traceback.print_exc()

                console_output["filename"] = None   # reset output to stdout


import os
import sys
import urllib
from PIL import Image

from bfs import proceed_bfs
from straightforward import proceed_straightforward

def proceed_from_url(url):
    res_default, res_bfs = "", ""
    try:
        file_name = url.split("/")[-1]
        urllib.urlretrieve(url, file_name)

        img = Image.open(file_name)

        res_default = proceed_straightforward(img)
        res_bfs = proceed_bfs(img)
    except:
        res_default, res_bfs = "invalid url", "invalid url"
    finally:
        try:
            os.remove(file_name)
        except:
            pass

    return {'default': res_default, 'bfs': res_bfs}

Some projects/Lun.ua - test/Project/classifier/proceed.py


import functools
import weakref

import numpy as np

from tensorflow.python.util import nest

def get_source_inputs(tensor, layer=None, node_index=None):
  """Returns the list of input tensors necessary to compute `tensor`.

  Output will always be a list of tensors
  (potentially with 1 element).

  Args:
      tensor: The tensor to start from.
      layer: Origin layer of the tensor. Will be
          determined via tensor._keras_history if not provided.
      node_index: Origin node index of the tensor.

  Returns:
      List of input tensors.
  """
  if not hasattr(tensor, '_keras_history'):
    return tensor

  if layer is None or node_index:
    layer, node_index, _ = tensor._keras_history
  if not layer._inbound_nodes:
    return [tensor]
  else:
    node = layer._inbound_nodes[node_index]
    if node.is_input:
      # Reached an Input layer, stop recursion.
      return nest.flatten(node.input_tensors)
    else:
      source_tensors = []
      for layer, node_index, _, tensor in node.iterate_inbound():
        previous_sources = get_source_inputs(tensor, layer, node_index)
        # Avoid input redundancy.
        for x in previous_sources:
          if all(x is not t for t in source_tensors):
            source_tensors.append(x)
      return source_tensors

def validate_string_arg(input_data,
                        allowable_strings,
                        layer_name,
                        arg_name,
                        allow_none=False,
                        allow_callables=False):
  """Validates the correctness of a string-based arg."""
  if allow_none and input_data is None:
    return
  elif allow_callables and callable(input_data):
    return
  elif isinstance(input_data, str) and input_data in allowable_strings:
    return
  else:
    allowed_args = '`None`, ' if allow_none else ''
    allowed_args += 'a `Callable`, ' if allow_callables else ''
    allowed_args += 'or one of the following values: %s' % (allowable_strings,)
    raise ValueError(('The %s argument of layer %s received an invalid '
                      'value %s. Allowed values are: %s.') %
                     (arg_name, layer_name, input_data, allowed_args))

def count_params(weights):
  """Count the total number of scalars composing the weights.

  Args:
      weights: An iterable containing the weights on which to compute params

  Returns:
      The total number of scalars composing the weights
  """
  unique_weights = {id(w): w for w in weights}.values()
  weight_shapes = [w.shape.as_list() for w in unique_weights]
  standardized_weight_shapes = [
      [0 if w_i is None else w_i for w_i in w] for w in weight_shapes
  ]
  return int(sum(np.prod(p) for p in standardized_weight_shapes))

def print_summary(model, line_length=None, positions=None, print_fn=None):
  """Prints a summary of a model.

  Args:
      model: Keras model instance.
      line_length: Total length of printed lines
          (e.g. set this to adapt the display to different
          terminal window sizes).
      positions: Relative or absolute positions of log elements in each line.
          If not provided, defaults to `[.33, .55, .67, 1.]`.
      print_fn: Print function to use.
          It will be called on each line of the summary.
          You can set it to a custom function
          in order to capture the string summary.
          It defaults to `print` (prints to stdout).
  """
  if print_fn is None:
    print_fn = print

  if model.__class__.__name__ == 'Sequential':
    sequential_like = True
  elif not model._is_graph_network:
    # We treat subclassed models as a simple sequence of layers, for logging
    # purposes.
    sequential_like = True
  else:
    sequential_like = True
    nodes_by_depth = model._nodes_by_depth.values()
    nodes = []
    for v in nodes_by_depth:
      if (len(v) > 1) or (len(v) == 1 and
                          len(nest.flatten(v[0].keras_inputs)) > 1):
        # if the model has multiple nodes
        # or if the nodes have multiple inbound_layers
        # the model is no longer sequential
        sequential_like = False
        break
      nodes += v
    if sequential_like:
      # search for shared layers
      for layer in model.layers:
        flag = False
        for node in layer._inbound_nodes:
          if node in nodes:
            if flag:
              sequential_like = False
              break
            else:
              flag = True
        if not sequential_like:
          break

  if sequential_like:
    line_length = line_length or 65
    positions = positions or [.45, .85, 1.]
    if positions[-1] <= 1:
      positions = [int(line_length * p) for p in positions]
    # header names for the different log elements
    to_display = ['Layer (type)', 'Output Shape', 'Param #']
  else:
    line_length = line_length or 98
    positions = positions or [.33, .55, .67, 1.]
    if positions[-1] <= 1:
      positions = [int(line_length * p) for p in positions]
    # header names for the different log elements
    to_display = ['Layer (type)', 'Output Shape', 'Param #', 'Connected to']
    relevant_nodes = []
    for v in model._nodes_by_depth.values():
      relevant_nodes += v

  def print_row(fields, positions):
    line = ''
    for i in range(len(fields)):
      if i > 0:
        line = line[:-1] + ' '
      line += str(fields[i])
      line = line[:positions[i]]
      line += ' ' * (positions[i] - len(line))
    print_fn(line)

  print_fn('Model: "{}"'.format(model.name))
  print_fn('_' * line_length)
  print_row(to_display, positions)
  print_fn('=' * line_length)

  def print_layer_summary(layer):
    """Prints a summary for a single layer.

    Args:
        layer: target layer.
    """
    try:
      output_shape = layer.output_shape
    except AttributeError:
      output_shape = 'multiple'
    except RuntimeError:  # output_shape unknown in Eager mode.
      output_shape = '?'
    name = layer.name
    cls_name = layer.__class__.__name__
    if not layer.built and not getattr(layer, '_is_graph_network', False):
      # If a subclassed model has a layer that is not called in Model.call, the
      # layer will not be built and we cannot call layer.count_params().
      params = '0 (unused)'
    else:
      params = layer.count_params()
    fields = [name + ' (' + cls_name + ')', output_shape, params]
    print_row(fields, positions)

  def print_layer_summary_with_connections(layer):
    """Prints a summary for a single layer (including topological connections).

    Args:
        layer: target layer.
    """
    try:
      output_shape = layer.output_shape
    except AttributeError:
      output_shape = 'multiple'
    connections = []
    for node in layer._inbound_nodes:
      if relevant_nodes and node not in relevant_nodes:
        # node is not part of the current network
        continue

      for inbound_layer, node_index, tensor_index, _ in node.iterate_inbound():
        connections.append('{}[{}][{}]'.format(inbound_layer.name, node_index,
                                               tensor_index))

    name = layer.name
    cls_name = layer.__class__.__name__
    if not connections:
      first_connection = ''
    else:
      first_connection = connections[0]
    fields = [
        name + ' (' + cls_name + ')', output_shape,
        layer.count_params(), first_connection
    ]
    print_row(fields, positions)
    if len(connections) > 1:
      for i in range(1, len(connections)):
        fields = ['', '', '', connections[i]]
        print_row(fields, positions)

  layers = model.layers
  for i in range(len(layers)):
    if sequential_like:
      print_layer_summary(layers[i])
    else:
      print_layer_summary_with_connections(layers[i])
    if i == len(layers) - 1:
      print_fn('=' * line_length)
    else:
      print_fn('_' * line_length)

  if hasattr(model, '_collected_trainable_weights'):
    trainable_count = count_params(model._collected_trainable_weights)
  else:
    trainable_count = count_params(model.trainable_weights)

  non_trainable_count = count_params(model.non_trainable_weights)

  print_fn('Total params: {:,}'.format(trainable_count + non_trainable_count))
  print_fn('Trainable params: {:,}'.format(trainable_count))
  print_fn('Non-trainable params: {:,}'.format(non_trainable_count))
  print_fn('_' * line_length)

def convert_dense_weights_data_format(dense,
                                      previous_feature_map_shape,
                                      target_data_format='channels_first'):
  """Utility useful when changing a convnet's `data_format`.

  When porting the weights of a convnet from one data format to the other,
  if the convnet includes a `Flatten` layer
  (applied to the last convolutional feature map)
  followed by a `Dense` layer, the weights of that `Dense` layer
  should be updated to reflect the new dimension ordering.

  Args:
      dense: The target `Dense` layer.
      previous_feature_map_shape: A shape tuple of 3 integers,
          e.g. `(512, 7, 7)`. The shape of the convolutional
          feature map right before the `Flatten` layer that
          came before the target `Dense` layer.
      target_data_format: One of "channels_last", "channels_first".
          Set it "channels_last"
          if converting a "channels_first" model to "channels_last",
          or reciprocally.
  """
  assert target_data_format in {'channels_last', 'channels_first'}
  kernel, bias = dense.get_weights()
  for i in range(kernel.shape[1]):
    if target_data_format == 'channels_first':
      c, h, w = previous_feature_map_shape
      original_fm_shape = (h, w, c)
      ki = kernel[:, i].reshape(original_fm_shape)
      ki = np.transpose(ki, (2, 0, 1))  # last -> first
    else:
      h, w, c = previous_feature_map_shape
      original_fm_shape = (c, h, w)
      ki = kernel[:, i].reshape(original_fm_shape)
      ki = np.transpose(ki, (1, 2, 0))  # first -> last
    kernel[:, i] = np.reshape(ki, (np.prod(previous_feature_map_shape),))
  dense.set_weights([kernel, bias])

def is_builtin_layer(layer):
  if not getattr(layer, '_keras_api_names', None):
    return False

  # Subclasses of `Layer` that are not exported inherit the export name
  # of the base layer class.
  return (layer._keras_api_names != ('keras.layers.Layer',) and
          layer._keras_api_names_v1 != ('keras.layers.Layer',))

def cached_per_instance(f):
  """Lightweight decorator for caching lazily constructed properties.

  When to use:
  This decorator provides simple caching with minimal overhead. It is designed
  for properties which are expensive to compute and static over the life of a
  class instance, and provides no mechanism for cache invalidation. Thus it is
  best suited for lazily exposing derived properties of other static data.

  For classes with custom getattr / setattr behavior (such as trackable
  objects), storing cache results as object attributes is not performant.
  Instead, a specialized cache can significantly reduce property lookup
  overhead. (While still allowing the decorated property to be lazily computed.)
  Consider the following class:

  ```
  class MyClass(object):
    def __setattr__(self, key, value):
      # Some expensive class specific code
      # ...
      # ...

      super(MyClass, self).__setattr__(key, value)

    @property
    def thing(self):
      # `thing` is expensive to compute (and may not even be requested), so we
      # want to lazily compute it and then cache it.
      output = getattr(self, '_thing', None)
      if output is None:
        self._thing = output = compute_thing(self)
      return output
  ```

  It's also worth noting that ANY overriding of __setattr__, even something as
  simple as:
  ```
    def __setattr__(self, key, value):
      super(MyClass, self).__setattr__(key, value)
  ```

  Slows down attribute assignment by nearly 10x.

  By contrast, replacing the definition of `thing` with the following sidesteps
  the expensive __setattr__ altogether:

  '''
  @property
  @tracking.cached_per_instance
  def thing(self):
    # `thing` is expensive to compute (and may not even be requested), so we
    # want to lazily compute it and then cache it.
    return compute_thing(self)
  '''

  Performance:
  The overhead for this decorator is ~0.4 us / call. A much lower overhead
  implementation (~0.085 us / call) can be achieved by using a custom dict type:

  ```
  def dict_based_cache(f):
    class Cache(dict):
      __slots__ = ()
      def __missing__(self, key):
        self[key] = output = f(key)
        return output

    return property(Cache().__getitem__)
  ```

  However, that implementation holds class instances as keys, and as a result
  blocks garbage collection. (And modifying it to use weakref's as keys raises
  the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary
  implementation below turns out to be more prudent.

  Args:
    f: The function to cache.

  Returns:
    f decorated with simple caching behavior.
  """

  cache = weakref.WeakKeyDictionary()

  @functools.wraps(f)
  def wrapped(item):
    output = cache.get(item)
    if output is None:
      cache[item] = output = f(item)
    return output

  wrapped.cache = cache
  return wrapped

def filter_empty_layer_containers(layer_list):
  """Filter out empty Layer-like containers and uniquify."""
  # TODO(b/130381733): Make this an attribute in base_layer.Layer.
  existing = set()
  to_visit = layer_list[::-1]
  while to_visit:
    obj = to_visit.pop()
    if id(obj) in existing:
      continue
    existing.add(id(obj))
    if hasattr(obj, '_is_layer') and not isinstance(obj, type):
      yield obj
    else:
      sub_layers = getattr(obj, 'layers', None) or []

      # Trackable data structures will not show up in ".layers" lists, but
      # the layers they contain will.
      to_visit.extend(sub_layers[::-1])


import re

from respect_validation.Rules.AbstractRule import AbstractRule

class Cpf(AbstractRule):

    def validate(self, input_val):
        c = str(re.sub(r'[^0-9]', "", input_val))

        if len(c) != 11 or re.findall(r'^'+c[0]+'{11}$', c) or c == '01234567890':
            return False

        n = 0
        i = 0
        for s in reversed(range(2, 11)):
            n += int(c[i]) * s
            i += 1
        n = n % 11

        if int(c[9]) != (0 if n < 2 else (11 - n)):
            return False

        n = 0
        i = 0
        for s in reversed(range(2, 12)):
            n += int(c[i]) * s
            i += 1
        n = n % 11

        check = 0 if n < 2 else (11 - n)

        return int(c[10]) == check


import aocd, re

data = f"\n{aocd.get_data(year=2021, day=3)}"

most = lambda d, n: int(len(re.findall(f"\n.{{{n}}}1", d)) > (d.count("\n") / 2))

# Part 1
γ = int("".join([str(most(data, n)) for n in range(len(data.split("\n")[1]))]), 2)
ε = int("".join([str(1 - most(data, n)) for n in range(len(data.split("\n")[1]))]), 2)
print(γ * ε)


from gpiozero import PWMLED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep
import RPi.GPIO as GPIO

class Air:
    relays = PiGPIOFactory(host='192.168.1.20') #RELAY PINS
    air_pin = PWMLED(18, pin_factory=relays)

    def __init__(self):
        self.data = []

    def blow(self, time):
        relays = self.relays
        air_pin = self.air_pin
        air_pin.value = 1
        print("blow")
        print(time)
        sleep(time)
        air_pin.value = 0

GPIO.cleanup()


import sys
sys.path.append('..')
from MobileNetV2 import MobileNetV2
from torch.autograd import Variable
import torch.nn as nn
import torch
from data.config import cfg
from gcn.st_gcn import Model_G

class EventDetector(nn.Module):
    def __init__(self, pretrain, width_mult, lstm_layers, lstm_hidden, bidirectional=True, dropout=True):
        super(EventDetector, self).__init__()
        self.width_mult = width_mult
        self.lstm_layers = lstm_layers
        self.lstm_hidden = lstm_hidden
        self.bidirectional = bidirectional
        self.dropout = dropout
        ######for gcn######
        self.in_channels = 3
        self.num_class = 9
        self.edge_importance_weighting = True
        self.gcn_feature = 128
        self.graph_args = {'layout': 'customer settings','strategy': 'spatial', 'max_hop': 1, 'dilation': 1}
        self.st_gcn_net = Model_G(self.in_channels, self.num_class,self.edge_importance_weighting,self.graph_args)
        net = MobileNetV2(width_mult=width_mult)
        state_dict_mobilenet = torch.load('../mobilenet_v2.pth.tar')
        state_dict_st_gcn_net = torch.load('../gcn_spotting_net_8000.pth.tar')
        if pretrain:
            net.load_state_dict(state_dict_mobilenet)
            self.st_gcn_net.load_state_dict(state_dict_st_gcn_net['model_state_dict'])

        self.cnn = nn.Sequential(*list(net.children())[0][:19])
        self.rnn = nn.LSTM(int(1280*width_mult if width_mult > 1.0 else 1280),
                           self.lstm_hidden, self.lstm_layers,
                           batch_first=True, bidirectional=bidirectional)
        if self.bidirectional:
            if cfg.FRAME_13_OPEN:
                self.lin = nn.Linear(2*self.lstm_hidden+self.gcn_feature, 14)
            else:
                self.lin = nn.Linear(2*self.lstm_hidden+self.gcn_feature, 9)
        else:
            if cfg.FRAME_13_OPEN:
                self.lin = nn.Linear(self.lstm_hidden+self.gcn_feature, 14)
            else:
                self.lin = nn.Linear(self.lstm_hidden+self.gcn_feature, 9)
        if self.dropout:
            self.drop = nn.Dropout(0.5)

    def init_hidden(self, batch_size):
        if self.bidirectional:
            return (Variable(torch.zeros(2*self.lstm_layers, batch_size, self.lstm_hidden).cuda(), requires_grad=True),
                    Variable(torch.zeros(2*self.lstm_layers, batch_size, self.lstm_hidden).cuda(), requires_grad=True))
        else:
            return (Variable(torch.zeros(self.lstm_layers, batch_size, self.lstm_hidden).cuda(), requires_grad=True),
                    Variable(torch.zeros(self.lstm_layers, batch_size, self.lstm_hidden).cuda(), requires_grad=True))

    def forward(self, x, k,lengths=None):
        k = self.st_gcn_net.extract_feature(k)
        batch_size, timesteps, C, H, W = x.size()
        self.hidden = self.init_hidden(batch_size)

        # CNN forward
        c_in = x.view(batch_size * timesteps, C, H, W)
        c_out = self.cnn(c_in)
        c_out = c_out.mean(3).mean(2)
        if self.dropout:
            c_out = self.drop(c_out)

        # LSTM forward
        r_in = c_out.view(batch_size, timesteps, -1)
        r_out, states = self.rnn(r_in, self.hidden)
        # print("after lstm")
        # print(r_out.shape)
        # print(k.shape)
        concat_out = torch.cat((r_out, k), 2)
        out = self.lin(concat_out)
        if cfg.FRAME_13_OPEN:
            out = out.view(batch_size*timesteps, 14)
        else:
            out = out.view(batch_size*timesteps, 9)

        return out


"""
Link: https://leetcode.com/problems/linked-list-cycle/
Topics: Linked List, Hash Table, Two Pointers
"""

from typing import Optional

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def has_cycle(self, head: Optional[ListNode]) -> bool:

        visited_node_values = set()

        while head:
            if head in visited_node_values:
                return True
            else:
                visited_node_values.add(head)
                head = head.next

        return False


# Exercício do livro Introdução à Programação com Python
# Código criado por Davi Lopes para aprendizagem  a partir de situações
# criadas no livro acima mencionado

x = 0
while x <= 10:
    if ( x % 3 == 0):
        print(x)
    x = x + 1
print("Programa encerrado")

5.4 escreva os 10 primeiros múltiplos de 3.py