from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import type_spec as type_spec_module
from tensorflow.python.ops import array_ops
from tensorflow.python.util import nest
from tensorflow.python.util import object_identity

# pylint: disable=g-classes-have-attributes

_KERAS_TENSORS_ENABLED = False

def enable_keras_tensors():
  """Enable using KerasTensors in Keras's functional API."""
  global _KERAS_TENSORS_ENABLED
  _KERAS_TENSORS_ENABLED = True

def disable_keras_tensors():
  """Disable using KerasTensors in Keras's functional API."""
  global _KERAS_TENSORS_ENABLED
  _KERAS_TENSORS_ENABLED = False

def keras_tensors_enabled():
  """Return a bool specifying if KerasTensors are enabled."""
  return _KERAS_TENSORS_ENABLED and ops.executing_eagerly_outside_functions()

class KerasTensor(object):
  """A representation of a Keras in/output during Functional API construction.

  `KerasTensor`s are tensor-like objects that represent the symbolic inputs
  and outputs of Keras layers during Functional model construction. They are
  comprised of the `tf.TypeSpec` of the (Composite)Tensor that will be
  consumed/produced in the corresponding location of the Functional model.

  KerasTensors are intended as a private API, so users should never need to
  directly instantiate `KerasTensor`s.

  **Building Functional Models with KerasTensors**
  `tf.keras.Input` produces `KerasTensor`s that represent the symbolic inputs
  to your model.

  Passing a `KerasTensor` to a `tf.keras.Layer` `__call__` lets the layer know
  that you are building a Functional model. The layer __call__ will
  infer the output signature and return `KerasTensor`s with `tf.TypeSpec`s
  corresponding to the symbolic outputs of that layer call. These output
  `KerasTensor`s will have all of the internal KerasHistory metadata attached
  to them that Keras needs to construct a Functional Model.

  Currently, layers infer the output signature by:
    * creating a scratch `FuncGraph`
    * making placeholders in the scratch graph that match the input typespecs
    * Calling `layer.call` on these placeholders
    * extracting the signatures of the outputs before clearing the scratch graph

  (Note: names assigned to KerasTensors by this process are not guaranteed to
  be unique, and are subject to implementation details).

  `tf.nest` methods are used to insure all of the inputs/output data
  structures get maintained, with elements swapped between KerasTensors and
  placeholders.

  In rare cases (such as when directly manipulating shapes using Keras layers),
  the layer may be able to partially infer the value of of the output in
  addition to just inferring the signature.
  When this happens, the returned KerasTensor will also contain the inferred
  value information. Follow-on layers can use this information.
  during their own output signature inference.
  E.g. if one layer produces a symbolic `KerasTensor` that the next layer uses
  as the shape of its outputs, partially knowing the value helps infer the
  output shape.

  **Automatically converting TF APIs to layers**:
  If you passing a `KerasTensor` to a TF API that supports dispatching,
  Keras will automatically turn that API call into a lambda
  layer in the Functional model, and return KerasTensors representing the
  symbolic outputs.

  Most TF APIs that take only tensors as input and produce output tensors
  will support dispatching.

  Calling a `tf.function` does not support dispatching, so you cannot pass
  `KerasTensor`s as inputs to a `tf.function`.

  Higher-order apis that take methods which produce tensors (e.g. `tf.while`,
  `tf.map_fn`, `tf.cond`) also do not currently support dispatching. So, you
  cannot directly pass KerasTensors as inputs to these APIs either. If you
  want to use these APIs inside of a Functional model, you must put them inside
  of a custom layer.

  Args:
    type_spec: The `tf.TypeSpec` for the symbolic input created by
      `tf.keras.Input`, or symbolically inferred for the output
      during a symbolic layer `__call__`.
    inferred_value: (Optional) a non-symbolic static value, possibly partially
      specified, that could be symbolically inferred for the outputs during
      a symbolic layer `__call__`. This will generally only happen when
      grabbing and manipulating `tf.int32` shapes directly as tensors.
      Statically inferring values in this way and storing them in the
      KerasTensor allows follow-on layers to infer output signatures
      more effectively. (e.g. when using a symbolic shape tensor to later
      construct a tensor with that shape).
    name: (optional) string name for this KerasTensor. Names automatically
      generated by symbolic layer `__call__`s are not guaranteed to be unique,
      and are subject to implementation details.
  """

  def __init__(self, type_spec, inferred_value=None, name=None):
    """Constructs a KerasTensor."""
    if not isinstance(type_spec, type_spec_module.TypeSpec):
      raise ValueError('KerasTensors must be constructed with a `tf.TypeSpec`.')

    self._type_spec = type_spec
    self._inferred_value = inferred_value
    self._name = name

  @property
  def type_spec(self):
    """Returns the `tf.TypeSpec` symbolically inferred for this Keras output."""
    return self._type_spec

  @property
  def shape(self):
    """Returns the `TensorShape` symbolically inferred for this Keras output."""
    # TODO(kaftan): This is only valid for normal/sparse/ragged tensors.
    # may need to raise an error when it's not valid for a type_spec,
    # but some keras code (e.g. build-related stuff) will likely fail when
    # it can't access shape or dtype
    return self._type_spec._shape  # pylint: disable=protected-access

  def get_shape(self):
    return self.shape

  def __len__(self):
    raise TypeError('Keras symbolic inputs/outputs do not '
                    'implement `__len__`. You may be '
                    'trying to pass Keras symbolic inputs/outputs '
                    'to a TF API that does not register dispatching, '
                    'preventing Keras from automatically '
                    'converting the API call to a lambda layer '
                    'in the Functional Model. This error will also get raised '
                    'if you try asserting a symbolic input/output directly.')

  @property
  def op(self):
    raise TypeError('Keras symbolic inputs/outputs do not '
                    'implement `op`. You may be '
                    'trying to pass Keras symbolic inputs/outputs '
                    'to a TF API that does not register dispatching, '
                    'preventing Keras from automatically '
                    'converting the API call to a lambda layer '
                    'in the Functional Model.')

  def __hash__(self):
    raise TypeError('Tensors are unhashable. (%s)'
                    'Instead, use tensor.ref() as the key.' % self)

  # Note: This enables the KerasTensor's overloaded "right" binary
  # operators to run when the left operand is an ndarray, because it
  # accords the Tensor class higher priority than an ndarray, or a
  # numpy matrix.
  # In the future explore chaning this to using numpy's __numpy_ufunc__
  # mechanism, which allows more control over how Tensors interact
  # with ndarrays.
  __array_priority__ = 100

  def __array__(self):
    raise TypeError(
        'Cannot convert a symbolic Keras input/output to a numpy array. '
        'This error may indicate that you\'re trying to pass a symbolic value '
        'to a NumPy call, which is not supported. Or, '
        'you may be trying to pass Keras symbolic inputs/outputs '
        'to a TF API that does not register dispatching, '
        'preventing Keras from automatically '
        'converting the API call to a lambda layer '
        'in the Functional Model.')

  @property
  def is_tensor_like(self):
    return True

  def set_shape(self, shape):
    """Updates the shape of this KerasTensor. Mimics `tf.Tensor.set_shape()`."""
    if not isinstance(shape, tensor_shape.TensorShape):
      shape = tensor_shape.TensorShape(shape)
    if shape.dims is not None:
      dim_list = [dim.value for dim in shape.dims]
      for dim in range(len(dim_list)):
        if dim_list[dim] is None and self.shape.dims is not None:
          dim_list[dim] = self.shape.dims[dim]
      shape = tensor_shape.TensorShape(dim_list)
    if not self.shape.is_compatible_with(shape):
      raise ValueError(
          "Keras symbolic input/output's shape %s is not"
          "compatible with supplied shape %s" %
          (self.shape, shape))
    else:
      self._type_spec._shape = shape  # pylint: disable=protected-access

  def __str__(self):
    symbolic_description = ''
    inferred_value_string = ''
    name_string = ''

    if hasattr(self, '_keras_history'):
      layer = self._keras_history.layer
      node_index = self._keras_history.node_index
      tensor_index = self._keras_history.tensor_index
      symbolic_description = (
          ', description="Symbolic value %s from '
          'symbolic call %s of layer \'%s\'"' % (
              tensor_index, node_index, layer.name))
    if self._inferred_value is not None:
      inferred_value_string = (
          ', inferred_value=%s' % self._inferred_value)
    if self.name is not None:
      name_string = ', name=\'%s\'' % self._name
    return 'KerasTensor(type_spec=%s%s%s%s)' % (
        self.type_spec, inferred_value_string,
        name_string, symbolic_description)

  def __repr__(self):
    symbolic_description = ''
    inferred_value_string = ''
    if isinstance(self.type_spec, tensor_spec.TensorSpec):
      type_spec_string = 'shape=%s dtype=%s' % (self.shape, self.dtype.name)
    else:
      type_spec_string = 'type_spec=%s' % self.type_spec

    if hasattr(self, '_keras_history'):
      layer = self._keras_history.layer
      node_index = self._keras_history.node_index
      tensor_index = self._keras_history.tensor_index
      symbolic_description = (
          ' (Symbolic value %s from symbolic call %s of layer \'%s\')' % (
              tensor_index, node_index, layer.name))
    if self._inferred_value is not None:
      inferred_value_string = (
          ' inferred_value=%s' % self._inferred_value)
    return '<KerasTensor: %s%s%s>' % (
        type_spec_string, inferred_value_string, symbolic_description)

  @property
  def dtype(self):
    """Returns the `dtype` symbolically inferred for this Keras output."""
    # TODO(kaftan): This is only valid for normal/sparse/ragged tensors.
    # may need to raise an error when it's not valid for a type_spec,
    # but some keras code (e.g. build-related stuff) will likely fail when
    # it can't access shape or dtype
    return self._type_spec._dtype  # pylint: disable=protected-access

  def ref(self):
    """Returns a hashable reference object to this KerasTensor.

    The primary use case for this API is to put KerasTensors in a
    set/dictionary. We can't put tensors in a set/dictionary as
    `tensor.__hash__()` is not available and tensor equality (`==`) is supposed
    to produce a tensor representing if the two inputs are equal.

    See the documentation of `tf.Tensor.ref()` for more info.
    """
    return object_identity.Reference(self)

  def __iter__(self):
    shape = None
    if self.shape.ndims is not None:
      shape = [dim.value for dim in self.shape.dims]

    if shape is None:
      raise TypeError('Cannot iterate over a Tensor with unknown shape.')
    if not shape:
      raise TypeError('Cannot iterate over a scalar.')
    if shape[0] is None:
      raise TypeError(
          'Cannot iterate over a Tensor with unknown first dimension.')
    return _KerasTensorIterator(self, shape[0])

  @property
  def name(self):
    """Returns the (non-unique, optional) name of this symbolic Keras value."""
    return self._name

  @classmethod
  def _overload_all_operators(cls):  # pylint: disable=invalid-name
    """Register overloads for all operators."""
    for operator in ops.Tensor.OVERLOADABLE_OPERATORS:
      cls._overload_operator(operator)

    # We include `experimental_ref` for versions of TensorFlow that
    # still include the deprecated method in Tensors.
    if hasattr(ops.Tensor, 'experimental_ref'):
      cls._overload_operator('experimental_ref')

  @classmethod
  def _overload_operator(cls, operator):  # pylint: disable=invalid-name
    """Overload an operator with the same overloading as `ops.Tensor`.

    We pull the operator out of ops.Tensor dynamically to avoid ordering issues.

    Args:
      operator: string. The operator name.
    """
    tensor_oper = getattr(ops.Tensor, operator)

    # Compatibility with Python 2:
    # Python 2 unbound methods have type checks for the first arg,
    # so we need to extract the underlying function
    tensor_oper = getattr(tensor_oper, '__func__', tensor_oper)

    setattr(cls, operator, tensor_oper)

KerasTensor._overload_all_operators()  # pylint: disable=protected-access

class _KerasTensorIterator(object):
  """Iterates over the leading dim of a KerasTensor. Performs 0 error checks."""

  def __init__(self, tensor, dim0):
    self._tensor = tensor
    self._index = 0
    self._limit = dim0

  def __iter__(self):
    return self

  def __next__(self):
    if self._index == self._limit:
      raise StopIteration
    result = self._tensor[self._index]
    self._index += 1
    return result

  next = __next__  # python2.x compatibility.

def keras_tensor_to_placeholder(x):
  """Construct a graph placeholder to represent a KerasTensor when tracing."""
  if hasattr(x, '_user_registered_symbolic_object'):
    return x._user_registered_symbolic_object  # pylint: disable=protected-access

  if isinstance(x, KerasTensor):
    spec = x.type_spec

    if x._inferred_value is not None:  # pylint: disable=protected-access
      # If we suspect this KerasTensor might be representing a shape tensor,
      # and we were able to extract value information with TensorFlow's shape
      # handling when making the KerasTensor, we construct the placeholder by
      # re-injecting the inferred value information into the graph.
      # Even though keras layers each trace in their own scratch
      # graph, this shape value info injection allows us to capture
      # a sizable and useful subset of the C++ shape value inference TF can do
      # if all tf ops appear in the same graph when using shape ops.
      #
      # Examples of things this cannot infer concrete dimensions for
      # that the full single-graph C++ shape inference sometimes can are:
      # * cases where the shape tensor is cast out of int32 before being
      #   manipulated w/ floating point numbers then converted back
      # * cases where int32 tensors w/ rank > 2 are manipulated before being
      #   used as a shape tensor
      inferred_value = array_ops.shape(
          array_ops.placeholder(
              shape=x._inferred_value, dtype=dtypes.int32))  # pylint: disable=protected-access
      if spec.shape.rank == 0:
        # `tf.shape` always returns a rank-1, we may need to turn it back to a
        # scalar.
        inferred_value = inferred_value[0]
      return inferred_value  # pylint: disable=protected-access

    if isinstance(spec, sparse_tensor.SparseTensorSpec):
      # nest.map_structure loses dense shape information for sparse tensors.
      # So, we special-case sparse placeholder creation.
      # This only preserves shape information for top-level sparse tensors;
      # not for sparse tensors that are nested inside another composite
      # tensor.
      return array_ops.sparse_placeholder(dtype=spec.dtype, shape=spec.shape)

    def component_to_placeholder(component):
      return array_ops.placeholder(component.dtype, component.shape)

    ph = nest.map_structure(
        component_to_placeholder, spec, expand_composites=True)
    return ph
  else:
    return x

class UserRegisteredSpec(type_spec_module.TypeSpec):
  """TypeSpec to represent user-registered symbolic objects."""

  def __init__(self, shape, dtype):
    self.shape = shape
    self._dtype = dtype
    self.dtype = dtype

  def _component_specs(self):
    raise NotImplementedError

  def _from_components(self, components):
    raise NotImplementedError

  def _serialize(self):
    raise NotImplementedError

  def _to_components(self, value):
    raise NotImplementedError

  def value_type(self):
    raise NotImplementedError

def keras_tensor_from_tensor(x):
  """Convert a traced (composite)tensor to a representative KerasTensor."""
  name = getattr(x, 'name', None)
  inferred_value = None

  # TODO(b/161487382):
  # Special-case user-registered symbolic objects (registered by the
  # private `register_symbolic_tensor_type` method) by passing them between
  # scratch graphs directly.
  # This is needed to not break Tensorflow probability
  # while they finish migrating to composite tensors.
  user_registered_symbolic = False
  try:
    from tensorflow.python.keras.utils import tf_utils  # pylint: disable=g-import-not-at-top to prevent circular imports
    if isinstance(x, tuple(tf_utils._user_convertible_tensor_types)):  # pylint: disable=protected-access
      user_registered_symbolic = True
  except ImportError:
    pass
  if user_registered_symbolic:
    type_spec = UserRegisteredSpec(x.shape, x.dtype)
  else:
    type_spec = type_spec_module.type_spec_from_value(x)

  if (isinstance(type_spec, tensor_spec.TensorSpec)
      and type_spec.dtype == dtypes.int32
      and type_spec.shape.rank < 2):
    # If this tensor might be representing shape information,
    # (dtype=int32, rank of 0 or 1)
    # we attempt to capture any value information tensorflow's
    # shape handling can extract from the current scratch graph.
    #
    # Even though keras layers each trace in their own scratch
    # graph, this shape value info extraction allows us to capture
    # a sizable and useful subset of the C++ shape value inference TF can do
    # if all tf ops appear in the same graph when using shape ops.
    #
    # Examples of things this cannot infer concrete dimensions for
    # that the full single-graph C++ shape inference sometimes can are:
    # * cases where the shape tensor is cast out of int32 before being
    #   manipulated w/ floating point numbers then converted back
    # * cases where int32 tensors w/ rank > 2 are manipulated before being
    #   used as a shape tensor
    inferred_value = array_ops.ones(shape=x).shape
    if inferred_value.dims:
      inferred_value = inferred_value.as_list()
    else:
      inferred_value = None

  out = KerasTensor(type_spec,
                    inferred_value=inferred_value, name=name)
  if user_registered_symbolic:
    out._user_registered_symbolic_object = x  # pylint: disable=protected-access

  if hasattr(x, '_keras_mask'):
    out._keras_mask = KerasTensor(  # pylint: disable=protected-access
        type_spec_module.type_spec_from_value(x._keras_mask))  # pylint: disable=protected-access

  return out


#!/usr/bin/python3
# encoding=utf-8

import os
import sys
import json
import time
from ffmpy import FFmpeg
import logging
import requests
from bs4 import BeautifulSoup

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

SAVE_PATH = "E://test"

def main():
    domain = "https://www.hifini.com/"
    page_idx = -1
    soup = BeautifulSoup('', features='html.parser')
    while True:
        page_idx += 1
        for idx in range(7, 1024, 2):
            music_data = soup.select(
                "#body > div > div > div.col-lg-9.main > div > div.card-body > ul > li:nth-child(%d)" % (idx))

            idx += 1
            if len(music_data) == 0:
                page_url = "https://www.hifini.com/forum-1-%d.htm?orderby=lastpid" % int(page_idx)
                logging.info("try request %s" % page_url)
                while True:
                    response = requests.get(page_url)  # Get方式获取网页数据
                    if response.status_code != 200:
                        logging.warning("request failed, code=%d" % response.status_code)
                        time.sleep(1)
                    else:
                        break
                soup = BeautifulSoup(response.text, features='html.parser')
                break
            elif len(music_data) != 1:
                continue

            data_href = music_data[0].get('data-href')
            url = domain + data_href
            play_html = requests.get(url)
            music_soup = BeautifulSoup(play_html.text, features="html.parser")
            author = None
            title = None
            music_url = None

            for script in music_soup.select("script"):
                script = str(script)
                if script.find("music") >= 0:
                    lines = script.split("\n")
                    for line in lines:
                        line = line.strip()
                        if line.split(":")[0] == "author":
                            author = line.split(":")[1].strip().strip(',')
                        elif line.split(":")[0] == "title":
                            title = line.split(":")[1].strip().strip(',')
                        elif line.split(":")[0] == "url":
                            music_url = line[len("url:"):].strip().strip(",")

            if author is not None and title is not None and music_url is not None:
                author = author.strip("'")
                title = title.strip("'")
                music_url = music_url.strip("'")
                download_url = domain + music_url

                response = requests.get(download_url)
                '''while response.status_code is None or response.status_code != 200:
                    response = requests.get(download_url)
                    #logging.info("request play page failed, code=%d" % response.status_code)
                    #time.sleep(1)
                '''
                if response.headers["Content-Type"] == "application/json;charset=UTF-8":
                    res_json = json.loads(response.text)
                    if res_json["code"] == -460:
                        logging.info("request play page failed, msg=%s, try later..." % res_json["message"])
                        continue
                elif response.status_code == 200:
                    suffix = response.headers["Content-Type"]
                    if suffix.find("/") > 0:
                        suffix = suffix.split("/")[1]
                    save_path = "%s/%s - %s.%s" % (SAVE_PATH, title, author, suffix)
                    with open(save_path, "wb") as fp:
                        fp.write(response.content)
                        logging.info("download success, saved as %s" % save_path)
                    if suffix.upper() != "MP3":
                        mp3_path = "%s/%s - %s.mp3" % (SAVE_PATH, title, author)
                        ff = FFmpeg(inputs={save_path: None}, outputs={mp3_path: None}, global_options="-y")
                        ff.run()
                        os.remove(save_path)

if __name__ == "__main__":
    main()


import os.path
from PyQt5.QtWidgets import (
    QWizardPage, QWizard, QLabel, QVBoxLayout, QCheckBox, QGridLayout,
    QLineEdit, QProgressBar, QPushButton, QMessageBox, QHBoxLayout,
    QApplication, QSizePolicy, QFileDialog
)
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, pyqtSignal, QThread

class FinalPage(QWizardPage):
    """Final QWizard page, displays test result."""
    def __init__(self, threadlink, test_utility, report):
        self.system_font = QApplication.font().family()
        self.label_font = QFont(self.system_font, 12)

        super().__init__()

        self.threadlink = threadlink
        self.tu = test_utility
        self.report = report

    def initializePage(self):
        self.report.file_not_found_signal.connect(self.file_not_found)
        self.report.generic_error_signal.connect(self.generic_error)

        # Disable abort button
        self.threadlink.button(QWizard.CustomButton1).setEnabled(False)

        # Check test result
        report_dir_path = self.tu.settings.value("report_dir_path")
        self.report.set_file_location(report_dir_path)
        report_file_path = self.report.generate_report()

        test_result = self.report.test_result

        if test_result == "PASS":
            self.test_status = "Successful"
        else:
            self.test_status = "Failed"

        self.test_status_lbl = QLabel(f"Test {self.test_status}!")
        self.test_status_lbl.setFont(self.label_font)

        self.report_location_lbl = QLabel(
            f"Report available at: {report_file_path}.")
        self.report_location_lbl.setWordWrap(True)
        self.report_location_lbl.setFont(self.label_font)

        self.break_down_lbl = QLabel("Remove power and remove DUT test "
                                     "fixture.")
        self.break_down_lbl.setFont(self.label_font)

        self.layout = QVBoxLayout()
        self.layout.addSpacing(100)
        self.layout.addWidget(self.test_status_lbl)
        self.layout.addSpacing(25)
        self.layout.addWidget(self.break_down_lbl)
        self.layout.addSpacing(25)
        self.layout.addWidget(self.report_location_lbl)
        self.layout.addStretch()
        self.setLayout(self.layout)
        self.setTitle("Test Completed")

    def file_not_found(self):
        QMessageBox.warning(self, "Warning", "Report directory does not "
                            "exist!\n Please specify directory.")
        report_dir = QFileDialog.getExistingDirectory(self,
            "Select report save location.")
        self.tu.settings.setValue("report_dir_path", report_dir)
        self.initializePage()

    def generic_error(self, error):
        QMessageBox.warning(self, "Warning", error)


import math

raggio = float(input("Dammi il raggio: "))

AreaDelCerchio = math.pi * (raggio * raggio)

LunghezzaDellaCirconferenza = math.pi *( 2 * raggio)

print ("L'area del cerchio vale:", (AreaDelCerchio))
print ("La circonferenza del cerchio vale:", (LunghezzaDellaCirconferenza))


# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime

def get_triangle_from_line(line):
    return tuple(int(v) for v in line.split())

def get_triangles_from_file(file_path="../../resources/year2016_day3_input.txt"):
    with open(file_path) as f:
        return [get_triangle_from_line(l.strip()) for l in f]

def triangle_is_possible(t):
    a, b, c = sorted(t)
    return a + b > c

def run_tests():
    assert not triangle_is_possible((5, 10, 25))
    assert triangle_is_possible((5, 10, 12))

def get_solutions():
    triangles = get_triangles_from_file()
    print(sum(triangle_is_possible(t) for t in triangles) == 993)

    s = 0
    triangles_iter = iter(triangles)
    while True:
        try:
            for t in zip(
                next(triangles_iter), next(triangles_iter), next(triangles_iter)
            ):
                s += triangle_is_possible(t)
        except StopIteration:
            break
    print(s == 1849)

if __name__ == "__main__":
    begin = datetime.datetime.now()
    run_tests()
    get_solutions()
    end = datetime.datetime.now()
    print(end - begin)


class Star:
    type = 'Star'
    x = 100

    def change():
        x = 200
        print('x is ', x)

print('x IS ', Star.x) #OK
Star.change() #OK
print('x Is ',Star.x) #OK

star = Star() #OK
print('x IS ', star.x) #OK
star.change() #Error

# 파이썬 클래스에서 생성자 없어도 되긴함
# 클래스를 통해 생성한 객체(인스턴스) 가 하나인 경우 = 싱글톤
# 싱글톤을 쓰는 이유 : 글로벌을 한 곳에 모아서 단일하게 사용하기위해

# 파이썬은 다음과 같이 처리함
# star.change() ==> Star.change(star)
# 파이썬의 변수는 그 자체가 포인터임


"""
Agent that creates symlinks to logfiles and embeds metadata in the
file/directory name of the Symlink.  Can be used in conjunction with a
log shipping agent (e.g. Fluentd) that watches the directory structure
containing the symlinks. Since all metadata is embedded in the
filename, there is no need to dynamically generate configuration for
the log shipping agent.
"""

import logging
import os
import pathlib
import re
import shutil

from kube_log_watcher.agents.base import BaseWatcher

logger = logging.getLogger(__name__)

def sanitize(s):
    return re.sub('[^a-zA-Z0-9_-]', '_', s)

class Symlinker(BaseWatcher):
    def __init__(self, configuration):
        symlink_dir = os.environ.get('WATCHER_SYMLINK_DIR', configuration.get('symlink_dir'))
        if not symlink_dir:
            raise RuntimeError(
                'Symlinker watcher agent initialization failed. Env variable WATCHER_SYMLINK_DIR must be set')
        self.symlink_dir = pathlib.Path(symlink_dir)
        if not self.symlink_dir.is_dir():
            raise RuntimeError(
                'Symlinker watcher agent initialization failed. Symlink base directory {} does not exist'
                .format(self.symlink_dir))
        logger.info('Symlinker watcher agent initialized')

    @property
    def name(self):
        return 'Symlinker'

    def add_log_target(self, target):
        logger.debug('Symlinker: add_log_target for %s called', target['id'])
        kw = target['kwargs']
        top_dir = self.symlink_dir / sanitize(kw['container_id'])
        link_dir = top_dir \
            / sanitize(kw['application'] or 'none') \
            / sanitize(kw['component'] or kw['application'] or 'none') \
            / sanitize(kw['namespace']) \
            / sanitize(kw['environment']) \
            / sanitize(kw['version'] or 'none') \
            / sanitize(kw['container_name'])
        link = (link_dir / sanitize(kw['pod_name'])).with_suffix('.log')

        if top_dir.exists():
            if link.is_symlink and link.samefile(kw['log_file_path']):
                logger.debug('Symlinker: link already exists for %s. Nothing to be done.', target['id'])
                return
            logger.info('Symlinker: metadata has changed for %s. Creating new symlink.', target['id'])
            shutil.rmtree(str(top_dir))
            logger.debug('Symlinker: Removed directory %s', top_dir)

        link_dir.mkdir(parents=True)
        link.symlink_to(kw['log_file_path'])
        logger.debug('Symlinker: Created symlink %s -> %s', link, kw['log_file_path'])

    def remove_log_target(self, container_id):
        logger.debug('Symlinker: remove_log_target for %s called', container_id)
        link_dir = str(self.symlink_dir / sanitize(container_id))
        try:
            shutil.rmtree(link_dir)
            logger.debug('Symlinker: Removed directory %s', link_dir)
        except Exception:
            logger.warning('%s watcher agent failed to remove link directory %s', self.name, link_dir)

    def flush(self):
        for container_dir in pathlib.Path(self.symlink_dir).iterdir():
            link = next(pathlib.Path(container_dir).glob('**/*.log'))
            if link and link.exists():
                continue
            else:
                shutil.rmtree(str(container_dir))


import random
player_choice = ""
rock = 0
rock_ascii_art = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''
paper = 1
paper_ascii_art = '''
     _______
---'    ____)____
           ______)
          _______)
         _______)
---.__________)
'''
scissors = 2
scissors_ascii_art = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''
continue_playing = True
while continue_playing:
    while True:
        player_choice = input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors:")
        if player_choice == "0" or player_choice == "1" or player_choice == "2":
            break
        else:
            print("Not a valid selection, please try again...")
            player_choice = ""

    player_choice = int(player_choice)
    computer_choice = random.randint(0, 2)
    player_pick = ''
    computer_pick = ''
    if player_choice == rock:
        player_pick = rock_ascii_art
    elif player_choice == paper:
        player_pick = paper_ascii_art
    else:
        player_pick = scissors_ascii_art

    if computer_choice == rock:
        computer_pick = rock_ascii_art
    elif computer_choice == paper:
        computer_pick = paper_ascii_art
    else:
        computer_pick = scissors_ascii_art

    print(f"Player:\n{player_pick}\nComputer:\n{computer_pick}")
    if player_choice == rock and computer_choice == paper:
        print("You lose, the computer beat your rock with paper")
    elif player_choice == rock and computer_choice == scissors:
        print("You WIN, you beat the computer's scissors with rock")
    elif player_choice == rock and computer_choice == rock:
        print("DRAW, the computer also threw down rock")
    elif player_choice == paper and computer_choice == rock:
        print("You WIN, your paper beat the computer's rock")
    elif player_choice == paper and computer_choice == paper:
        print("DRAW, the computer also picked paper")
    elif player_choice == paper and computer_choice == scissors:
        print("You lose, the computer beat your paper with scissors")
    elif player_choice == scissors and computer_choice == rock:
        print("You lose, the computer beat your rock with scissors")
    elif player_choice == scissors and computer_choice == paper:
        print("You WIN, your scissors beat the computer's rock")
    elif player_choice == scissors and computer_choice == scissors:
        print("DRAW, you BOTH picked scissors")

    while True:
        continue_choice = input("Would you like to continue playing? yes or no:").lower()
        if continue_choice == "yes" or continue_choice == "no":
            if continue_choice == "yes":
                continue_playing = True
            else:
                continue_playing = False
            break
        else:
            print("Not a valid option, try again...")
            continue_choice = ""

print("Thanks for playing, good-bye!")


import tensorflow as tf
import tensorflow_probability as tfp
import snapshottest

from glow.bijectors import GlowFlow, GlowStep
from glow.bijectors.squeeze import Squeeze

tfb = tfp.bijectors

tf.enable_eager_execution()
tf.set_random_seed(1)

class TestGlowFlow(tf.test.TestCase, snapshottest.TestCase):

    def setUp(self):
        self.batch_size = 1
        # event_dims = image_size
        self.event_dims = (8, 8, 3)
        tf.reset_default_graph()

    def testBijective(self):
        flow = GlowFlow(level=3, level_depth=3, validate_args=False)
        x = tf.random_uniform(
            (self.batch_size, ) + self.event_dims, dtype=tf.float32)
        z = flow.inverse(x)
        x_ = flow.forward(tf.identity(z))

        assert z.shape == x.shape

        with self.test_session():
            self.assertAllEqual(x, x_.numpy())

    def testForward(self):
        flow = GlowFlow(level=3, level_depth=3, validate_args=False)
        x = tf.random_uniform(
            (self.batch_size, ) + self.event_dims, dtype=tf.float32)
        z = flow.forward(x)

        # with self.test_session():
        #     self.assertMatchSnapshot(x.numpy().tolist())

    def testInverse(self):
        flow = GlowFlow(level=3, level_depth=3, validate_args=False)
        x = tf.random_uniform(
            (self.batch_size, ) + self.event_dims, dtype=tf.float32)
        z = flow.inverse(x)

        # with self.test_session():
        #     self.assertMatchSnapshot(z.numpy().tolist())

    def testSingleLevelShapes(self):
        num_levels = 1
        flow = GlowFlow(
            level=num_levels, level_depth=2, validate_args=False)
        event_dims = (64, 64, 8)
        x = tf.random_uniform(
            (self.batch_size, ) + event_dims, dtype=tf.float32)
        z = flow.forward(x)

        self.assertEqual(x.shape, z.shape)

    def testParallelPassthrough(self):
        num_levels = 3
        flow = GlowFlow(
            level=num_levels, level_depth=2, validate_args=False)
        event_dims = (64, 64, 8)
        x = tf.random_uniform(
            (self.batch_size, ) + event_dims, dtype=tf.float32)

        z = flow.forward(x)

        z2 = tfb.Chain(list(reversed(
            flow.flow_steps[:2] + flow.flow_steps[-1:]
        ))).forward(x)

        self.assertNotEqual(z, z2)
        self.assertTrue(tf.reduce_all(
            tf.equal(z[..., :event_dims[-1]/2], z2[..., :event_dims[-1]/2])
        ))

    def testVerifyTrainableVariables(self):
        num_levels = 3
        flow = GlowFlow(
            level=num_levels, level_depth=2, validate_args=False)
        event_dims = (64, 64, 8)
        x = tf.random_uniform(
            (self.batch_size, ) + event_dims, dtype=tf.float32)

        flow.forward(x)

        trainable_variables = tf.trainable_variables()

        raise NotImplementedError(
            "Should test that the trainable variables match expectation")

        with self.test_session():
            self.assertMatchSnapshot(trainable_variables)

class TestGlowStep(tf.test.TestCase, snapshottest.TestCase):

    def setUp(self):
        self.batch_size = 1
        # event_dims = image_size
        self.event_dims = (8, 8, 3)

    def testForward(self):
        step = GlowStep(depth=2, validate_args=False)
        x = Squeeze(factor=2).forward(
            tf.random_uniform(
                (self.batch_size, ) + self.event_dims, dtype=tf.float32))
        z = step.forward(x)

        self.assertEqual(x.shape, z.shape)

        # with self.test_session():
        #     self.assertMatchSnapshot(x.numpy().tolist())

    def testVerifyTrainableVariables(self):
        raise NotImplementedError(
            "Should test that the trainable variables match expectation")

if __name__ == '__main__':
    tf.test.main()


# -*- coding: utf-8 -*-
"""
Created on Tue Jun  9 14:10:44 2020.

@author: pielsticker
"""
import os
import pickle
import numpy as np
import json
from matplotlib import pyplot as plt
import matplotlib.colors as mcolors
import seaborn as sns

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm, Pt

#%%
class SpectraPlot:
    """A nx5 array of plots from a given data set."""

    def __init__(self, data, annots):
        """
        Initiate subplots in a nx5 array where n = data.shape[0]/5.

        Parameters
        ----------
        data : array
            A numpy set with two channels: binding energy and intensity.
        annots : list
            List of annotations.

        Returns
        -------
        None.

        """
        self.data = data
        self.annots = annots
        self.no_of_spectra = self.data.shape[0]

        self.no_of_cols = 5
        self.no_of_rows = int(self.no_of_spectra / self.no_of_cols)
        if (self.no_of_spectra % self.no_of_cols) != 0:
            self.no_of_rows += 1

        self.fig, self.axs = plt.subplots(
            nrows=self.no_of_rows, ncols=self.no_of_cols, squeeze=False
        )
        plt.subplots_adjust(
            left=0.125,
            bottom=0.5,
            right=4.8,
            top=self.no_of_rows,
            wspace=0.2,
            hspace=0.2,
        )

    def plot(self):
        """
        Populate the plots with the data.

        Returns
        -------
        fig, axs
            Matplotlib objects.
        """
        for i in range(self.no_of_spectra):
            row, col = int(i / self.no_of_cols), i % self.no_of_cols
            x = self.data[i][:, 0]
            y = self.data[i][:, 1]
            annot = self.annots[i]

            try:
                self.axs[row, col].plot(x, y)
                self.axs[row, col].invert_xaxis()
                self.axs[row, col].set_xlim(np.max(x), np.min(x))
                self.axs[row, col].set_xlabel("Binding energy (eV)")
                self.axs[row, col].set_ylabel("Intensity (arb. units)")
                self.axs[row, col].text(
                    0.025,
                    0.4,
                    annot,
                    horizontalalignment="left",
                    verticalalignment="top",
                    transform=self.axs[row, col].transAxes,
                    fontsize=12,
                )

            except IndexError:
                self.axs[row].plot(x, y)
                self.axs[row].invert_xaxis()
                self.axs[row].set_xlim(np.max(x), np.min(x))
                self.axs[row].set_xlabel("Binding energy (eV)")
                self.axs[row].set_ylabel("Intensity (arb. units)")
                self.axs[row].text(
                    0.025,
                    0.4,
                    annot,
                    horizontalalignment="left",
                    verticalalignment="top",
                    transform=self.axs[row, col].transAxes,
                    fontsize=12,
                )

        return self.fig, self.axs

class ClassDistribution:
    """Class for the distribution of classes in a dataset."""

    def __init__(self, task, data_list):
        """
        Calculate the distributions of the labels.

        If the task is "regression", the average distributions
        are calculated. If the task is "classification", calculate how
        many examples of each class are in the different data ses.

        Save the distribution in a dict called 'cd'.
        cd: Dictionary of the format {'all data': dict,
                                      'training data': dict,
                                      'validation data': dict,
                                      'test data': dict}.
        Each of the sub-dicts contains the distribution of the labels
        in the data sub-set.

        Parameters
        ----------
        task : str
            If task == 'regression', an average distribution is
            calculated.
            If task == 'classification' or 'multi_class_detection',
            the distribution of the labels across the different data
            sets is calculated.
        data_list : list
            List of numpy arrays containing labels.

        Returns
        -------
        None.

        """
        self.task = task

        self.cd = {
            "all data": {},
            "training data": {},
            "validation data": {},
            "test data": {},
        }

        for i in range(data_list[0].shape[1]):
            self.cd["all data"][str(i)] = 0
            self.cd["training data"][str(i)] = 0
            self.cd["validation data"][str(i)] = 0
            self.cd["test data"][str(i)] = 0

        if self.task == "classification":
            for i, dataset in enumerate(data_list):
                key = list(self.cd.keys())[i]
                for j, datapoint in enumerate(dataset):
                    argmax_class = np.argmax(datapoint, axis=0)
                    self.cd[key][str(argmax_class)] += 1

        elif self.task == "regression":
            for i, dataset in enumerate(data_list):
                key = list(self.cd.keys())[i]
                average = list(np.mean(dataset, axis=0))
                self.cd[key] = average

        elif self.task == "multi_class_detection":
            for i, dataset in enumerate(data_list):
                key = list(self.cd.keys())[i]
                for j, datapoint in enumerate(dataset):
                    non_zero_classes_args = np.where(datapoint > 0.0)[0]
                    for n in non_zero_classes_args:
                        self.cd[key][str(n)] += 1

    def plot(self, labels):
        """
        Plot the class distribution. Using the labels list as legend.

        Parameters
        ----------
        labels : list
            List of label values for the legend.

        Returns
        -------
        None.

        """
        fig = plt.figure()
        ax = fig.add_axes([0, 0, 1, 1])
        x = np.arange(len(self.cd.keys())) * 1.5
        data = []

        if self.task == "regression":
            plt.title("Average distribution across the classes")
            # Plot of the average label distribution in the different
            # data sets.
            for k, v in self.cd.items():
                data.append(v)
            data = np.transpose(np.array(data))
            ax.set_ylabel("Average concentration")

        else:
            plt.title("Class distribution")
            for k, v in self.cd.items():
                data_list = []
                for key, value in v.items():
                    data_list.append(value)
            data.append(data_list)
            data = np.transpose(np.array(data))

        for i in range(data.shape[0]):
            ax.bar(x + i * 0.25, data[i], align="edge", width=0.2)
        plt.legend(labels)
        plt.xticks(ticks=x + 0.5, labels=list(self.cd.keys()))
        plt.show()

class TrainingGraphs:
    """Class for graphs with the result of the training in Keras."""

    def __init__(self, history, fig_dir):
        """
        Take a dictionary containing the results from training.

        Parameters
        ----------
        history : dict
            # A dictionary containing the results from the training of a
            neural network in Keras.
        fig_dir : str
            The name of the directory where the figures shall be saved.

        Returns
        -------
        None.

        """
        self.history = history
        self.fig_dir = fig_dir

    def plot_metric(self, metric, title=None, ylabel=None, to_file=True):
        """
        Plots the training and validation values of a metric
        against the epochs.

        Returns
        -------
        None.

        """
        metric_cap = metric.capitalize()

        try:
            metric_history = self.history[metric]
            fig, ax = plt.subplots()
            ax.plot(metric_history, linewidth=3)
            try:
                val_key = "val_" + metric
                ax.plot(self.history[val_key], linewidth=3)
            except KeyError:
                print(f"Validation {metric} was not logged.")
            ax.set_title(metric_cap)
            ax.set_ylabel(metric_cap)
            if title:
                ax.set_title(str(title))
            if ylabel:
                ax.set_ylabel(str(ylabel))
            ax.set_xlabel("Epoch")
            ax.legend(["Train", "Validation"])

            if to_file:
                fig_name = os.path.join(self.fig_dir, f"{metric}.png")
                fig.savefig(fig_name)

        except KeyError:
            print(f"{metric_cap} was not logged during training.")

    def plot_loss(self, to_file=True):
        """
        Plot the training and validation loss against the epochs.

        Returns
        -------
        None.

        """
        self.plot_metric(metric="loss", to_file=to_file)

    def plot_accuracy(self, to_file=True):
        """
        Plot the training and validation accuracy against the epochs.

        Returns
        -------
        None.

        """
        self.plot_metric(
            metric="accuracy",
            ylabel="Classification accuracy",
            to_file=to_file,
        )

    def plot_mse(self, to_file=True):
        """
        Plots the training and validation mean squared error against the epochs.

        Returns
        -------
        None.

        """
        self.plot_metric(
            metric="mse", title="MSE", ylabel="MSE", to_file=to_file
        )

class WeightDistributions:
    """
    Class to calculate weight distribution of a Bayesian model in keras.
    """

    def __init__(self, bayesian_layers, fig_dir):
        import warnings

        warnings.filterwarnings("ignore")

        self.bayesian_layers = bayesian_layers
        self.names = [layer.name for layer in self.bayesian_layers]

        self.fig_dir = fig_dir

    def plot_weight_priors(self, to_file=True):
        qm_vals = [
            layer.kernel_prior.mean().numpy() for layer in self.bayesian_layers
        ]
        qs_vals = [
            layer.kernel_prior.stddev().numpy()
            for layer in self.bayesian_layers
        ]

        return self.plot_distribution(
            qm_vals, qs_vals, kind="prior", to_file=to_file
        )

    def plot_weight_posteriors(self, to_file=True):
        qm_vals = [
            layer.kernel_posterior.mean().numpy()
            for layer in self.bayesian_layers
        ]
        qs_vals = [
            layer.kernel_posterior.stddev().numpy()
            for layer in self.bayesian_layers
        ]

        return self.plot_distribution(
            qm_vals, qs_vals, kind="posterior", to_file=to_file
        )

    def plot_distribution(
        self, qm_vals, qs_vals, kind="posterior", to_file=True
    ):

        fig, _ = plt.subplots(figsize=(12, 6))
        colors = iter(mcolors.TABLEAU_COLORS.keys())

        ax1 = fig.add_subplot(1, 2, 1)
        ax2 = fig.add_subplot(1, 2, 2)

        for n, qm, qs in zip(self.names, qm_vals, qs_vals):
            c = next(colors)
            try:
                sns.histplot(
                    np.reshape(qm, newshape=[-1]),
                    ax=ax1,
                    # bins=50,
                    label=n,
                    color=c,
                    kde=True,
                    stat="density",
                )
                sns.histplot(
                    np.reshape(qs, newshape=[-1]),
                    ax=ax2,
                    # bins=50,
                    label=n,
                    color=c,
                    kde=True,
                    stat="density",
                )
            except np.linalg.LinAlgError:
                sns.histplot(
                    np.reshape(qm, newshape=[-1]),
                    ax=ax1,
                    # bins=50,
                    label=n,
                    color=c,
                    kde=False,
                    stat="density",
                )
                sns.histplot(
                    np.reshape(qs, newshape=[-1]),
                    ax=ax2,
                    # bins=50,
                    label=n,
                    color=c,
                    kde=False,
                    stat="density",
                )

        ax1.set_title(f"{kind.capitalize()}" + " weight means")
        ax1.legend()
        ax2.set_title(f"{kind.capitalize()}" + " weight standard deviations")

        fig.tight_layout()
        # plt.show()

        return fig

class Report:
    """Report on the results of the training in keras."""

    def __init__(self, dir_name=""):
        """
        Initialize a docx document.

        Load the data from the hyperparamters file.

        Parameters
        ----------
        dir_name : str, optional
            The name of the directory where the report shall be saved.
            The default is ''.

        Returns
        -------
        None.

        """
        self.document = Document()
        style = self.document.styles["Normal"]
        font = style.font
        font.name = "Arial"
        font.size = Pt(10)

        # Get the data
        root_dir = os.getcwd()
        self.model_dir = os.path.join(
            *[
                root_dir,
                "runs",
                dir_name,
                "model",
            ]
        )
        self.log_dir = os.path.join(*[root_dir, "runs", dir_name, "logs"])
        self.fig_dir = os.path.join(*[root_dir, "runs", dir_name, "figures"])

        (
            self.name_data,
            self.train_data,
            self.model_summary,
        ) = self.get_hyperparams()
        self.results = self.get_results()
        self.class_dist = self.results["class_distribution"]
        self.filename = os.path.join(self.log_dir, "report.docx")
        self.create_document()

    def create_document(self):
        """
        Add data from the results to the report.

        Returns
        -------
        None.

        """
        self.document.add_heading("Training report", 0)

        # Add the names and basic information.
        self.document.add_heading("Data:", 1)

        name_table = self.document.add_table(
            rows=len(self.name_data.keys()), cols=2
        )
        for key, value in self.name_data.items():
            j = int(list(self.name_data.keys()).index(key))
            name_table.cell(j, 0).text = key + ":"
            name_table.cell(j, 1).text = str(value)

        self.document.add_heading("Distribution:", 1)
        dist_table = self.document.add_table(
            rows=len(self.class_dist.keys()) + 1,
            cols=len(next(iter(self.class_dist.values()))) + 1,
        )

        dist_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        for i, name in enumerate(self.name_data["Labels"]):
            dist_table.cell(0, i + 1).text = name
        for item, param in self.class_dist.items():
            j = int(list(self.class_dist.keys()).index(item)) + 1
            dist_table.cell(j, 0).text = item

            for key, value in enumerate(self.class_dist[item]):
                k = int(key) + 1
                dist_table.cell(j, k).text = str(np.round(value, 3))

        self.document.add_page_break()

        # Add information about the training parameters
        self.document.add_heading("Training parameters:", 1)

        train_table = self.document.add_table(
            rows=len(self.train_data.keys()), cols=2
        )

        for key, value in self.train_data.items():
            j = int(list(self.train_data.keys()).index(key))
            train_table.cell(j, 0).text = key + ":"
            train_table.cell(j, 1).text = str(value)

        # Add the model architecture
        self.document.add_heading("Model architecture", 1)

        par = self.document.add_paragraph(self.model_summary)
        par.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

        self.document.add_page_break()

        # Add loss and accuracy values.
        self.document.add_heading("Loss & accuracy", 1)

        loss_file = os.path.join(self.fig_dir, "loss.png")
        self.document.add_picture(loss_file, width=Cm(12))
        last_paragraph = self.document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        try:
            acc_file = os.path.join(self.fig_dir, "accuracy.png")
            self.document.add_picture(acc_file, width=Cm(12))
            last_paragraph = self.document.paragraphs[-1]
            last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        except FileNotFoundError:
            pass

        # Add results on the test data.
        self.document.add_heading("Results", 1)

        result_table = self.document.add_table(rows=2, cols=2)
        result_table.cell(0, 0).text = "Test loss:"
        result_table.cell(0, 1).text = str(
            np.round(self.results["test_loss"], decimals=3)
        )
        try:
            result_table.cell(1, 0).text = "Test accuracy:"
            result_table.cell(1, 1).text = str(
                np.round(self.results["test_accuracy"], decimals=3)
            )

            for row in result_table.rows:
                for cell in row.cells:
                    cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        except KeyError:
            pass

        self.document.add_page_break()

        # Add predictions on random data.
        self.document.add_heading("Predictions for 5 random examples", 1)

        self.document.add_heading("Training data", 2)

        r = np.random.randint(0, self.results["y_train"].shape[0] - 5)
        pred_train_5 = self.results["pred_train"][r : r + 5, :]
        y_train_5 = self.results["y_train"][r : r + 5, :]

        p = self.document.add_paragraph()
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = None
        run = p.add_run()
        run.text = "Predictions:"
        run.font.underline = True
        _ = self.add_result_table(pred_train_5)

        p = self.document.add_paragraph()
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = None
        run = p.add_run()
        run.text = "Correct labels:"
        run.font.underline = True
        self.add_result_table(y_train_5)

        self.document.add_heading("Test data", 2)
        s = np.random.randint(0, self.results["y_test"].shape[0] - 5)
        pred_test_5 = self.results["pred_test"][s : s + 5, :]
        y_test_5 = self.results["y_test"][s : s + 5, :]

        p = self.document.add_paragraph()
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = None
        run = p.add_run()
        run.text = "Predictions:"
        run.font.underline = True
        self.add_result_table(pred_test_5)

        p = self.document.add_paragraph()
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = None
        run = p.add_run()
        run.text = "Correct labels:"
        run.font.underline = True
        self.add_result_table(y_test_5)

    def add_result_table(self, data_array):
        """
        Store and display the results from training.

        Parameters
        ----------
        data_array : ndarray
            Array with the results from training.

        Returns
        -------
        None.

        """
        new_table = self.document.add_table(
            rows=data_array.shape[0] + 1, cols=data_array.shape[1]
        )
        for row in new_table.rows:
            row.height = Cm(0.5)
            row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

        for i, name in enumerate(self.name_data["Labels"]):
            new_table.cell(0, i).text = name
            new_table.cell(0, i).paragraphs[
                0
            ].alignment = WD_ALIGN_PARAGRAPH.CENTER

        if data_array.dtype == "float32":
            a = np.around(data_array, decimals=4)
            row_sums = a.sum(axis=1)
            data_array = a / row_sums[:, np.newaxis]
            data_array = np.around(data_array, decimals=2)

        for i in range(data_array.shape[0]):
            for j in range(data_array.shape[1]):
                new_table.cell(i + 1, j).text = str(data_array[i, j])
                new_table.cell(i + 1, j).paragraphs[
                    0
                ].alignment = WD_ALIGN_PARAGRAPH.CENTER

    def get_hyperparams(self):
        """
        Load the hyperparameters of the training from the JSON file.

        Returns
        -------
        name_data : dict
            Basic information about the experiment.
        class_distribution : dict
            Distribution of the class in the data sets.
        train_data : dict
            Information about the training parameters..
        model_summary : dict
            Summary of the model in str format.

        """
        hyperparam_file_name = os.path.join(
            self.log_dir, "hyperparameters.json"
        )
        with open(hyperparam_file_name, "r") as json_file:
            data_dict = json.load(json_file)

        name_data = {
            "Name": data_dict["exp_name"],
            "Time created": data_dict["time"],
            "No. of classes": data_dict["num_of_classes"],
            "Labels": data_dict["labels"],
            "Total no. of samples": data_dict["no_of_examples"],
            "Train-test-split": data_dict["train_test_split"],
            "Train-val-split": data_dict["train_val_split"],
            "No. of training samples": data_dict["No. of training samples"],
            "No. of validation samples": data_dict[
                "No. of validation samples"
            ],
            "No. of test samples": data_dict["No. of test samples"],
            "Shape of each sample": data_dict["Shape of each sample"],
        }

        train_data = {
            "Optimizer": data_dict["optimizer"],
            "Learning rate": data_dict["learning_rate"],
            "Loss function": data_dict["loss"],
            "Epochs trained": data_dict["epochs_trained"],
            "Batch size": data_dict["batch_size"],
        }

        model_summary = data_dict["model_summary"]

        return name_data, train_data, model_summary

    def get_results(self):
        """
        Load the results from the pickle file.

        Results include e.g. the test data and the predictions.

        Returns
        -------
        data : dict
            Dictionary of numpy arrays with the results..

        """
        file_name = os.path.join(self.log_dir, "results.pkl")

        with open(file_name, "rb") as pickle_file:
            data = pickle.load(pickle_file)

        return data

    def write(self):
        """
        Store the document in the logs folder.

        Returns
        -------
        None.

        """
        self.document.save(self.filename)
        print("Report saved!")


from heapq import heappop, heappush
n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    s, e, d = map(int, input().split())
    graph[s].append([e, d])

s, e = map(int, input().split())
cost = [9876543210] * (n + 1)
checked = set(range(1, n+1))

h = []
heappush(h, [0, s])

cost[s] = 0
while h and checked:
    cost_, cs = heappop(h)
    if cs in checked:
        checked.remove(cs)
    else:
        continue
    if cs == e:
        break
    for ce, d in graph[cs]:
        if cost[ce] > cost_ + d:
            heappush(h, [cost_ + d, ce])
            cost[ce] = cost_ + d
print(cost[e])

백준/Gold/1916. 최소비용 구하기/최소비용 구하기.py


class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        m,n,O=len(obstacleGrid),len(obstacleGrid[0]),obstacleGrid
        num=[[0 for j in range(n)] for i in range(m)]
        if O[0][0]==0:
            num[0][0]=1
        else:
            num[0][0]=0
        for i in range(m):
            for j in range(n):
                if O[i][j]==0:
                    if i-1>=0:
                        num[i][j]+=num[i-1][j]
                    if j-1>=0:
                        num[i][j]+=num[i][j-1]
        return num[m-1][n-1]
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """


'''

script for constructing HOD catalogs for the Quijote LHC simulations
with a forward model of the BOSS CMASS galaxy sample
Use this file for z=0.5 catalog

'''
import os, sys
import numpy as np
sys.path.append('../src/')
import halos as Halos
import galaxies as Galaxies
import json

np.random.seed(1)

m_hod = sys.argv[1] # hod model
i0 = int(sys.argv[2])
i1 = int(sys.argv[3])
#zred = float(sys.argv[4])
zred = 0.5
nhod = 5

def sample_HOD(m_hod):
    ''' sample HOD value based on priors set by Reid et al (2013), Table 4, MedRes column (4)
    (https://academic.oup.com/mnras/article/444/1/476/1010938)
    The scatter uncertainties are increased by 100% or more to account for variations in cosmology. Some values are increased to match lowz scatter
    '''
    if m_hod == 'zheng07':
        hod_min = np.array([13., 0.32, 13.3, 14.1, 0.7])
        dhod = np.array([0.15, 0.15, 0.5, 0.3, 0.4])
        #dhod = 2*np.array([0.029, 0.06, 0.13, 0.06, 0.18])
        #_hod = hod_fid + dhod * np.random.uniform(-0.5, 0.5, size=(5))
        _hod = hod_min + dhod * np.random.uniform(size=(5))
        return {'logMmin': _hod[0], 'sigma_logM': _hod[1], 'logM0': _hod[2], 'logM1': _hod[3], 'alpha': _hod[4]}
    elif m_hod == 'zheng07_ab':
        hod_min = np.array([13., 0.32, 13.3, 14.1, 0.7, 0., 0.])
        dhod = np.array([0.1, 0.1, 0.2, 0.12, 0.3, 0.5, 0.5])
        _hod = hod_min + dhod * np.random.uniform(size=(7))
        return {'logMmin': _hod[0], 'sigma_logM': _hod[1], 'logM0': _hod[2], 'logM1': _hod[3], 'alpha': _hod[4],
                'mean_occupation_centrals_assembias_param1': _hod[5],
                'mean_occupation_satellites_assembias_param1': _hod[6]}
    else:
        raise NotImplementedError

dat_dir = '/mnt/ceph/users/cmodi/simbig/z0p5/catalogs/'
for i_lhc in range(i0, i1):
    print('LHC %i' % i_lhc)
    # read in halo catalog
    halos = Halos.Quijote_LHC_HR(i_lhc, z=zred)
    for i_hod in range(nhod):
        print('  HOD %i' % i_hod)

        save_dir = dat_dir + '%04d/'%i_lhc
        os.makedirs(save_dir, exist_ok=True)

        fgal = os.path.join(save_dir, '%s.%i.bf' %
                ( m_hod, i_hod))
        fhod = fgal.replace('.bf', '.npy')
        fsum = fgal.replace('.bf', '.json')

        if not os.path.isfile(fhod) or not os.path.isdir(fgal):
            # sample HOD parameters
            theta_hod = sample_HOD(m_hod)
            np.save(fhod, theta_hod)
            # populate box with HOD
            hod = Galaxies.hodGalaxies(halos, theta_hod, seed=0, hod_model=m_hod)
            # save box
            hod.save(fgal)

            #calculate some summary numbers on galaxy types
            gtype = hod['gal_type'].compute()
            galsum = {}
            galsum['total'], galsum['number density'] = gtype.size, gtype.size/1000**3
            galsum['centrals'], galsum['satellites'] = np.unique(gtype, return_counts=True)[1]
            print(galsum)
            #save
            def convert(o):
                if isinstance(o, np.generic): return int(o)
                raise TypeError
            with open(fsum, 'w') as fp:
                json.dump(galsum, fp, default=convert, indent=4, sort_keys=True)


import openpyxl
import re
wb = openpyxl.load_workbook("question-choosing.xlsx").active
dataDict = {}
resultDict = {}

for i in range(4, 29):
    for j in range(2, 12, 4):
        key = wb.cell(row=i, column=j).value
        if (key != None):
            key = re.sub('\s+', '', key)
            key = key[-2:]
            dataDict[key] = wb.cell(row=i, column=j+1).value

groupResults = open("result.txt","w")
studentNames = open("../studentList.txt").readlines()

for i in range(1,26):
    groupResults.write("\n\nQuestion "+str(i)+"\n")
    result = [studentNames[int(k)-1] for k,v in dataDict.items() if v==i]
    groupResults.writelines(result)

for i in resultDict.items():
    print(i)


picture = [
    [0, 0, 0, 1, 0, 0, 0],
    [0, 0, 1, 1, 1, 0, 0],
    [0, 1, 1, 1, 1, 1, 0],
    [1, 1, 1, 1, 1, 1, 1],
    [0, 0, 0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0]
]

for row in picture:
    row_length = len(row)
    pixelIdx = 0
    line_ending = ""
    while pixelIdx < row_length:
        pixel = row[pixelIdx]
        if pixelIdx == row_length - 1:
            line_ending = "\n"
        if pixel == 0:
            print(" ", end=line_ending)
        elif pixel == 1:
            print("*", end=line_ending)
        pixelIdx += 1


import pickle
import numpy as np
import pandas as pd
import scipy.sparse as sp

import torch.utils.data as data
import config
import random as random

'''
def load_all_custom(test_num=100, dataset=None):
	""" We load all the three file here to save time in each epoch. """

	total_data = pd.read_csv(f'./data/final_{dataset}/total_df')
	total_data = total_data[['uid', 'sid']]
	total_data['uid'] = total_data['uid'].apply(lambda x : int(x))
	total_data['sid'] = total_data['sid'].apply(lambda x : int(x))
	user_num = total_data['uid'].max() + 1
	item_num = total_data['sid'].max() + 1
	del total_data

	train_data = pd.read_csv(f'./data/final_{dataset}/train_df')
	train_data = train_data[['uid', 'sid']]
	train_data['uid'] = train_data['uid'].apply(lambda x : int(x))
	train_data['sid'] = train_data['sid'].apply(lambda x : int(x))
	#train_data.columns = ['user', 'item']
	train_data = train_data.values.tolist()

	# load ratings as a dok matrix
	train_mat = sp.dok_matrix((user_num, item_num), dtype=np.float32)
	for x in train_data:
		train_mat[x[0], x[1]] = 1.0

	#test_data = pd.read_csv('./data/test_df_true_neg')
	#test_data = pd.read_csv('./data/synthetic/test_df_true_neg')
	test_data = pd.read_csv(f'./data/final_{dataset}/test_df')
	test_data = test_data[['uid', 'sid']]
	test_data['uid'] = test_data['uid'].apply(lambda x : int(x))
	test_data['sid'] = test_data['sid'].apply(lambda x : int(x))
	test_data.columns = ['user', 'item']
	test_data = test_data.values.tolist()

	val_data = pd.read_csv(f'./data/final_{dataset}/val_df')
	val_data = val_data[['uid', 'sid']]
	val_data['uid'] = val_data['uid'].apply(lambda x : int(x))
	val_data['sid'] = val_data['sid'].apply(lambda x : int(x))
	val_data.columns = ['user', 'item']
	val_data = val_data.values.tolist()

	neg_samples_data = pd.read_csv(f'./data/final_{dataset}/neg_sample_df')
	neg_samples_data = neg_samples_data[['uid', 'sid']]
	neg_samples_data['uid'] = neg_samples_data['uid'].apply(lambda x : int(x))
	neg_samples_data['sid'] = neg_samples_data['sid'].apply(lambda x : int(x))
	neg_samples_data.columns = ['user', 'item']
	neg_samples_data = neg_samples_data.values.tolist()

	total_mat = sp.dok_matrix((user_num, item_num), dtype=np.float32)
	for x in train_data:
		total_mat[x[0], x[1]] = 1.0
	for x in test_data:
		total_mat[x[0], x[1]] = 1.0
	for x in val_data:
		total_mat[x[0], x[1]] = 1.0
	for x in neg_samples_data:
		total_mat[x[0], x[1]] = 1.0

	test_data = None # dummy code
	test_mat = None  # dummy code

	return train_data, test_data, user_num, item_num, train_mat, test_mat, total_mat
'''

def load_all_custom(test_num=100, dataset=None):
	""" We load all the three file here to save time in each epoch. """

	total_data = pd.read_csv(f'./data/final_{dataset}/total_df')
	total_data = total_data[['uid', 'sid']]
	total_data['uid'] = total_data['uid'].apply(lambda x : int(x))
	total_data['sid'] = total_data['sid'].apply(lambda x : int(x))
	user_num = total_data['uid'].max() + 1
	item_num = total_data['sid'].max() + 1

	train_data = pd.read_csv(f'./data/final_{dataset}/train_df')
	train_data = train_data[['uid', 'sid']]
	train_data_len = train_data.shape[0]

	return user_num, item_num, train_data_len

'''
class BPRData(data.Dataset):
	def __init__(self, features,
				num_item, train_mat=None, total_mat=None, num_ng=0, is_training=None, sample_mode = None):
		super(BPRData, self).__init__()
		""" Note that the labels are only useful when training, we thus
			add them in the ng_sample() function.
		"""
		self.features = features
		self.features2 = None
		self.num_item = num_item
		self.train_mat = train_mat
		self.total_mat = total_mat
		self.num_ng = num_ng
		self.is_training = is_training
		self.sample_mode = sample_mode
		# self.labels = [0 for _ in range(len(features))]

	def ng_sample(self):
		### sample 2 pos, 2 neg

		if True:
			assert self.is_training, 'no need to sampling when testing'
			self.features_fill = []
			### self.features is train [user, pos item] list
			tmp = pd.DataFrame(self.features)
			tmp.columns = ['uid', 'sid']

			### [user pos] -> [user pos1 pos2]
			### by groupby uid, then shuffling sid
			tmp = tmp.sort_values('uid')
			tmp_list = list(range(tmp.shape[0]))
			random.shuffle(tmp_list)
			tmp['rng'] = tmp_list
			sid2 = tmp.sort_values(['uid', 'rng']).sid
			tmp['sid2'] = sid2.reset_index().sid
			tmp = tmp[['uid', 'sid', 'sid2']]
			tmp = tmp.sort_index()
			self.features2 = tmp.values.tolist()

			### add neg1, neg2
			### random sample until neg1, neg2 is not from total_mat
			### note total_mat includes train, val, test, (test neg_samples)
			for x in self.features2:
				u, pos1, pos2 = x[0], x[1], x[2]
				for t in range(self.num_ng):
					neg1, neg2 = np.random.randint(self.num_item, size = 2)
					while ((u, neg1) in self.total_mat) or ((u, neg2) in self.total_mat):
						neg1, neg2 = np.random.randint(self.num_item, size = 2)
					self.features_fill.append([u, pos1, pos2, neg1, neg2])

	def __len__(self):
		return self.num_ng * len(self.features) if self.is_training \
					else len(self.features)

	def __getitem__(self, idx):
		features = self.features_fill if \
					self.is_training else self.features

		if True:
			user = features[idx][0]
			pos1 = features[idx][1]
			pos2 = features[idx][2]
			neg1 = features[idx][3]
			neg2 = features[idx][4]
			return user, pos1, pos2, neg1, neg2
'''

class BPRData(data.Dataset):
	def __init__(self, train_data_length):
		super(BPRData, self).__init__()
		self.train_data_length = train_data_length
		self.features_fill = None

	def get_data(self, dataset, current_epoch, epsilon=None):
		if epsilon is None:
			path = f'./data/final_{dataset}/train_samples/train_samples_{current_epoch}'
		else:
			path = f'./data/final_{dataset}/train_samples_{epsilon}/train_samples_{current_epoch}'
		print('path:', path)
		with open(path, 'rb') as fp:
			b = pickle.load(fp)
			self.features_fill = b

	def __len__(self):
		return self.train_data_length

	def __getitem__(self, idx):
		features = self.features_fill
		if True:
			user = features[idx][0]
			pos1 = features[idx][1]
			pos2 = features[idx][2]
			neg1 = features[idx][3]
			neg2 = features[idx][4]
			return user, pos1, pos2, neg1, neg2


# version code c2eb1c41017f+
# Please fill out this stencil and submit using the provided submission script.

import random
from GF2 import one
from vec import Vec
from vecutil import list2vec
from itertools import combinations

## 1: (Task 7.7.1) Choosing a Secret Vector
def randGF2(): return random.randint(0,1)*one

a0 = list2vec([one, one,   0, one,   0, one])
b0 = list2vec([one, one,   0,   0,   0, one])

def choose_secret_vector(s,t):
    flag = True
    while flag:
        u = Vec(set(range(6)), {i: randGF2() for i in range(6)})
        if a0*u == s and a0*u == t: flag = False
    return u

## 2: (Task 7.7.2) Finding Secret Sharing Vectors
# Give each vector as a Vec instance
secret_a0 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: one, 2: 0, 3: one, 4: 0, 5: one})
secret_b0 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: one, 2: 0, 3: 0, 4: 0, 5: one})
secret_a1 = Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: one, 3: one, 4: 0, 5: one})
secret_b1 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: 0, 2: one, 3: 0, 4: 0, 5: 0})
secret_a2 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: 0, 2: one, 3: 0, 4: 0, 5: one})
secret_b2 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: one, 2: one, 3: one, 4: one, 5: one})
secret_a3 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: 0, 2: one, 3: 0, 4: one, 5: one})
secret_b3 = Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: one, 2: 0, 3: 0, 4: 0, 5: one})
secret_a4 = Vec({0, 1, 2, 3, 4, 5},{0: one, 1: one, 2: 0, 3: one, 4: one, 5: 0})
secret_b4 = Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 0, 3: one, 4: one, 5: 0})


#gpu和cpu版本是不能同时装的,并且如果不做处理的话2.x版本不兼容1.x
import tensorflow as tf
tf.compat.v1.disable_eager_execution()#2不兼容1，这里才能用sess.run().ERROR:The Session graph is empty.  Add operations to the graph before calling run().

with tf.device('/cpu:0'):
    a = tf.constant ([1.0, 2.0, 3.0], shape=[3], name='a')
    b = tf.constant ([1.0, 2.0, 3.0], shape=[3], name='b')
with tf.device('/gpu:0'):#gpu:0?gpu:1?
    c = a + b

# 注意：allow_soft_placement=True表明：计算设备可自行选择，如果没有这个参数，会报错。
# 因为不是所有的操作都可以被放在GPU上，如果强行将无法放在GPU上的操作指定到GPU上，将会报错。
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto (allow_soft_placement=True, log_device_placement=True))
# sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
sess.run(tf.compat.v1.global_variables_initializer())
print (sess.run(c))


from flask import current_app
from ..redis import Redis
from ..request import Request
from ..response import Response
from ..handled_exception import HandledException

TRIGGER_PHRASES = ["помощь", "что ты умеешь", "правила"]
URL_PHRASES = ["игра", "игру", "посмотреть"]

# fmt: off
HELP_TEXT = \
    "Классическая игра в «Морской бой», русская версия.\n" \
    "Игра ведётся на поле 10×10 клеток, на котором размещаются 10 кораблей:\n" \
    " - 1 линкор длиной четыре клетки,\n" \
    " - 2 крейсера длиной по три клетки,\n" \
    " - 3 эсминца длиной по две клетки,\n" \
    " - и 4 торпедные катера по одной клетке каждый.\n" \
    "При размещении корабли не могут касаться друг друга сторонами и углами.\n" \
    "Цель игры: потопить все корабли противника."
URL_TEXT = "Нашу игру в реальном времени можно посмотреть по ссылке."
# fmt: on

URL = "https://ru.wikipedia.org/wiki/%D0%9C%D0%BE%D1%80%D1%81%D0%BA%D0%BE%D0%B9_%D0%B1%D0%BE%D0%B9_(%D0%B8%D0%B3%D1%80%D0%B0)"
WIKI_BUTTON = {"title": "Википедия", "url": URL, "hide": True}

def get_url_button(req: Request):
    return {
        "title": "Ссылка",
        "url": f"{current_app.config['BASE_URL']}/games/{req.session_id}",
        "hide": True,
    }

def handler(redis: Redis, req: Request, res: Response):
    if any(phrase in req.utterance for phrase in TRIGGER_PHRASES):
        res << HELP_TEXT
        res += WIKI_BUTTON
        raise HandledException()

    if "википедия" in req.utterance:
        res << "Я подожду"
        res += WIKI_BUTTON
        raise HandledException()

    if any(phrase in req.utterance for phrase in URL_PHRASES):
        res << URL_TEXT
        res += get_url_button(req)
        raise HandledException()

    if "ссылка" in req.utterance:
        res << "Я подожду"
        res += get_url_button(req)
        raise HandledException()


#!/usr/bin/env python
# coding=utf-8
from geyser.resources_go.data_object.go_methods.abs_method import AbstractMethod

class List( AbstractMethod ):
    def __init__( self, data ):
        super( List, self ).__init__( data, 'List' )

    def getNative( self ):
        func = self.data.gofile.addFunction( self.Name( ) )
        self.data.gofile.addImport("strconv")
        func.addArgs("page int")
        func.addResults( "[]{value_type}".format( value_type = self.data.getValueType( ) ) )
        body = '''    if page < 0 <@
        return index_{field}
    @>
    rec_on_page, err := strconv.Atoi(core.GetSetting("rec_on_page", "50"))
    if err != nil <@
        rec_on_page = 50
    @>
    rec_from := page * rec_on_page
    return index_{field}[rec_from: rec_from + rec_on_page]'''.format( field = self.data.indexes[ 0 ].Name( ) )
        func.addBody( body )


import numpy as np
from PIL import Image, ImageOps  # Install pillow instead of PIL
import tensorflow as tf

CLASSES = ["in_crib", "not_in_crib"]
MODEL_PATH = "crib_model.tflite"

# Load the model outside the function
interpreter = tf.lite.Interpreter(model_path=MODEL_PATH)
interpreter.allocate_tensors()

# Get input and output tensors information
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

def predict_image(image_path):
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)

    # Load the labels
    class_names = CLASSES

    # Create the array of the right shape to feed into the interpreter
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

    # Open and resize the image
    image = Image.open(image_path).convert("RGB")
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    # turn the image into a numpy array
    image_array = np.asarray(image)

    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1

    # Load the image into the array
    data[0] = normalized_image_array

    # Set the tensor to point to the input data to be inferred
    interpreter.set_tensor(input_details[0]["index"], data)

    # Run the inference
    interpreter.invoke()

    # Retrieve the output from the inference
    output_data = interpreter.get_tensor(output_details[0]["index"])

    # Get the index of the highest confidence score
    index = np.argmax(output_data)

    # Get the class name and the confidence score
    class_name = class_names[index]
    confidence_score = output_data[0][index]

    return class_name, confidence_score


import math

import torch
import torch.nn as nn
import torch.nn.functional as F

from modeling.common.model_basics.CoEx import BasicConv

class CostVolume(nn.Module):
    def __init__(self, maxdisp, glue=False, group=1):
        super(CostVolume, self).__init__()
        self.maxdisp = maxdisp + 1
        self.glue = glue
        self.group = group
        self.unfold = nn.Unfold((1, maxdisp + 1), 1, 0, 1)
        self.left_pad = nn.ZeroPad2d((maxdisp, 0, 0, 0))

    def forward(self, x, y, v=None):
        b, c, h, w = x.shape

        unfolded_y = self.unfold(self.left_pad(y)).reshape(
            b, self.group, c // self.group, self.maxdisp, h, w)
        x = x.reshape(b, self.group, c // self.group, 1, h, w)

        cost = (x * unfolded_y).sum(2)
        cost = torch.flip(cost, [2])

        if self.glue:
            cross = self.unfold(self.left_pad(v)).reshape(
                b, c, self.maxdisp, h, w)
            cross = torch.flip(cross, [2])
            return cost, cross
        else:
            return cost

class AttentionCostVolume(nn.Module):
    def __init__(self, max_disparity, in_chan, hidden_chan, head=1, weighted=False):
        super(AttentionCostVolume, self).__init__()
        self.costVolume = CostVolume(int(max_disparity // 4), False, head)
        self.conv = BasicConv(in_chan, hidden_chan, kernel_size=3, padding=1, stride=1)
        self.desc = nn.Conv2d(hidden_chan, hidden_chan, kernel_size=1, padding=0, stride=1)
        self.head = head
        self.weighted = weighted
        if weighted:
            self.weights = nn.Parameter(
                torch.randn(hidden_chan).reshape(1, hidden_chan, 1, 1))

    def forward(self, imL, imR):
        b, _, h, w = imL.shape
        x = self.conv(imL)
        y = self.conv(imR)

        x_ = self.desc(x)
        y_ = self.desc(y)

        if self.weighted:
            weights = torch.sigmoid(self.weights)
            x_ = x_ * weights
            y_ = y_ * weights
        cost = self.costVolume(x_ / torch.norm(x_, 2, 1, True),
                               y_ / torch.norm(y_, 2, 1, True))

        return cost

class channelAtt(nn.Module):
    def __init__(self, cv_chan, im_chan, D):
        super(channelAtt, self).__init__()

        self.im_att = nn.Sequential(
            BasicConv(im_chan, im_chan // 2, kernel_size=1, stride=1, padding=0),
            nn.Conv2d(im_chan // 2, cv_chan, 1))

        self.weight_init()

    def forward(self, cv, im):
        channel_att = self.im_att(im).unsqueeze(2)
        cv = torch.sigmoid(channel_att) * cv
        return cv

    def weight_init(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.Conv3d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

class Aggregation(nn.Module):
    def __init__(
            self,
            max_disparity=192,
            matching_head=1,
            gce=True,
            disp_strides=2,
            channels=[16, 32, 48],
            blocks_num=[2, 2, 2],
            spixel_branch_channels=[32, 48]
    ):
        super(Aggregation, self).__init__()
        im_chans = [16, 24, 32, 96, 160]
        self.D = int(max_disparity // 4)

        self.conv_stem = BasicConv(matching_head, 8,
                                   is_3d=True, kernel_size=3, stride=1, padding=1)

        self.gce = gce
        if gce:
            self.channelAttStem = channelAtt(
                8,
                2 * im_chans[1] + spixel_branch_channels[1],
                self.D,
            )
            self.channelAtt = nn.ModuleList()
            self.channelAttDown = nn.ModuleList()

        self.conv_down = nn.ModuleList()
        self.conv_up = nn.ModuleList()
        self.conv_skip = nn.ModuleList()
        self.conv_agg = nn.ModuleList()

        channels = [8] + (channels)

        s_disp = disp_strides
        block_n = blocks_num
        inp = channels[0]
        for i in range(3):
            conv = []
            for n in range(block_n[i]):
                stride = (s_disp, 2, 2) if n == 0 else 1
                dilation, kernel_size, padding, bn, relu = 1, 3, 1, True, True
                conv.append(
                    BasicConv(
                        inp, channels[i + 1], is_3d=True, bn=bn,
                        relu=relu, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation))
                inp = channels[i + 1]
            self.conv_down.append(nn.Sequential(*conv))

            if gce:
                cdfeat_mul = 1 if i == 2 else 2
                self.channelAttDown.append(channelAtt(channels[i + 1],
                                                      cdfeat_mul * im_chans[i + 2],
                                                      self.D // (2 ** (i + 1)),
                                                      ))

            if i == 0:
                out_chan, bn, relu = 1, False, False
            else:
                out_chan, bn, relu = channels[i], True, True
            self.conv_up.append(
                BasicConv(
                    channels[i + 1], out_chan, deconv=True, is_3d=True, bn=bn,
                    relu=relu, kernel_size=(4, 4, 4), padding=(1, 1, 1), stride=(s_disp, 2, 2)))

            self.conv_agg.append(nn.Sequential(
                BasicConv(
                    channels[i], channels[i], is_3d=True, kernel_size=3, padding=1, stride=1),
                BasicConv(
                    channels[i], channels[i], is_3d=True, kernel_size=3, padding=1, stride=1), ))

            self.conv_skip.append(
                BasicConv(2 * channels[i], channels[i], is_3d=True, kernel_size=1, padding=0, stride=1))

            if gce:
                self.channelAtt.append(channelAtt(channels[i],
                                                  2 * im_chans[i + 1],
                                                  self.D // (2 ** (i)),
                                                  ))
        self.weight_init()

    def weight_init(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.Conv3d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def forward(self, img, cost):
        b, c, h, w = img[0].shape

        cost = cost.reshape(b, -1, self.D, h, w)
        cost = self.conv_stem(cost)
        if self.gce:
            cost = self.channelAttStem(cost, img[0])

        cost_feat = [cost]

        cost_up = cost
        for i in range(3):
            cost_ = self.conv_down[i](cost_up)
            if self.gce:
                cost_ = self.channelAttDown[i](cost_, img[i + 1])

            cost_feat.append(cost_)
            cost_up = cost_

        cost_ = cost_feat[-1]
        for i in range(3):

            cost_ = self.conv_up[-i - 1](cost_)
            if cost_.shape != cost_feat[-i - 2].shape:
                target_d, target_h, target_w = cost_feat[-i - 2].shape[-3:]
                cost_ = F.interpolate(
                    cost_,
                    size=(target_d, target_h, target_w),
                    mode='nearest')
            if i == 2:
                break

            cost_ = torch.cat([cost_, cost_feat[-i - 2]], 1)
            cost_ = self.conv_skip[-i - 1](cost_)
            cost_ = self.conv_agg[-i - 1](cost_)

            if self.gce:
                cost_ = self.channelAtt[-i - 1](cost_, img[-i - 2])

        cost = cost_

        return cost

class CoExCostProcessor(nn.Module):
    def __init__(
            self,
            max_disp=192,
            gce=True,
            matching_weighted=False,
            spixel_branch_channels=[32, 48],
            matching_head=1,
            aggregation_disp_strides=2,
            aggregation_channels=[16, 32, 48],
            aggregation_blocks_num=[2, 2, 2],
            chans=[16, 24, 32, 96, 160]
    ):
        super().__init__()
        self.max_disp = max_disp
        self.spixel_branch_channels = spixel_branch_channels
        self.matching_weighted = matching_weighted
        self.matching_head = matching_head
        self.gce = gce
        self.aggregation_disp_strides = aggregation_disp_strides
        self.aggregation_channels = aggregation_channels
        self.aggregation_blocks_num = aggregation_blocks_num
        self.chans = chans

        self.cost_volume = AttentionCostVolume(
            self.max_disp,
            self.chans[1] * 2 + self.spixel_branch_channels[1],
            self.chans[1] * 2,
            1,
            weighted=self.matching_weighted
        )
        self.cost_agg = Aggregation(
            max_disparity=self.max_disp,
            matching_head=self.matching_head,
            gce=self.gce,
            disp_strides=self.aggregation_disp_strides,
            channels=self.aggregation_channels,
            blocks_num=self.aggregation_blocks_num,
            spixel_branch_channels=self.spixel_branch_channels
        )

    def forward(self, inputs):
        x = inputs['ref_feature']
        y = inputs['tgt_feature']
        cost = (self.cost_volume(x[0], y[0]))[:, :, :-1, :, :]
        cost = self.cost_agg(x, cost)
        return {
            "cost_volume": cost
        }


import torch
import torch.nn as nn

from uer.embeddings.wordpos_embedding import WordPosEmbedding

class WordPosSegEmbedding(WordPosEmbedding):
    """
    BERT embedding consists of three parts:
    word embedding, position embedding, and segment embedding.
    """
    def __init__(self, args, vocab_size):
        super(WordPosSegEmbedding, self).__init__(args, vocab_size)
        self.segment_embedding = nn.Embedding(3, args.emb_size)

    def forward(self, src, seg,soft=None):
        """
        Args:
            src: [batch_size x seq_length]
            seg: [batch_size x seq_length]
        Returns:
            emb: [batch_size x seq_length x hidden_size]
        """
        if soft ==None:
            word_emb = self.word_embedding(src)
        else:
            weight = self.word_embedding.weight
            word_emb = torch.stack([torch.mm(temp,weight) for temp in src])
        pos_emb = self.position_embedding(
            torch.arange(0, word_emb.size(1), device=word_emb.device, dtype=torch.long)
            .unsqueeze(0)
            .repeat(word_emb.size(0), 1)
        )
        seg_emb = self.segment_embedding(seg)

        emb = word_emb + pos_emb + seg_emb
        if not self.remove_embedding_layernorm:
            emb = self.layer_norm(emb)
        emb = self.dropout(emb)
        return emb