def CountBits(bits):
    count = 0
    while bits != 0:
        count += 1
        bits &= bits - 1
    return count
def SquareToFyle(square): return square & 0x7
def SquareToRank(square): return square >> 3
def CoordToSquare(fyle, rank): return (rank << 3) | fyle
def SquareToBB(square): return 0x1 << square
def CoordToBB(fyle, rank): return SquareToBB(CoordToSquare(fyle, rank))
def GenLineBB(square1, square2):
    fyle1 = SquareToFyle(square1)
    fyle2 = SquareToFyle(square2)
    rank1 = SquareToRank(square1)
    rank2 = SquareToRank(square2)
    ret = 0
    if fyle1 == fyle2:
        ret = SquareToBB(square1) | SquareToBB(square2)
        inc = 1 if rank2 > rank1 else -1
        while rank1 != rank2:
            ret |= CoordToBB(fyle1, rank1)
            rank1 += inc
    elif rank1 == rank2:
        ret = SquareToBB(square1) | SquareToBB(square2)
        inc = 1 if fyle2 > fyle1 else -1
        while fyle1 != fyle2:
            ret |= CoordToBB(fyle1, rank1)
            fyle1 += inc
    elif abs(fyle2 - fyle1) == abs(rank2 - rank1):
        ret = SquareToBB(square1) | SquareToBB(square2)
        fyle_inc = 1 if fyle2 > fyle1 else -1
        rank_inc = 1 if rank2 > rank1 else -1
        while (fyle1 != fyle2) and (rank1 != rank2):
            ret |= CoordToBB(fyle1, rank1)
            fyle1 += fyle_inc
            rank1 += rank_inc
    return ret
def GenDistance(square1, square2):
    fyle1 = SquareToFyle(square1)
    fyle2 = SquareToFyle(square2)
    rank1 = SquareToRank(square1)
    rank2 = SquareToRank(square2)
    return max((abs(fyle1 - fyle2), abs(rank1 - rank2)))
def GenIsEnPassant(e_square, to):
    if e_square == to:
        if (SquareToRank(e_square) == 2) or (SquareToRank(e_square) == 5):
            return "true"
    return "false"
def GenIs2StepMove(src, dst):
    if SquareToRank(src) == 1:
        if (dst - src) == 16: return "true"
    if SquareToRank(src) == 6:
        if (src - dst) == 16: return "true"
    return "false"
ROT = [\
    [\
         0,  1,  2,  3,  4,  5,  6,  7,\
         8,  9, 10, 11, 12, 13, 14, 15,\
        16, 17, 18, 19, 20, 21, 22, 23,\
        24, 25, 26, 27, 28, 29, 30, 31,\
        32, 33, 34, 35, 36, 37, 38, 39,\
        40, 41, 42, 43, 44, 45, 46, 47,\
        48, 49, 50, 51, 52, 53, 54, 55,\
        56, 57, 58, 59, 60, 61, 62, 63\
    ],\
    [\
        28, 21, 15, 10,  6,  3,  1,  0,\
        36, 29, 22, 16, 11,  7,  4,  2,\
        43, 37, 30, 23, 17, 12,  8,  5,\
        49, 44, 38, 31, 24, 18, 13,  9,\
        54, 50, 45, 39, 32, 25, 19, 14,\
        58, 55, 51, 46, 40, 33, 26, 20,\
        61, 59, 56, 52, 47, 41, 34, 27,\
        63, 62, 60, 57, 53, 48, 42, 35\
    ],\
    [\
         7, 15, 23, 31, 39, 47, 55, 63,\
         6, 14, 22, 30, 38, 46, 54, 62,\
         5, 13, 21, 29, 37, 45, 53, 61,\
         4, 12, 20, 28, 36, 44, 52, 60,\
         3, 11, 19, 27, 35, 43, 51, 59,\
         2, 10, 18, 26, 34, 42, 50, 58,\
         1,  9, 17, 25, 33, 41, 49, 57,\
         0,  8, 16, 24, 32, 40, 48, 56\
    ],\
    [\
         0,  2,  5,  9, 14, 20, 27, 35,\
         1,  4,  8, 13, 19, 26, 34, 42,\
         3,  7, 12, 18, 25, 33, 41, 48,\
         6, 11, 17, 24, 32, 40, 47, 53,\
        10, 16, 23, 31, 39, 46, 52, 57,\
        15, 22, 30, 38, 45, 51, 56, 60,\
        21, 29, 37, 44, 50, 55, 59, 62,\
        28, 36, 43, 49, 54, 58, 61, 63\
    ]\
]
R_ROT = [
    [\
         0,  1,  2,  3,  4,  5,  6,  7,\
         8,  9, 10, 11, 12, 13, 14, 15,\
        16, 17, 18, 19, 20, 21, 22, 23,\
        24, 25, 26, 27, 28, 29, 30, 31,\
        32, 33, 34, 35, 36, 37, 38, 39,\
        40, 41, 42, 43, 44, 45, 46, 47,\
        48, 49, 50, 51, 52, 53, 54, 55,\
        56, 57, 58, 59, 60, 61, 62, 63\
    ],\
    [\
         7,\
         6, 15,\
         5, 14, 23,\
         4, 13, 22, 31,\
         3, 12, 21, 30, 39,\
         2, 11, 20, 29, 38, 47,\
         1, 10, 19, 28, 37, 46, 55,\
         0,  9, 18, 27, 36, 45, 54, 63,\
         8, 17, 26, 35, 44, 53, 62,\
        16, 25, 34, 43, 52, 61,\
        24, 33, 42, 51, 60,\
        32, 41, 50, 59,\
        40, 49, 58,\
        48, 57,\
        56\
    ],\
    [\
        56, 48, 40, 32, 24, 16,  8,  0,
        57, 49, 41, 33, 25, 17,  9,  1,
        58, 50, 42, 34, 26, 18, 10,  2,
        59, 51, 43, 35, 27, 19, 11,  3,
        60, 52, 44, 36, 28, 20, 12,  4,
        61, 53, 45, 37, 29, 21, 13,  5,
        62, 54, 46, 38, 30, 22, 14,  6,
        63, 55, 47, 39, 31, 23, 15,  7
    ],\
    [\
         0,\
         8,  1,\
        16,  9,  2,\
        24, 17, 10,  3,\
        32, 25, 18, 11,  4,\
        40, 33, 26, 19, 12,  5,\
        48, 41, 34, 27, 20, 13,  6,\
        56, 49, 42, 35, 28, 21, 14,  7,\
        57, 50, 43, 36, 29, 22, 15,\
        58, 51, 44, 37, 30, 23,\
        59, 52, 45, 38, 31,\
        60, 53, 46, 39,\
        61, 54, 47,\
        62, 55,\
        63\
    ]\
]
MAGIC_SHIFT_V = [\
     0,  0,  0,  0,  0,  0,  0,  0,\
     8,  8,  8,  8,  8,  8,  8,  8,\
    16, 16, 16, 16, 16, 16, 16, 16,\
    24, 24, 24, 24, 24, 24, 24, 24,\
    32, 32, 32, 32, 32, 32, 32, 32,\
    40, 40, 40, 40, 40, 40, 40, 40,\
    48, 48, 48, 48, 48, 48, 48, 48,\
    56, 56, 56, 56, 56, 56, 56, 56\
]
MAGIC_SHIFT_D = [\
     0,\
     1,  1,\
     3,  3,  3,\
     6,  6,  6,  6,\
    10, 10, 10, 10, 10,\
    15, 15, 15, 15, 15, 15,\
    21, 21, 21, 21, 21, 21, 21,\
    28, 28, 28, 28, 28, 28, 28, 28,\
    36, 36, 36, 36, 36, 36, 36,\
    43, 43, 43, 43, 43, 43,\
    49, 49, 49, 49, 49,\
    54, 54, 54, 54,\
    58, 58, 58,\
    61, 61,\
    63\
]
MAGIC_SHIFT = []
for square in range(64):
    MAGIC_SHIFT += [[\
        MAGIC_SHIFT_V[ROT[0][square]], MAGIC_SHIFT_D[ROT[1][square]], \
        MAGIC_SHIFT_V[ROT[2][square]], MAGIC_SHIFT_D[ROT[3][square]]\
    ]]
MAGIC_MASK_V = [\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\
]
MAGIC_MASK_D = [\
    0x1,\
    0x3, 0x3,\
    0x7, 0x7, 0x7,\
    0xf, 0xf, 0xf, 0xf,\
    0x1f, 0x1f, 0x1f, 0x1f, 0x1f,\
    0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f,\
    0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\
    0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\
    0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f,\
    0x1f, 0x1f, 0x1f, 0x1f, 0x1f,\
    0xf, 0xf, 0xf, 0xf,\
    0x7, 0x7, 0x7,\
    0x3, 0x3,\
    0x1\
]
MAGIC_MASK = []
for square in range(64):
    MAGIC_MASK += [[\
        MAGIC_MASK_V[ROT[0][square]], MAGIC_MASK_D[ROT[1][square]], \
        MAGIC_MASK_V[ROT[2][square]], MAGIC_MASK_D[ROT[3][square]]\
    ]]

def BBToSquare(bb): return CountBits((bb & (-bb)) - 1)
def GetPoint(square, rot):
    return (SquareToBB(ROT[rot][square]) >> MAGIC_SHIFT[square][rot]) \
    & MAGIC_MASK[square][rot]
def ToBitboard(bit, square, rot):
    return SquareToBB(R_ROT[rot][BBToSquare(bit\
    << MAGIC_SHIFT[square][rot])])
def GenAttackMagic(square, pattern):
    ret0 = 0
    ret45 = 0
    ret90 = 0
    ret135 = 0
    bit0 = GetPoint(square, 0)
    bit45 = GetPoint(square, 1)
    bit90 = GetPoint(square, 2)
    bit135 = GetPoint(square, 3)
    for i in range(8):
        bit0 = (bit0 << 1) & MAGIC_MASK[square][0]
        bit45 = (bit45 << 1) & MAGIC_MASK[square][1]
        bit90 = (bit90 << 1) & MAGIC_MASK[square][2]
        bit135 = (bit135 << 1) & MAGIC_MASK[square][3]
        if bit0 != 0:
            ret0 |= ToBitboard(bit0, square, 0)
            if (bit0 & pattern) != 0: bit0 = 0
        if bit45 != 0:
            ret45 |= ToBitboard(bit45, square, 1)
            if (bit45 & pattern) != 0: bit45 = 0
        if bit90 != 0:
            ret90 |= ToBitboard(bit90, square, 2)
            if (bit90 & pattern) != 0: bit90 = 0
        if bit135 != 0:
            ret135 |= ToBitboard(bit135, square, 3)
            if (bit135 & pattern) != 0: bit135 = 0
    bit0 = GetPoint(square, 0)
    bit45 = GetPoint(square, 1)
    bit90 = GetPoint(square, 2)
    bit135 = GetPoint(square, 3)
    for i in range(8):
        bit0 = (bit0 >> 1) & MAGIC_MASK[square][0]
        bit45 = (bit45 >> 1) & MAGIC_MASK[square][1]
        bit90 = (bit90 >> 1) & MAGIC_MASK[square][2]
        bit135 = (bit135 >> 1) & MAGIC_MASK[square][3]
        if bit0 != 0:
            ret0 |= ToBitboard(bit0, square, 0)
            if (bit0 & pattern) != 0: bit0 = 0
        if bit45 != 0:
            ret45 |= ToBitboard(bit45, square, 1)
            if (bit45 & pattern) != 0: bit45 = 0
        if bit90 != 0:
            ret90 |= ToBitboard(bit90, square, 2)
            if (bit90 & pattern) != 0: bit90 = 0
        if bit135 != 0:
            ret135 |= ToBitboard(bit135, square, 3)
            if (bit135 & pattern) != 0: bit135 = 0
    return "{" + hex(ret0) + "ULL," + hex(ret45) + "ULL," \
    + hex(ret90) + "ULL," + hex(ret135) + "ULL}"

def GenPawnMovable(side, square, pattern):
    if side == 0:
        return "0x0ULL"

    ret = 0
    rank = SquareToRank(square)
    if side == 1:
        if rank == 1:
            if (GetPoint(square + 8, 2) & pattern) == 0:
                ret |= SquareToBB(square + 8)
                if (GetPoint(square + 16, 2)& pattern) == 0:
                    ret |= SquareToBB(square + 16)
            return hex(ret) + "ULL"
        elif rank == 7:
            return "0x0ULL"
        else:
            if (GetPoint(square + 8, 2)& pattern) == 0:
                ret |= SquareToBB(square + 8)
            return hex(ret) + "ULL"
    elif side == 2:
        if rank == 6:
            if (GetPoint(square - 8, 2) & pattern) == 0:
                ret |= SquareToBB(square - 8)
                if (GetPoint(square - 16, 2) & pattern) == 0:
                    ret |= SquareToBB(square - 16)
            return hex(ret) + "ULL"
        elif rank == 0:
            return "0x0ULL"
        else:
            if (GetPoint(square - 8, 2)& pattern) == 0:
                ret |= SquareToBB(square - 8)
            return hex(ret) + "ULL"

    return "0x0ULL"

if __name__ == "__main__":
    frame = """\
/* The MIT License (MIT)
 *
 * Copyright (c) 2013-2016 Hironori Ishibashi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * @file chess_util_extra.h
 * @author Hironori Ishibashi
 * @brief chess_util.h chess_util.cppで使うテーブル。 (Pythonで生成)
 */

#ifndef CHESS_UTIL_EXTRA_H_dd1bb50e_83bf_4b24_af8b_7c7bf60bc063
#define CHESS_UTIL_EXTRA_H_dd1bb50e_83bf_4b24_af8b_7c7bf60bc063

namespace Sayuri {{
  namespace MetaUtil {{
    /** CountBits()で使う、立っているビットの数のテーブル。 */
    constexpr char NUM_BIT16_TABLE[0xffff + 1] {{
      {0}
    }};

    /** 直線のビットボード。 */
    constexpr Bitboard LINE[NUM_SQUARES][NUM_SQUARES] {{
      {1}
    }};

    /** 直線のビットボード。 端点なし。 */
    constexpr Bitboard BETWEEN[NUM_SQUARES][NUM_SQUARES] {{
      {2}
    }};

    /** 距離のテーブル。 */
    constexpr int DISTANCE[NUM_SQUARES][NUM_SQUARES] {{
      {3}
    }};

    /** アンパッサン判定テーブル。 */
    constexpr bool IS_EN_PASSANT[NUM_SQUARES][NUM_SQUARES] {{
      {4}
    }};

    /** ポーンの2歩の動き判定テーブル。 */
    constexpr bool IS_2STEP_MOVE[NUM_SQUARES][NUM_SQUARES] {{
      {5}
    }};

    /** ライン攻撃のマジック用テーブル。 */
    constexpr Bitboard ATTACK_TABLE[NUM_SQUARES][0xff + 1][NUM_ROTS] {{
      {6}
    }};

    /** ポーンの動きのマジック用テーブル。 */
    constexpr Bitboard PAWN_MOVABLE_TABLE[NUM_SIDES][NUM_SQUARES][0xff + 1] {{
      {7}
    }};
  }}
}}  // namespace Sayuri

#endif"""

    # NUM_BIT16_TABLE
    elms0 = ""
    for num in range(0xffff + 1): elms0 += str(CountBits(num)) + ","
    elms0 = elms0[:-1]

    # LINE BETWEEN DISTANCE IS_EN_PASSANT IS_2STEP_MOVE
    elms1 = ""
    elms2 = ""
    elms3 = ""
    elms4 = ""
    elms5 = ""
    for square1 in range(64):
        elms1 += "{"
        elms2 += "{"
        elms3 += "{"
        elms4 += "{"
        elms5 += "{"
        for square2 in range(64):
            elms1 += hex(GenLineBB(square1, square2)) + ","
            elms2 += hex(GenLineBB(square1, square2) \
            & ~(SquareToBB(square1) | SquareToBB(square2))) + ","
            elms3 += str(GenDistance(square1, square2)) + ","
            elms4 += GenIsEnPassant(square1, square2) + ","
            elms5 += GenIs2StepMove(square1, square2) + ","
        elms1 = elms1[:-1]
        elms2 = elms2[:-1]
        elms3 = elms3[:-1]
        elms4 = elms4[:-1]
        elms5 = elms5[:-1]
        elms1 += "},"
        elms2 += "},"
        elms3 += "},"
        elms4 += "},"
        elms5 += "},"
    elms1 = elms1[:-1]
    elms2 = elms2[:-1]
    elms3 = elms3[:-1]
    elms4 = elms4[:-1]
    elms5 = elms5[:-1]

    # ATTACK_TABLE
    elms6 = ""
    for square in range(64):
        elms6 += "{"
        for pattern in range(0xff + 1):
            elms6 += GenAttackMagic(square, pattern) + ","
        elms6 = elms6[:-1]
        elms6 += "},"
    elms6 = elms6[:-1]

    # PAWN_MOVABLE_TABLE
    elms7 = ""
    for side in range(3):
        elms7 += "{"
        for square in range(64):
            elms7 += "{"
            for pattern in range(0xff + 1):
                elms7 += GenPawnMovable(side, square, pattern) + ","
            elms7 = elms7[:-1]
            elms7 += "},"
        elms7 = elms7[:-1]
        elms7 += "},"
    elms7 = elms7[:-1]

    # 出力。
    print(frame.format(elms0, elms1, elms2, elms3, elms4, elms5, elms6, elms7))


"""Added switch history

Revision ID: b85b82664c28
Revises: 94ccd671cbcd
Create Date: 2021-03-26 15:56:26.634107

"""
from alembic import op
import sqlalchemy as sa

from its_on.utils import AwareDateTime

# revision identifiers, used by Alembic.
revision = 'b85b82664c28'
down_revision = '94ccd671cbcd'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('switch_history',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('switch_id', sa.Integer(), nullable=True),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('new_value', sa.String(length=64), nullable=False),
    sa.Column('changed_at', AwareDateTime(), nullable=False),
    sa.ForeignKeyConstraint(['switch_id'], ['switches.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('switch_history')
    # ### end Alembic commands ###


from time import sleep

from Persona import Persona
from User import User

class BingePersona(Persona):

    def __init__(self, user, hash, leave, other_args):
        super().__init__(user, hash, leave, other_args)

        # set if leech (False by default)
        if len(other_args) > 0:
            self.leech = int(other_args[0])
        else:
            self.leech = 0

    def act(self):
        self.user.visit("http://host/webplayer.html")
        if self.leech == 1:
            self.user.toggle_gateway()
        self.user.watch_hash(self.hash)

        self.sleep_until(self.get_duration())


from pprint import pprint
from riko.bado import coroutine
from riko.collections import SyncPipe, AsyncPipe

p232_conf = {
    "attrs": [
        {"value": "www.google.com", "key": "link"},
        {"value": "google", "key": "title"},
        {"value": "empty", "key": "author"},
    ]
}

p421_conf = {"rule": [{"find": "empty", "param": "first", "replace": "ABC"}]}

def pipe(test=False):
    stream = (
        SyncPipe("itembuilder", conf=p232_conf, test=test)
        .strreplace(conf=p421_conf, field="author", assign="author")
        .list
    )

    for i in stream:
        pprint(i)

    return stream

@coroutine
def async_pipe(reactor, test=False):
    stream = yield (
        AsyncPipe("itembuilder", conf=p232_conf, test=test)
        .strreplace(conf=p421_conf, field="author", assign="author")
        .list
    )

    for i in stream:
        pprint(i)


from rest_framework.exceptions import *
from common.log import *
from common.env import *

class RespNotFound(APIException):
    status_code = status.HTTP_404_NOT_FOUND
#    default_detail = _('Not found.')

class APgentResponseMessgae(object):
    def __init__(self):
        self.response = dict()

    def set_response_value(self, status_code, response_msg, is_successful):
        if status_code != 200:
            response = response_msg.response
            try:
                explanation = response.json()['message']
            except ValueError:
                explanation = (response.content or '').strip()
        else:
            explanation = response_msg

        self.response['status_code'] = status_code
        self.response['error_msg'] = explanation
        self.response['isSuccessful'] = is_successful
        log_debug(LOG_MODULE_RESPONSE, "Set Response = ", str(self.response))

        return self.response

    @property
    def status_code(self):
        return self.response['status_code']

    @property
    def error_msg(self):
        return self.response['error_msg']

    @property
    def is_successful(self):
        return self.response['isSuccessful']

    def make_response_body(self, body_data):
        if not body_data:
            body_data = dict()

        body_data['header'] =  {
            'resultCode': self.status_code,
            'resultMessage': self.error_msg,
            'isSuccessful': self.is_successful
        }
        log_debug(LOG_MODULE_RESPONSE, "Response Body = ", str(body_data))
        return body_data

def response_make_simple_success_body():
    response = APgentResponseMessgae()
    response.set_response_value(200, "Successful", True)
    data = response.make_response_body(None)
    return data


# -*- coding: utf-8 -*-
import numpy as np
from collections import deque, OrderedDict
from datetime import datetime
from common.funcs import *
from common.layers import *
from common.optimizers import *

class Planner_separate():

    def __init__(self, name, env, state_dim, action_dim):

        #name：このPlannerインスタンスの名前
        #env：このPlannerインスタンスが対象とする環境
        #state_dim：このPlannerインスタンスが認識する状態の要素数
        #action_dim：このPlannerインスタンスが認識する行動の要素数

        self._name = name
        self._env = env
        self._state_dim = state_dim
        self._action_dim = action_dim

        ###Layersの定義###

        output_dim_afn1 = self._state_dim*10
        output_dim_afn3 = self._action_dim*10
        output_dim_afn2 = np.ceil( np.sqrt(output_dim_afn1*output_dim_afn3) ).astype(np.int)

        ##ActorのLayersの定義##

        self._layers_actor = OrderedDict()

        #①Affine 「afn1_actor」　instance of Affine
        opt_afn1_actor = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn1_actor = Affine(name="afn1_actor", input_shape=(state_dim,), output_shape=(output_dim_afn1,), optimizer=opt_afn1_actor,
                        init_weight_option="xavier")
        self._layers_actor[afn1_actor.name] = afn1_actor
        prev_layer = afn1_actor

        #②Tanh　「tanh_afn1_actor」　instance of Tanh
        tanh_afn1_actor = Tanh(name="tanh_afn1_actor", input_shape=prev_layer.output_shape)
        self._layers_actor[tanh_afn1_actor.name] = tanh_afn1_actor
        prev_layer = tanh_afn1_actor

        #③Affine 「afn2_actor」　instance of Affine
        opt_afn2_actor = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn2_actor = Affine(name="afn2_actor", input_shape=prev_layer.output_shape, output_shape=(output_dim_afn2,), optimizer=opt_afn2_actor,
                        init_weight_option="xavier")
        self._layers_actor[afn2_actor.name] = afn2_actor
        prev_layer = afn2_actor

        #④Tanh　「tanh_afn2_actor」　instance of Tanh
        tanh_afn2_actor = Tanh(name="tanh_afn2_actor", input_shape=prev_layer.output_shape)
        self._layers_actor[tanh_afn2_actor.name] = tanh_afn2_actor
        prev_layer = tanh_afn2_actor

        #⑤Affine 「afn3_actor」　instance of Affine
        opt_afn3_actor = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn3_actor = Affine(name="afn3_actor", input_shape=prev_layer.output_shape, output_shape=(output_dim_afn3,), optimizer=opt_afn3_actor,
                        init_weight_option="xavier")
        self._layers_actor[afn3_actor.name] = afn3_actor
        prev_layer = afn3_actor

        #⑥Tanh　「tanh_afn3_actor」　instance of Tanh
        tanh_afn3_actor = Tanh(name="tanh_afn3_actor", input_shape=prev_layer.output_shape)
        self._layers_actor[tanh_afn3_actor.name] = tanh_afn3_actor
        prev_layer = tanh_afn3_actor

        #Actor　平均μの出力のlayers　中身はAffine1個とTanh1個
        opt_afn_actor_mu = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        self._out_actor_mu = Actor_Output(name="out_actor_mu", input_shape=prev_layer.output_shape,
                                          output_shape=(action_dim,), optimizer=opt_afn_actor_mu)
        #self._layers_actorに含めないので注意

        #Actor　分散varのlog(var)の出力のlayers　中身はAffine1個とTanh1個
        opt_afn_actor_log_var = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        self._out_actor_log_var = Actor_Output(name="out_actor_log_var", input_shape=prev_layer.output_shape,
                                               output_shape=(action_dim,), optimizer=opt_afn_actor_log_var)
        #self._layers_actorに含めないので注意

        ##ActorのLayersの定義　終わり##

        ##CriticのLayersの定義##

        self._layers_critic = OrderedDict()

        #①Affine 「afn1_critic」　instance of Affine
        opt_afn1_critic = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn1_critic = Affine(name="afn1_critic", input_shape=(state_dim,), output_shape=(output_dim_afn1,), optimizer=opt_afn1_critic,
                        init_weight_option="xavier")
        self._layers_critic[afn1_critic.name] = afn1_critic
        prev_layer = afn1_critic

        #②Tanh　「tanh_afn1_critic」　instance of Tanh
        tanh_afn1_critic = Tanh(name="tanh_afn1_critic", input_shape=prev_layer.output_shape)
        self._layers_critic[tanh_afn1_critic.name] = tanh_afn1_critic
        prev_layer = tanh_afn1_critic

        #③Affine 「afn2_critic」　instance of Affine
        opt_afn2_critic = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn2_critic = Affine(name="afn2_critic", input_shape=prev_layer.output_shape, output_shape=(output_dim_afn2,), optimizer=opt_afn2_critic,
                        init_weight_option="xavier")
        self._layers_critic[afn2_critic.name] = afn2_critic
        prev_layer = afn2_critic

        #④Tanh　「tanh_afn2_critic」　instance of Tanh
        tanh_afn2_critic = Tanh(name="tanh_afn2_critic", input_shape=prev_layer.output_shape)
        self._layers_critic[tanh_afn2_critic.name] = tanh_afn2_critic
        prev_layer = tanh_afn2_critic

        #⑤Affine 「afn3_critic」　instance of Affine
        opt_afn3_critic = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn3_critic = Affine(name="afn3_critic", input_shape=prev_layer.output_shape, output_shape=(output_dim_afn3,), optimizer=opt_afn3_critic,
                        init_weight_option="xavier")
        self._layers_critic[afn3_critic.name] = afn3_critic
        prev_layer = afn3_critic

        #⑥Tanh　「tanh_afn3_critic」　instance of Tanh
        tanh_afn3_critic = Tanh(name="tanh_afn3_critic", input_shape=prev_layer.output_shape)
        self._layers_critic[tanh_afn3_critic.name] = tanh_afn3_critic
        prev_layer = tanh_afn3_critic

        #⑦Affine 「afn4_critic」　instance of Affine　出力layer　活性化関数は無し（linear）
        opt_afn4_critic = Adam(lr=0.001, rho1=0.9, rho2=0.999)
        afn4_critic = Affine(name="afn4_critic", input_shape=prev_layer.output_shape, output_shape=(1,), optimizer=opt_afn4_critic,
                        init_weight_option="xavier")
        self._layers_critic[afn4_critic.name] = afn4_critic

        ##CriticのLayersの定義　終わり##

        #ActorとCritic　Lossの定義##

        #ActorのLoss
        self._loss_actor = Actor_Loss("loss_actor")

        #criticのLoss
        self._loss_critic = Critic_Loss("loss_critic")

        ##ActorとCritic　Lossの定義　終わり##

    def predict_best_action(self, a_state):
        #最適な行動を推測

        if a_state.ndim==1:
            a_state = a_state.reshape(1, self._state_dim)
        elif a_state.shape[0]!=1:
            raise ValueException("a_stateは1件だけにしてください。1件のstateについてbest actionを推測します。")

        #Actorから正規分布の平均μと分散varのlog_varを得る。
        #どちらも(1, action_dim)
        mu, log_var = self._forward_output_actor(a_state, train_flg=False)

        #分散var
        #(1, action_dim)
        var = np.exp(log_var)

        #muとvarからバッチ数のaxis=0を削除し、(action_dim,)にする
        mu = mu[0]
        var = var[0]

        #平均μと分散varの正規分布からサンプリング
        best_action = np.random.normal(loc=mu, scale=np.sqrt(var))

        return best_action

    def _forward_output_actor(self, state, train_flg):
        #Actorの出力
        #分岐以外の、勾配に影響を与える演算はしないこと

        if state.ndim==1:
            state = state.reshape(1, self._state_dim)

        ##Actor中間layersの出力##
        #出力値を「m」とする
        #(N, M) 「M」は最後の中間layerのAffineのニューロン数
        x = state
        for layer in self._layers_actor.values():
            x = layer.forward(x, train_flg)
        m = x
        ##Actor中間layersの出力　終わり##

        ##Actorの出力##

        #2つの出力layersにActor中間layersの出力を渡す。
        #Actor中間layersの出力が2分岐する。

        #Actorのμ出力layersからの出力 (N, action_dim)
        mu = self._out_actor_mu.forward(m, train_flg)

        #Actorのlog(var)出力layersからの出力 (N, action_dim)
        log_var = self._out_actor_log_var.forward(m, train_flg)

        ##Actorの出力　終わり##

        return mu, log_var

    def _backward_output_actor(self, d_mu, d_log_var):
        #Actorの出力から最初までの誤差逆伝播

        ##Actorの出力の逆伝播##

        #Actorのμ出力部分の逆伝播
        #(N, M) 「M」は共有最終layerのAffineのニューロン数
        d_m_mu = self._out_actor_mu.backward(d_mu)

        #Actorのlog(var)出力部分の逆伝播
        #(N, M) 「M」はActor中間layersの最終layerのAffineのニューロン数
        d_m_log_var = self._out_actor_log_var.backward(d_log_var)

        #forwardでActor中間layersの最終layerの出力mを
        #Actorのμ出力、Actorのlog(var)出力
        #に2分岐したので、これらから逆伝播してきた勾配を合算する。
        d_m = d_m_mu + d_m_log_var

        ##Actorの出力の逆伝播　終わり##

        ##Actor中間layers（最初まで）の逆伝播##
        #(N, state_dim)
        layers_shared = list(self._layers_actor.values())
        layers_shared.reverse()
        d_out = d_m
        for layer in layers_shared:
            d_out = layer.backward(d_out)
        d_state = d_out
        ##Actor中間layers（最初まで）の逆伝播　終わり##

        return d_state

    def _forward_output_critic(self, state, train_flg):
        #Criticの出力
        #分岐以外の、勾配に影響を与える演算はしないこと

        if state.ndim==1:
            state = state.reshape(1, self._state_dim)

        x = state
        for layer in self._layers_critic.values():
            x = layer.forward(x, train_flg)
        V = x

        return V

    def _backward_output_critic(self, d_V):
        #Criticの出力から最初までの誤差逆伝播

        layers_shared = list(self._layers_critic.values())
        layers_shared.reverse()
        d_out = d_V
        for layer in layers_shared:
            d_out = layer.backward(d_out)
        d_state = d_out

        return d_state

    def _forward_loss_actor(self, state, action, G, V, softplus_to_advantage, weight_decay_lmd):
        #Actorのloss
        #action, Gのもとになったstateは、引数stateと同じ並びであること
        #分岐以外の、勾配に影響を与える演算はしないこと
        #V：Criticの出力　(N, 1)

        ##Actorの出力##
        #Actorの出力μ、Actorの出力log(var)
        #(N, action_dim), (N, action_dim),
        mu, log_var = self._forward_output_actor(state, train_flg=True)
        ##Actorの出力　終わり##

        ##Actorのloss##
        La = self._loss_actor.forward(mu, log_var, action, V, G, softplus_to_advantage)
        ##Actorのloss　終わり##

        #荷重減衰
        if weight_decay_lmd > 0:
            sum_all_weights_square = self._sum_all_weights_square(role=0)
            La = La + 0.5*weight_decay_lmd*sum_all_weights_square

        return La

    def _backward_loss_actor(self, d_La=1):
        #Actorのlossから最初までの一気通貫の誤差逆伝播

        ##Actorのloss　逆伝播##
        #どちらも(N, action_dim)
        d_mu, d_log_var = self._loss_actor.backward(d_La)
        ##Actorのloss　逆伝播　終わり##

        ##Actorの出力と中間Layersの逆伝播　最初まで##
        #(N, state_dim)
        d_states = self._backward_output_actor(d_mu, d_log_var)
        ##Actorの出力と中間Layersの逆伝播　最初まで　終わり##

        return d_states

    def _forward_loss_critic(self, state, G, weight_decay_lmd):
        #Criticのloss
        #Gのもとになったstateは、引数stateと同じ並びであること
        #分岐以外の、勾配に影響を与える演算はしないこと

        ##Criticの出力##
        #Criticの出力V
        #(N, 1),
        V = self._forward_output_critic(state, train_flg=True)
        ##Criticの出力　終わり##

        ##Criticのloss##
        Lc = self._loss_critic.forward(V, G)  #Gは教師信号として使用される
        ##Criticのloss　終わり##

        #荷重減衰
        if weight_decay_lmd > 0:
            sum_all_weights_square = self._sum_all_weights_square(role=1)
            Lc = Lc + 0.5*weight_decay_lmd*sum_all_weights_square

        #戻り値にVがあるのは、呼び出し元で使うから
        return Lc, V

    def _backward_loss_critic(self, d_Lc=1):
        #Criticのlossから最初までの一気通貫の誤差逆伝播

        ##Criticのloss　逆伝播##
        #(N, 1)
        d_V = self._loss_critic.backward(d_Lc)
        ##Criticのloss　逆伝播#　終わり##

        ##Criticの出力と中間Layersの逆伝播　最初まで##
        #(N, state_dim)
        d_states = self._backward_output_critic(d_V)
        ##Criticの出力と中間Layersの逆伝播　最初まで　終わり##

        return d_states

    def train(self, episodes, steps_per_episode, gamma=0.99, metrics=1, standardize_G=True, softplus_to_advantage=False,
              weight_decay_lmd=0, verbose_interval=100):

        start_time = datetime.now()

        #エピソード毎の記録list生成
        loss_episodes = [] #エピソード毎のlossのlist
        loss_actor_episodes = [] #エピソード毎のActorのlossのlist
        loss_critic_episodes = [] #エピソード毎のCriticのlossのlist
        step_count_episodes = [] #エピソード毎のステップ数のlist
        score_episodes = [] #エピソード毎のスコア（Σステップ毎の即時reward）のlist

        episode_count = 0
        step_count_total = 0
        best_step_count = 0 #今までのepisodeの中で最も多いstep回数
        best_score = -np.inf #今までのepisodeの中で最も大きいscore
        best_metrics_count = 0

        #エピソード反復
        for ep in range(0, episodes):
            #1エピソード

            #このエピソード中の全ステップ記録のlist生成
            state_steps_episode = []
            action_steps_episode = []
            reward_steps_episode = []
            next_state_steps_episode = []

            step_count_ep = 0
            score_ep = 0
            save_temp_params = False

            #環境の開始時点にagentをセット
            curr_st = self._env.reset()

            #ステップ反復
            for st in range(steps_per_episode):
                #1ステップ

                #ステップ実行
                action_predicted = self.predict_best_action(curr_st)
                next_st, reward_earned, done, info = self._env.step(action_predicted)

                #このエピソード中の全ステップ記録のlistに追加
                state_steps_episode.append(curr_st)
                action_steps_episode.append(action_predicted)
                reward_steps_episode.append(reward_earned)
                next_state_steps_episode.append(next_st)

                step_count_ep += 1
                step_count_total += 1

                #ステップ反復終了判定　steps_per_episodeに達したかenvからdone=Trueが返ってきたか
                #終了するならbreak
                if step_count_ep>=steps_per_episode or done==True:
                    break
                else:
                    curr_st = next_st

            #ステップ反復　for　終わり

            #このエピソードのスコア算出
            #各ステップの即時報酬の単純合計
            score_ep = sum(reward_steps_episode)

            #このエピソードの”成績”が過去最高なら、パラメーターを退避

            if metrics==0 and (step_count_ep>=best_step_count):
                #step countで成績を計測
                best_step_count = step_count_ep
                best_metrics_count += 1
                save_temp_params = True
            elif metrics==1 and (score_ep>=best_score):
                #scoreで成績を計測
                best_score = score_ep
                best_metrics_count += 1
                save_temp_params = True

            if save_temp_params==True:
                #パラメーターを一時退避
                self._keep_temporarily_all_learnable_params()

            #割引報酬和「G」算出
            li_G = self._calc_G_of_step_in_an_episode(reward_steps_episode, gamma)

            #割引報酬和Gの標準化　引数standardize_Gでやるかやらないか指定される
            if standardize_G==True:
                Gs = standardize(li_G, with_mean=False).reshape(-1, 1) #平均を0にしない標準化
            else:
                Gs = np.array(li_G).reshape(-1, 1)

            #ActorとCriticのloss算出の順伝播　引数の準備
            states = np.array(state_steps_episode)
            actions = np.array(action_steps_episode)

            #Critic　loss算出の順伝播　Actorで使用するVも取得
            loss_critic_ep, Vs = self._forward_loss_critic(state=states, G=Gs, weight_decay_lmd=weight_decay_lmd)
            #Critic　逆伝播
            _ = self._backward_loss_critic(d_Lc=1)
            #Critic　パラメーター更新
            self._update_all_learnable_params(role=1, weight_decay_lmd=weight_decay_lmd)

            #Actor　loss算出の順伝播
            loss_actor_ep = self._forward_loss_actor(state=states, action=actions, G=Gs, V=Vs,
                                                     softplus_to_advantage=softplus_to_advantage,
                                                     weight_decay_lmd=weight_decay_lmd)
            #Actor　逆伝播
            _ = self._backward_loss_actor(d_La=1)
            #Actor　パラメーター更新
            self._update_all_learnable_params(role=0, weight_decay_lmd=weight_decay_lmd)

            #このエピソードの記録をエピソード毎の記録listに追加
            step_count_episodes.append(step_count_ep) #ステップ数
            loss_actor_episodes.append(loss_actor_ep) #Actorのloss
            loss_critic_episodes.append(loss_critic_ep) #Criticのloss
            score_episodes.append(score_ep) #score

            if verbose_interval>0 and ( (ep+1)%verbose_interval==0 or ep==0 or (ep+1)==episodes ):

                time_string = datetime.now().strftime('%H:%M:%S')

                if metrics==0:
                    best_metrics_string = " best step count:" + str(best_step_count) + "(" + str(best_metrics_count) + "回)"
                elif metrics==1:
                    best_metrics_string = " best score:" + str(best_score) + "(" + str(best_metrics_count) + "回)"
                else:
                    best_metrics_string=""

                if save_temp_params==True:
                    params_saved_string = " ベストなパラメーターを一時退避"
                else:
                    params_saved_string = ""

                print("Episode:" + str(ep) + " score:" + str(score_ep) + " step count:" + str(step_count_ep) + \
                      " loss_actor:" + str(loss_actor_ep) + " loss_critic:" + str(loss_critic_ep) + \
                      best_metrics_string + params_saved_string + " time:" + time_string)

            episode_count += 1

        #エピソード反復　for　終わり

        #一時退避させてたパラメーターを戻す
        self._adopt_all_learnable_params_kept_temporarily()
        if verbose_interval>0:
            print("一時退避したベストなパラメーターを正式採用")

        end_time = datetime.now()

        processing_time_total = end_time - start_time #総処理時間　datetime.timedelta
        processing_time_total_string = timedelta_HMS_string(processing_time_total) #総処理時間の文字列表現

        #resultを生成し、エピソード毎の記録listや引数やらを追加
        result = {}
        result["name"] = self._name
        result["episode_count"] = episode_count
        result["loss_actor_episodes"] = loss_actor_episodes
        result["loss_critic_episodes"] = loss_critic_episodes
        result["step_count_episodes"] = step_count_episodes
        result["score_episodes"] = score_episodes
        result["step_count_total"] = step_count_total
        result["processing_time_total_string"] = processing_time_total_string
        result["processing_time_total"] = processing_time_total
        #以下引数
        result["episodes"] = episodes
        result["steps_per_episode"] = steps_per_episode
        result["gamma"] = gamma
        result["metrics"] = metrics
        result["softplus_to_advantage"] = softplus_to_advantage
        result["weight_decay_lmd"] = weight_decay_lmd

        return result

    def _calc_G_of_step_in_an_episode(self, li_reward_in_an_episode, gamma):
        #エピソード1個分の記録中の各ステップの割引報酬和Gを計算する。
        #li_reward_in_an_episode：エピソード1個分の全ステップのrewardのlist。
        #戻り値は、このエピソード1個の中の各ステップのsum_of_discounted_rewardsのlist。listのlenはステップ数。
        #※もしExperience Replay方式にする場合、ここは、エピソード1個分の全ステップ記録にGを付加し、そのエピソード1個分の記録を
        #経験バッファに追加、となる。

        li_G = []
        for t, r in enumerate(li_reward_in_an_episode):
            li_discounted_rewards_future = \
            [r_following * (gamma**t_diff) for t_diff, r_following in enumerate(li_reward_in_an_episode[t:])]
            sum_of_discounted_rewards = sum(li_discounted_rewards_future)
            li_G.append(sum_of_discounted_rewards)

        return li_G

    def _update_all_learnable_params(self, role, weight_decay_lmd):
        #role：Actor（0）かCritic（1）か
        #指定されたroleの全Layersのtrainableなパラメーターを一括更新する。

        if role==0:
            #Actor
            for layer in self._layers_actor.values():
                if layer.trainable == True:
                    layer.update_learnable_params(weight_decay_lmd)
            self._out_actor_mu.update_learnable_params(weight_decay_lmd)
            self._out_actor_log_var.update_learnable_params(weight_decay_lmd)
        elif role==1:
            #Critic
            for layer in self._layers_critic.values():
                if layer.trainable == True:
                    layer.update_learnable_params(weight_decay_lmd)

    def save_params_in_file(self, file_dir, file_name=""):
        #このモデルインスタンスのパラメーターをファイル保存する。

        if file_name=="":
            file_name = self._name + ".pickle"

        file_path = file_dir + file_name

        #Dictionaryにして保存。keyはlayer.name。
        #all_params_dic(Dictionary)
        # --learnable layer1の保存したいパラメーターのtuple(weightsのndarray, biasesのndarray)
        # --learnable layer2の保存したいパラメーターのtuple(weightsのndarray, biasesのndarray)
        #　・
        #　・
        # --Actor outout layersの保存したいパラメーターのtuple(weightsのndarray, biasesのndarray)

        all_params_dic = {}

        #Actorのパラメーター分
        for layer in self._layers_actor.values():
            if layer.trainable == True:
                params_tpl = layer.copy_params()
                all_params_dic[layer.name] = params_tpl
        all_params_dic[self._out_actor_mu.name] = self._out_actor_mu.copy_params()
        all_params_dic[self._out_actor_log_var.name] = self._out_actor_log_var.copy_params()

        #Criticのパラメーター分
        for layer in self._layers_critic.values():
            if layer.trainable == True:
                params_tpl = layer.copy_params()
                all_params_dic[layer.name] = params_tpl

        save_pickle_file(all_params_dic, file_path)

        return file_name

    def overwrite_params_from_file(self, file_path):
        #このモデルインスタンスの全パラメーターを、ファイル保存されている別の物に差し替える。

        param_layer_tpls_dic = read_pickle_file(file_path)

        for layer_name in param_layer_tpls_dic.keys():

            #上書きするパラメーターをLayer毎に取り出す
            layer_params_tpl = param_layer_tpls_dic[layer_name]

            #コピー先Layer毎に上書きする。
            #名前が同じLayerがコピー先Layer。

            if layer_name in self._layers_actor.keys():
                #Actor　中間layers
                to_layer = self._layers_actor[layer_name]
                if to_layer.trainable==True:
                    #ltrainableなLayer　上書き
                    to_layer.overwrite_params(layer_params_tpl)
            elif layer_name==self._out_actor_mu.name:
                #Actor　μ出力layers
                self._out_actor_mu.overwrite_params(layer_params_tpl)
            elif layer_name==self._out_actor_log_var.name:
                #Actor　log(var)出力layers
                self._out_actor_log_var.overwrite_params(layer_params_tpl)
            elif layer_name in self._layers_critic.keys():
                #Critic　全layers
                to_layer = self._layers_critic[layer_name]
                if to_layer.trainable==True:
                    #ltrainableなLayer　上書き
                    to_layer.overwrite_params(layer_params_tpl)

    def _keep_temporarily_all_learnable_params(self):

        #配下の各trainableなLayerに対し、現時点でのlearnableパラメーターの一時退避を指示

        #Actor
        for layer in self._layers_actor.values():
            if layer.trainable == True:
                layer.keep_temporarily_learnable_params()
        self._out_actor_mu.keep_temporarily_learnable_params()
        self._out_actor_log_var.keep_temporarily_learnable_params()

        #Critic
        for layer in self._layers_critic.values():
            if layer.trainable == True:
                layer.keep_temporarily_learnable_params()

    def _adopt_all_learnable_params_kept_temporarily(self):

        #配下の各trainableなLayerに対し、一時退避していたlearnableパラメーターの正式採用を指示

        #Actor
        for layer in self._layers_actor.values():
            if layer.trainable == True:
                layer.adopt_learnable_params_kept_temporarily()
        self._out_actor_mu.adopt_learnable_params_kept_temporarily()
        self._out_actor_log_var.adopt_learnable_params_kept_temporarily()

        #Critic
        for layer in self._layers_critic.values():
            if layer.trainable == True:
                layer.adopt_learnable_params_kept_temporarily()

    def _sum_all_weights_square(self, role):
        #role：Actor（0）かCritic（1）か
        #weightを持つtrainableな全Layerと出力layersのweightの2乗の総和を返す。
        #荷重減衰（weight decay）のため。

        if role==0:
            #Actor
            sum_of_weights_square = 0
            for layer in self._layers_actor.values():
                if layer.trainable == True and isinstance(layer, Affine):
                    sum_of_weights_square += layer.sum_weights_square()
            sum_of_weights_square += self._out_actor_mu.sum_weights_square()
            sum_of_weights_square += self._out_actor_log_var.sum_weights_square()
        elif role==1:
            #Critic
            sum_of_weights_square = 0
            for layer in self._layers_critic.values():
                if layer.trainable == True and isinstance(layer, Affine):
                    sum_of_weights_square += layer.sum_weights_square()
        else:
            sum_of_weights_square = 0

        return sum_of_weights_square

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @property
    def env(self):
        return self._env

    @property
    def state_dim(self):
        return self._state_dim

    @property
    def action_dim(self):
        return self._action_dim


import os
import pandas as pd
import sqlalchemy

#Definindo uma string de conexão
str_connection = 'sqlite:///{path_to_data}'

# Os endereços do projeto e sub-pastas
BASE_DIR = os.path.dirname( os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(BASE_DIR,'data')

# Encontrando os arquivos de dados
files_names = [i for i in os.listdir(DATA_DIR) if i.endswith('.csv')]

# Abrindo uma conexão com o banco...
connection = sqlalchemy.create_engine(str_connection.format(path_to_data = os.path.join(DATA_DIR, 'olist.db')))

# Para cada Arquivo é realizado uma inserção no banco
for i in files_names:
    df_tmp = pd.read_csv(os.path.join (DATA_DIR, i))
    table_name = "tb_" + i.strip(".csv").replace("olist_", "").replace("_dataset","")
    df_tmp.to_sql(table_name, connection)


from sdv.model import DataPointFloat, Model

class O2WR(Model):
    """O2WR model.

    Attributes
    ----------
    Lambda: sensor
        PID 2x (byte AB) and PID 3x (byte AB) - Lambda for wide range/band oxygen sensor

    Voltage: sensor
        PID 2x (byte CD) - Voltage for wide range/band oxygen sensor

        Unit: V
    Current: sensor
        PID 3x (byte CD) - Current for wide range/band oxygen sensor

        Unit: A
    """

    def __init__(self, name, parent):
        """Create a new O2WR model."""
        super().__init__(parent)
        self.name = name

        self.Lambda = DataPointFloat("Lambda", self)
        self.Voltage = DataPointFloat("Voltage", self)
        self.Current = DataPointFloat("Current", self)


import dash
from dash_core_components.Tabs import Tabs
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import plotly.express as px
import datetime
import pandas as pd
import base64

# Python scripts
import aux_ as aux
import tasks
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
from calendar_class import Calendar

calendar = Calendar()
calendar.auto_schedule = True

now = datetime.datetime.now()
str_date = datetime.datetime.strftime(now, '%Y/%m/%d')

# App settings
app = dash.Dash(__name__,suppress_callback_exceptions=True,meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}])
app.title = aux.APP_TITLE
app.layout =  html.Div([html.Br(),html.Div([html.H1(aux.APP_TITLE)],style={'text-align':'center'}),html.Br(),
        dcc.Tabs(id="tabs-styled-with-inline", value='today', children=[
        dcc.Tab(label='Què he de fer avui?', value='avui', style=aux.tab_style, selected_style=aux.tab_selected_style),
        dcc.Tab(label='Afegeix tasca', value='add_task', style=aux.tab_style, selected_style=aux.tab_selected_style),
        dcc.Tab(label='El meu perfil', value='profile', style=aux.tab_style, selected_style=aux.tab_selected_style),
    ], style=aux.tabs_styles),
   html.Div(id='tabs-content-inline')
])

###############################################
# TASKS
###############################################
@app.callback(
    Output("tabs-styled-with-inline", "value"),
    [Input("submit-entry", "n_clicks")],
    [
        State("select-subject", "value"),
        State("select-activity", "value"),
        State("enter-task", "value"),
        State("enter-hours", "value"),
        State("date-picker", "date"),
        State("enter-time", "value"),
    ],
)
def register(submit_entry, select_subject, select_activity, enter_task, enter_hours,date_picker, enter_time):
    if submit_entry:
        date = date_picker.replace("-", "/")
        calendar.add_deadline(select_subject, select_activity, enter_task, date, enter_time, dedication=enter_hours)
        #print(submit_entry, select_subject, select_activity, enter_task, enter_hours, date_picker, enter_time)
        print(calendar.get_schedule())
        return "today"
    raise dash.exceptions.PreventUpdate

###############################################
# TODAY
###############################################
@app.callback(dash.dependencies.Output('label1', 'children'),
    [dash.dependencies.Input('interval1', 'n_intervals')])
def update_interval(n):
    now = datetime.datetime.now()
    now += datetime.timedelta(hours= 12)
    return now

def state(str_date, hour):
    res = []
    for time,task in calendar.schedule[str_date].items():
        time = int(time[0:2])
        if hour == time:
            res.append(aux.red_button_style)
        elif hour < time:
            res.append(aux.normal_button_style)
        elif hour > time:
            res.append(aux.ended_button_style)
    return res

LLISTA = []

a = [dash.dependencies.Output('TIME', 'figure')] + LLISTA
@app.callback(a,
    [dash.dependencies.Input('label1', 'children')])
def time_clock(now):
    time = now[11:19]
    global str_date
    str_date = now[0:10].replace("-", "/")
    min = int(time[-5:-3])
    hour = int(time[-8:-6])
    fet = min/60*100
    falta = 100 - fet
    data = [['% Completat', fet],['% Pendent', falta]]
    df = pd.DataFrame(data,columns = ['Etiqueta', 'Percentatge'])
    fig = px.pie(df, hover_name="Etiqueta", hover_data={'Etiqueta':False,'Percentatge':False}, values='Percentatge', names='Etiqueta', color_discrete_sequence=["#00CC96","rgb(246,246,246)"])
    fig.update(layout_showlegend=False)
    fig.update_traces(textinfo='none',sort=False)

    global a
    if str_date in calendar.schedule.keys():

        LLISTA = [dash.dependencies.Output(f"t{task.date_time}", 'style') for _, task in calendar.schedule[str_date].items()]
        a = [dash.dependencies.Output('TIME', 'figure')] + LLISTA
        print(len(a))
        print(len(LLISTA))
        print(type(LLISTA))
        print(len([fig] + state(str_date, hour)))
    else:
        a = [dash.dependencies.Output('TIME', 'figure')] + []

    return [fig] + state(str_date, hour)

# MAIN
@app.callback(Output('tabs-content-inline', 'children'),
              Input('tabs-styled-with-inline', 'value'))
def render_content(tab):
    if tab == 'avui':
        now = datetime.datetime.now()
        now += datetime.timedelta(hours= 12) #BORRAR
        str_date = datetime.datetime.strftime(now, '%Y/%m/%d')
        lst=[]

        if str_date not in calendar.schedule.keys():
            return html.Div([html.Div([html.H1("No tens res a fer avui!")],style={'text-align':'center'}), html.Img(src=aux.b64_image("img/felicitats!.png"))], style={'height':'70%','text-align':'center'})

        for hour, task in calendar.schedule[str_date].items():
            lst.append( html.Div([html.Button(hour + " - "+ task.name, id=str(task.date_time),style=aux.normal_button_style),html.Br(),html.Br()]))
        return  html.Div([html.Div([
                html.Div([html.Div([html.H2("Tasques:"),html.Div(lst)], style={'marginLeft': "5%",'marginRight': "5%"})], style={'width':'40%','text-align':'left','backgroundColor': 'rgb(153,153,153)','marginTop': 22,'marginBottom': 60,'marginLeft': 10}),
                html.Div([
                    html.Div([dcc.Interval(id='interval1', interval=1000, n_intervals=0),html.Br(),html.H1(id='label1', children='',style={ 'textAlign': 'center', 'color': 'black'})]),
                    dcc.Graph(id='TIME')], style={'width':'60%','text-align':'center'})],style={'display':'flex'}
                ),html.Div([html.Div("hl")], style={'width':'50%','text-align':'right'})])

    elif tab == 'add_task':
        return tasks.tasks_tab()
    elif tab == 'profile':
        return

if __name__ == '__main__':
    app.run_server(debug=True)


import telebot
from telebot import types

bot = telebot.TeleBot('')

@bot.message_handler(commands=['start'])
def start(message):
    mess = f'Привет, <b>{message.from_user.first_name} {message.from_user.last_name}</b>'
    bot.send_message(message.chat.id, mess, parse_mode='html')

@bot.message_handler(commands=['website'])
def website(message):
    markup = types.InlineKeyboardMarkup()
    markup.add(types.InlineKeyboardButton("Посетить веб сайт", url="https://hestiamaks.ml"))
    bot.send_message(message.chat.id, "Перейдите на сайт!", reply_markup=markup)

@bot.message_handler(commands=['help'])
def website(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
    website = types.KeyboardButton('Веб сайт')
    start = types.KeyboardButton('Старт')
    markup.add(website, start)
    bot.send_message(message.chat.id, "Перейдите на сайт!", reply_markup=markup)

@bot.message_handler(content_types=['text'])
def get_user_text(message):
    if message.text == "Hello":
        bot.send_message(message.chat.id, "И тебе привет!", parse_mode='html')
    elif message.text == "Id":
        bot.send_message(message.chat.id, f"Твой ID:{message.from_user.id}", parse_mode='html')
    else:
        bot.send_message(message.chat.id, "мне не понятно!", parse_mode='html')

bot.polling(none_stop=True)


'''@file score.py
contains functions to score the system'''

import numpy as np

def cer(outputs, targets):
    '''
    compute the character error rate

    Args:
        outputs: a dictionary containing the decoder outputs
        targets: a dictionary containing the reference outputs

    Returns:
    the character error rate
    '''

    errors = 0
    num_labels = 0

    for utt in targets:
        scores = np.array([h[0] for h in outputs[utt]])

        decoded = outputs[utt][np.argmax(scores)][1].split(' ')

        #get the reference as a list
        reference = targets[utt].split(' ')

        #compute the error
        error_matrix = np.zeros([len(reference) + 1, len(decoded) + 1])

        error_matrix[:, 0] = np.arange(len(reference) + 1)
        error_matrix[0, :] = np.arange(len(decoded) + 1)

        for x in range(1, len(reference) + 1):
            for y in range(1, len(decoded) + 1):
                error_matrix[x, y] = min([
                    error_matrix[x-1, y] + 1, error_matrix[x, y-1] + 1,
                    error_matrix[x-1, y-1] + (reference[x-1] !=
                                              decoded[y-1])])

        errors += error_matrix[-1, -1]
        num_labels += len(reference)

    return errors/num_labels


import random

class Vehicle(object):
    """
    A Vehicle drives from intersection to intersection and does so in a number of steps.
    """
    def __init__(self, roads_to_drive, road, lane):
        # The road the vehicle is driving on
        self.road = road
        # The lane the vehicle leaves the road
        self.lane = lane
        # Add the vehicle to the lane.
        lane.enter(self)

        # The number of roads to drive
        self.roads_to_drive = roads_to_drive

        # The number of steps driving
        self.steps_driving = 0
        # The number of steps waiting
        self.steps_waiting = 0
        # The number of traffic lights encountered
        self.number_of_encountered_traffic_lights = 1 if lane.has_traffic_light else 0

        # Used for resetting
        self.start_lane = lane
        self.start_road = road
        self.start_roads_to_drive = roads_to_drive

    def is_finished(self):
        """
        Returns true if the vehicle is done driving
        """
        return self.roads_to_drive == 0

    def total_steps(self):
        """
        Return the total number of steps = steps_driving + steps_waiting.
        """
        return self.steps_driving + self.steps_waiting

    def choose_lane(self):
        """
        Choose a random lane and enter it
        """
        lane = random.choice(list(self.road.lanes.values()))
        lane.enter(self)
        self.lane = lane

    def cross_intersection(self):
        """
        Cross the intersection and enter the road
        """
        self.lane.goes_to_road.enter(self)
        self.road = self.lane.goes_to_road

    def reset(self):
        """
        Reset the vehicle by repositioning it and setting the starting values
        """
        self.lane = self.start_lane
        self.lane.enter(self)
        self.road = self.start_road
        self.roads_to_drive = self.start_roads_to_drive

        self.steps_waiting = 0
        self.steps_driving = 0
        self.number_of_encountered_traffic_lights = 1 if self.lane.has_traffic_light else 0


from django.urls import path
from . import views

urlpatterns =[
    path('',views.login,name='index_login'),
    path('login/',views.login,name='login'),
    path('logout/',views.logout,name='logout'),
    path('cadastrar/',views.cadastrar,name='cadastrar'),
    path('dashboard/',views.dashboard,name='dashboard')
]


def pascal(n):
        for x in range(1,n+1):
            for y in range(n-x):
                print(" ",end="")   #inverted triangle blank spaces
            for z in range(1,x):
                print(z,end="")     #normal counting
            for q in range(x,0,-1):
                print(q,end="")       #backward counting

            print("\n",end="")

pascal(5)


"""Auth urls."""
from django.urls import path
from apps.vmc_auth import views

app_name = "auth"

urlpatterns = [
    path("accounts/signup/", views.signup, name="signup"),
    # path("accounts/signin/", views.signin, name="signin"),
    path("accounts/signin/", views.LoginView.as_view(), name="signin"),
    path("accounts/signin/#signin-modal", views.signin, name="signin_modal"),
    path("accounts/profile/", views.ProfileView.as_view(), name="profile"),
    path("accounts/signout", views.user_logout, name="signout"),
    path(
        "accounts/profile/delete/<int:pk>/",
        views.DeleteAccount.as_view(),
        name="delete_account",
    ),
]


import sys

def read_matrix():
    (rows_count, columns_count) = map(int, input().split(', '))
    matrix = []
    for row_index in range(rows_count):
        row = list(map(int, input().split(', ')))
        matrix.append(row)
    return matrix

def submatrix(matrix):
    rows = len(matrix)
    columns = len(matrix[0])
    first_row = []
    second_row = []
    max_sum = - sys.maxsize
    for column in range(columns - 1, 0, -1):
        for row in range(rows - 1, 0, -1):
            sum_values = matrix[row][column] + matrix[row][column-1] + matrix[row - 1][column] + matrix[row-1][column - 1]
            if sum_values >= max_sum:
                max_sum = sum_values
                second_row = matrix[row][column-1], matrix[row][column]
                first_row = matrix[row-1][column - 1], matrix[row - 1][column]

    return f'{" ".join(map(str, first_row)) }\n{" ".join(map(str, second_row))}\n{max_sum}'

print(submatrix(read_matrix()))

3. Multidimensional Lists - Lab/05. Square with Maximum Sum.py


"""
--- Day 13: Knights of the Dinner Table ---
In years past, the holiday feast with your family hasn't gone so well. Not everyone gets along! This year, you resolve,
will be different. You're going to find the optimal seating arrangement and avoid all those awkward conversations.

You start by writing up a list of everyone invited and the amount their happiness would increase or decrease if they
were to find themselves sitting next to each other person. You have a circular table that will be just big enough to fit
everyone comfortably, and so each person will have exactly two neighbors.

For example, suppose you have only four attendees planned, and you calculate their potential happiness as follows:

Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.

Then, if you seat Alice next to David, Alice would lose 2 happiness units (because David talks so much), but David would
gain 46 happiness units (because Alice is such a good listener), for a total change of 44.

If you continue around the table, you could then seat Bob next to Alice (Bob gains 83, Alice gains 54). Finally, seat
Carol, who sits next to Bob (Carol gains 60, Bob loses 7) and David (Carol gains 55, David gains 41).

The arrangement looks like this:

     +41 +46
+55   David    -2
Carol       Alice
+60    Bob    +54
     -7  +83

After trying every other seating arrangement in this hypothetical scenario, you find that this one is the most optimal,
with a total change in happiness of 330.

What is the total change in happiness for the optimal seating arrangement of the actual guest list?

--- Part Two ---
In all the commotion, you realize that you forgot to seat yourself. At this point, you're pretty apathetic toward the
whole thing, and your happiness wouldn't really go up or down regardless of who you sit next to. You assume everyone
else would be just as ambivalent about sitting next to you, too.

So, add yourself to the list, and give all happiness relationships that involve you a score of 0.

What is the total change in happiness for the optimal seating arrangement that actually includes yourself?
"""

from itertools import permutations

def parse(data: [str]) -> (dict, set):
    scores = {}
    people = set()
    for line in data:
        person1, _, way, units, person2 = line[:-1].replace("happiness units by sitting next to ", "").split(" ")
        people.add(person1)
        people.add(person2)
        scores[(person1, person2)] = int(units) if way == "gain" else int(units) * -1
        scores[(person1, "Me")] = 0
        scores[("Me", person1)] = 0
        scores[(person2, "Me")] = 0
        scores[("Me", person2)] = 0
    return (scores, people)

def calc_happiness() -> int:
    chairs = len(people)
    happiness = []
    for perm in permutations(people):
        change = 0
        for i in range(chairs):
            j = i + 1
            if j >= chairs:
                j = 0
            person1 = perm[i]
            person2 = perm[j]

            score1 = scores[(person1, person2)]
            score2 = scores[(person2, person1)]
            change += score1 + score2

        happiness.append(change)
    return max(happiness)

#
#

inputdata = open("input.data").read().strip().splitlines()
scores, people = parse(inputdata)

print("Part 1:", calc_happiness())

people.add("Me")
print("Part 2:", calc_happiness())


# Renames files/ photos in a specific folder.

import os,sys,string,glob,shutil

i = 0
k = 0

sourceAl1 = "D:\\Photos\\"

destination = "D:\\Photos\\"

a = os.listdir(sourceAl1)

i=1

for _ in a:
    tkn = _.split('.',-1)
    tkn1 = _.split('.',-1)
    print (tkn)
    sN = sourceAl1 + tkn[0] + "." + tkn[1]
    tN = destination + "Phot-" + str(i) + "." + tkn[1]

    print ("SourceName: ", sN)
    print ("DestinationName: ", tN)

    os.rename(sN,tN)

    i+=1


# Напишите программу, которая найдёт произведение пар чисел списка.
# Парой считаем первый и последний элемент, второй и предпоследний и т.д.

# Пример:
# - [2, 3, 4, 5, 6] => [12, 15, 16];
# - [2, 3, 5, 6] => [12, 15]

n = int(input('Введите количество чисел: '))
some_list = []
for _ in range (0, n):
    some_list.append(int(input('Введите число: ')))

index = 0
Mult_list = []
while index <= (n-1)//2 :
    Mult_list.append(some_list[index] * some_list[n-1-index])
    index += 1
print(Mult_list)


from ansiblelint import AnsibleLintRule
import re

class ComparisonToEmptyStringRule(AnsibleLintRule):
    id = 'EXTRA0015'
    shortdesc = "Don't compare to empty string"
    description = 'Use `when: var` rather than `when: var != ""` (or ' \
                  'conversely `when: not var` rather than `when: var == ""`)'
    tags = ['idiom']
    empty_string_compare = re.compile("[=!]= ?[\"'][\"']")

    def match(self, file, line):
        return self.empty_string_compare.search(line)


from __future__ import annotations
import pytest
from mocksafe import MockProperty, mock, stub, that

class Philosopher:
    @property
    def meaning_of_life(self: Philosopher) -> str:
        return "42"

def test_mock_getter_prop():
    mock_meaning: MockProperty[str] = MockProperty("")

    philosopher: Philosopher = mock(Philosopher)

    stub(philosopher).meaning_of_life = mock_meaning

    with pytest.raises(TypeError):
        stub(philosopher).meaning_of_life = MockProperty(123)

    with pytest.raises(AttributeError):
        stub(philosopher).foobar = mock_meaning

    assert philosopher.meaning_of_life == ""

    mock_meaning.return_value = (
        "Try and be nice to people, avoid eating fat, "
        "read a good book every now and then, get "
        "some walking in, and try and live together "
        "in peace and harmony with people of all "
        "creeds and nations."
    )

    assert "be nice" in philosopher.meaning_of_life
    assert "live together in peace" in philosopher.meaning_of_life

    assert that(mock_meaning).was_called
    assert that(mock_meaning).num_calls == 3
    assert that(mock_meaning).last_call == ()


import webapp2
import jinja2
import os
from google.appengine.ext import db

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape=True)

class Entry(db.Model):
    title = db.StringProperty(required = True)
    content = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self,template,**params):
        t=jinja_env.get_template(template)
        return t.render(params)

    def render(self,template,**kw):
        self.write(self.render_str(template, **kw))

class MainPage(Handler):

    def get(self):
        self.redirect('/blog')

class BlogHome(Handler):

    def render_base(self, title="", content="", error=""):
        entries=db.GqlQuery("SELECT * from Entry ORDER BY created DESC LIMIT 5")
        self.render("blog.html", title=title, content=content, error=error, entries=entries)

    def get(self):
        self.render_base()

    def post(self):
        title=self.request.get("title")
        content=self.request.get("content")

        if title and content:
            a=Entry(title=title, content=content)
            a.put()
            self.redirect("/")
        else:
            error="Need both title and content"
            self.render_base(title, content, error=error)

class NewPost(Handler):

    def get(self, title="", content="", error=""):
        self.render("newpost.html")

    def post(self):
        title = self.request.get("title")
        content = self.request.get("content")

        if title and content:
            a=Entry(title=title, content=content)
            a.put()
            self.redirect("/blog/"+str(a.key().id()))
        else:
            error="Need both title and content"
            self.render("newpost.html",title=title, content=content, error=error)

class ViewPostHandler(Handler):
    def get(self,id):
        entry=Entry.get_by_id(int(id), parent=None)
        self.render("individual_post.html",title=entry.title,content=entry.content)

app = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/newpost', NewPost),
    ('/blog',BlogHome),
    webapp2.Route('/blog/<id:\d+>', ViewPostHandler)

], debug=True)


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

from pprint import pprint
from crawler import WebCrawler
from db_sqlite import DB
from sites.wawacity.page_list import PageList as PL
from sites.wawacity.page_detail import PageDetail as PD

class Builder:
    def __init__(self):
        pass

    def set_crawler(self, url):
        self.crawler = WebCrawler(url)

    def get_data(self, url):
        self.set_crawler(url)
        manga_list = PL(url, self.crawler.get_soup())
        result = manga_list.get_data()

        # _url = 'https://www.wawacity.vip/?p=manga&id=1872-the-millionaire-detective-balance-unlimited-saison1'
        # _url = 'https://www.wawacity.vip/?p=manga&id=1874-food-wars-saison5'
        for k, v in result.items():
            result[k]['page'] = self.get_page_data(result[k]['link'])

        pprint(result)

    def get_page_data(self, _url):
        self.set_crawler(_url)
        manga_page = PD(_url, self.crawler.get_soup())

        return manga_page.get_data()

    def insert_process(self, args):
        result = {}
        for num, dict in args.items():
            for keys, values in dict.items():
                if keys != 'page':
                    result[keys] = values
                else:
                    for key, value in dict['page'].items():
                        if key == 'details':
                            for k, v in value.items():
                                result[k] = v
                        else:
                            result[key] = value
            ''' inset in DB import from create_table'''

'''
a partir d'un fichier text ou de la db, ou du programme, acceder a une liste d'url,
selon l'url, reconnaitre le site et utilise le bon script
rechercher toutes les infos de l'anime.
stocker les resultats dans la db liens dl inclut,
ajouter le lien vers l'emplacement de l'anime sur le DD
selectionner le numeros de l'episodes a par puis le comparer au numeros de lepisode dans le titre sur le DD
ne selectionner que les liens des episodes nno telecharger
'''
url = 'https://www.wawacity.vip/?p=mangas'
b = Builder()
b.get_data(url)
# b.create_tables()


#predefined functions
def largest_num(*args):
    print(max(args))
largest_num(10,20,0,33,40,78,99)
def smallest_num(*args):
    print(min(args))
smallest_num(0,-2,99,22,1,3,4,55,66)

def absoult_num(a):
    print(abs(a))
absoult_num(-40)
absoult_num(50)
print(type(99))
print(type(99.88))
print(type("99"))
print(type[1,2,3,4,5])
print(type('55'))
print(type("jug"))
print(type(True))
print(type(-1))

#class and calling functions

import math
#import car

#in built constructor
class DemoMethod():
    def builten_methods(self):
        print(math.sqrt(100))
        print(math.factorial(3))
        print(math.pow(2,3))
    def car(self):
        make= '5500i'
        model = 'benz'
#        car.info(model, make)
#        car.cont(model,make)

a=DemoMethod()
a.builten_methods()
#a.car()
#car.cont(6,6)
#car.info('rst','stk')

#Defaukt constructer

class student:
    def __init__(self):
        print("call the default constructer")
        self.info="new one"
        self.findnumber="20"
    def show (self, name):
        print("name", name)
        print(self.info)
    def call(self):
        print(self.findnumber)

e= student()
e.show("Hari")
e.call()

class stud:
    count =0
    def __init__(self):
      stud.count=stud.count+1
s1=stud()
print("number of student",stud.count)
s2=stud()
print("number of student",stud.count)
s3=stud()
print("number of student",stud.count)
print()

class new:
    id= 30
    name="Hari"
    def __init__(self,name,id):
        self.id =id
        self.name=name
    def display_identity(self):
        print("id=%d\nname=%s"% (self.id,self.name))
    def new_temp(self):
        print("add new emp")
e1=new("hkk",11)
e2=new("Hari",177)
e1.display_identity()
e2.display_identity()


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

# In[1]:

import numpy as np
import pandas as pd
import math as mt
from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))

# In[2]:

def DectoBin(num):
    x = np.absolute(num)
    Bin = ""
    for i in range(1,33):
        if x > 1:
            Bin = (str)(x%2) + Bin
            x = (int)(x/2)
        elif x <= 1:
            Bin = (str)(x%2) + Bin
            x = 0
        else:
            Bin = (str)(0) + Bin

    compActive = 0
    if(num < 0):
        for i in range(31,-1,-1):
            if compActive == 0 and Bin[i] == '1':
                compActive = 1
            elif compActive == 1:
                twoscomp = ((int)(Bin[i]) - 1)**2
                lst = list(Bin)
                lst[i] = str(twoscomp)
                Bin = "".join(lst)
    return (str)(Bin)

def BintoDec(num):
    sum = 0
    if(num[0] == "0"):
        for i in range(1,33):
            sum = sum + (int((num[len(num)-i]))*(2**(i-1)))
        return sum
    else:
        for i in range(1,32):
            sum = sum + (int((num[len(num)-i]))*(2**(i-1)))
        sum = sum - (int((num[0]))*(2**(31)))
        return sum

class MyJaggedArray:
    def __init__(self,JALen):
        self.mem = [None]*(JALen*40)
        self.JALen = JALen
        self.inArrLenArr = [0]*JALen
        i = 0
        while (i < self.JALen):
            inArrLen = int(input(f"Enter {i+1} Array Length :"))
            if(inArrLen <= 10 and inArrLen > 0):
                self.inArrLenArr[i] = inArrLen
                for j in range(0,inArrLen):
                    data = int(input(f"Enter {i+1}, {j+1} Values : "))
                    data = DectoBin(data)
                    self.setValuestoMem(data,((i*40)+(j*4)))
            else:
                print("Lenght must be between 1 to 10")
                i = i -1
            i = i+1

    def setValuestoMem(self,data,index):
        count = 0
        for i in range(0,4):
            self.mem[index+i] = data[count:count+8]
            count = count + 8

    def getAllValues(self):
        printmd("My Jagged Array Values")
        for i in range(0,self.JALen):
            print(f"Base Address is :",(i*40))
            for j in range(0,self.inArrLenArr[i]):
                val = self.mem[((i*40)+(j*4))]
                val = val + self.mem[((i*40)+(j*4))+1]
                val = val + self.mem[((i*40)+(j*4))+2]
                val = val + self.mem[((i*40)+(j*4))+3]
                print(BintoDec(val) , end =" ")
            print("")

    def printMem(self):
        printmd("Memory")
        for i in range(0,len(self.mem)):
            print(self.mem[i])

# In[3]:

while True:
    JALen = int(input("Enter Jaggaed Array Length : "))
    if JALen <= 0 or JALen > 10:
        print("Jagged Array Length must be Between 1 to 10")
    else:
        break

obj = MyJaggedArray(JALen)
obj.getAllValues()

# In[4]:

obj.printMem()

# In[ ]:


#!/usr/bin/python3

import re

f = open('LornasData.xml', 'r')
lines = f.readlines()
f.close()

parse_regex = '(.*)  (.*)<'

test_seq, comment_str = [], []
for l in lines[3:-1]:
    m = re.search(parse_regex, l)
    if not m:
        print("line mismatch: {}\n".format(l))
    else:
        test_seq.append(m.group(1))
        comment_str.append(m.group(2))
# print("{}    {}\n".format(len(test_seq), len(comment_str)))

ftml_hdr = '''<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="../tools/ftml.xsl" type="text/xsl"?>
<ftml version="1.0">
  <head>
    <fontscale>200</fontscale>
    <fontsrc>url(../results/CharisSIL-Regular.ttf)</fontsrc>
    <fontsrc>url(../results/CharisSIL-Bold.ttf)</fontsrc>
    <fontsrc>url(../results/CharisSIL-Italic.ttf)</fontsrc>
    <fontsrc>url(../results/CharisSIL-BoldItalic.ttf)</fontsrc>
    <fontsrc label="CRv5">url(../references/v5/CharisSIL-Regular.ttf)</fontsrc>
    <fontsrc label="CIv5">url(../references/v5/CharisSIL-Italic.ttf)</fontsrc>
    <fontsrc label="DRb1">url(../references/b1/DoulosSIL-Regular.ttf)</fontsrc>
    <fontsrc label="DRv5">url(../references/v5/DoulosSIL-Regular.ttf)</fontsrc>
    <title>LornasData</title>
  </head>
  <testgroup label="Common base diacritic combos">
'''

ftml_ftr = '''  </testgroup>
</ftml>
'''

test_tmplt = '''    <test label="{}">
      <comment>{}</comment>
      <string>{}</string>
    </test>
'''

f = open("LornasData.ftml", "w")
f.write(ftml_hdr)
for test_utf8, comment in zip(test_seq, comment_str):
#    print(comment);
    test, label_str = "", ""
    for c in test_utf8:
        usv = ord(c)
        if usv > 0xFFFF: # detect values that don't work with the below
            print (f"USV too large: {usv}\n")
        test += "\\u" + format(usv, "06X")
        label_str += "U+" + format(usv, "04X") + " "
    label_str = label_str[:-1]
    f.write(test_tmplt.format(label_str, comment, test))
f.write(ftml_ftr)
f.close()