"""
Imgur CLI
"""

import argparse
import logging
import os
import traceback
import sys

from collections import namedtuple

import imgurpython

from imgur_cli import __version__
from imgur_cli import cli_api
from imgur_cli import exceptions
from imgur_cli.utils import cli_arg

logger = logging.getLogger(__name__)

def imgur_credentials():
    ImgurCredentials = namedtuple('ImgurCredentials',
                                  ['client_id', 'client_secret', 'access_token',
                                   'refresh_token', 'mashape_key'])

    client_id = os.environ.get('IMGUR_CLIENT_ID')
    client_secret = os.environ.get('IMGUR_CLIENT_SECRET')
    access_token = os.environ.get('IMGUR_ACCESS_TOKEN')
    refresh_token = os.environ.get('IMGUR_REFRESH_TOKEN')
    mashape_key = os.environ.get('IMGUR_MASHAPE_KEY')

    if not client_id or not client_secret:
        raise imgurpython.client.ImgurClientError('Client credentials not found. '
                                                  'Ensure you have both client id '
                                                  'and client secret')

    return ImgurCredentials(client_id, client_secret, access_token,
                            refresh_token, mashape_key)

class ImgurCli:

    def __init__(self):
        self.subcommands = {}
        self.parser = None
        self.client = None
        self.subparsers = {}

    @property
    def base_parser(self):
        parser = argparse.ArgumentParser(prog='imgur', description=__doc__.strip(),
                                         epilog='See "imgur help <SUBPARSER> '
                                         '<SUBCOMMAND>" for help on a specific '
                                         'subparser or subcommand')

        # Global arguments
        parser.add_argument('-v', '--version', action='version',
                            version='%(prog)s {0}'.format(__version__))

        return parser

    def generate_parser(self):
        self.parser = self.base_parser
        base_subparser = self.parser.add_subparsers(metavar='<subparsers>')
        self._add_help(self, base_subparser)
        self._add_subparsers(base_subparser)
        self._add_subcommands(cli_api)

    def _generate_subcommand(self, name, callback, subparser):
        description = callback.__doc__ or ''
        action_help = description.strip()
        arguments = getattr(callback, 'arguments', [])
        subcommand = subparser.add_parser(name, help=action_help,
                                          description=description,
                                          add_help=False)
        subcommand.add_argument('-h', '--help', action='help',
                                help=argparse.SUPPRESS)
        for args, kwargs in arguments:
            subcommand.add_argument(*args, **kwargs)
        subcommand.set_defaults(func=callback)
        self.subcommands[name] = subcommand

    def _add_help(self, cli_api, subparser):
        callback = getattr(self, 'cmd_help')
        self._generate_subcommand('help', callback, subparser)

    def _add_subparsers(self, subparser):
        for name, description in cli_api.SUBPARSERS.items():
            parser = subparser.add_parser(name, help=description,
                                          description=description,
                                          add_help=False)
            parser.add_argument('-h', '--help', action='help',
                                help=argparse.SUPPRESS)
            self.subparsers[name] = {}
            self.subparsers[name]['parser'] = parser
            self.subparsers[name]['subparser'] = (
                parser.add_subparsers(metavar='<subcommands>')
            )

    def _add_subcommands(self, cli_api):
        for attr in (action for action in dir(cli_api)
                     if action.startswith('cmd_')):
            callback = getattr(cli_api, attr)
            subparser_name = getattr(callback, 'subparser', None)
            name = (attr[len('cmd_{0}_'.format(subparser_name.replace('-', '_'))):]
                    .replace('_', '-'))
            subparser = self.subparsers[subparser_name]['subparser']
            self._generate_subcommand(name, callback, subparser)

    @cli_arg('subparser', metavar='<subparser>', nargs='?',
             help='Display help for <subparser>')
    @cli_arg('subcommand', metavar='<subcommand>', nargs='?',
             help='Display help for <subcommand>')
    def cmd_help(self, args):
        """Display help about this program or one of its subparsers"""
        if args.subparser:
            if args.subcommand:
                try:
                    self.subcommands[args.subcommand].print_help()
                except KeyError:
                    raise exceptions.CommandError('{0} is not valid subcommand'
                                                  .format(args.subcommand))
            else:
                try:
                    self.subparsers[args.subparser]['parser'].print_help()
                except KeyError:
                    raise exceptions.CommandError('{0} is not valid subparser'
                                                  .format(args.subparser))
        else:
            self.parser.print_help()

    def main(self, argv):
        self.generate_parser()
        if not argv:
            self.parser.print_help()
            return 0
        args = self.parser.parse_args(argv)
        try:
            # Short-circuit and deal with help right away
            if args.func == self.cmd_help:
                self.cmd_help(args)
                return 0
            credentials = imgur_credentials()
            self.client = imgurpython.ImgurClient(*credentials)
            args.func(self.client, args)
        except AttributeError:
            self.subparsers[argv[0]]['parser'].print_help()

def main():
    try:
        imgur_cli = ImgurCli()
        imgur_cli.main(sys.argv[1:])
    except imgurpython.client.ImgurClientError as e:
        print(e, file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(traceback.format_exc())
        sys.exit(1)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import pygame
from pygame.locals import *

from cnst import *

import sprite
import player

import math
import random

class Boss(sprite.Sprite3):
    def __init__(self, game, rect, name, *args):
        sprite.Sprite3.__init__(self, game, rect, 'boss/left-0',
            (54, 124, 150, 78))
        self.rect.centery = rect.centery
        self.rect.centerx = rect.centerx
        self.groups.add('boss')
        self.hit_groups.add('capsule')
        self.game.sprites.append(self)
        self.game.boss = self

        self.vx = -1.4
        self.vy = 0

        self.auto_gc = False

        self.phase = 1
        self.phase_frames = 0

        self.taking_damage = 0

        self.dying = None
        self.dead = False

        self.drop = 120

        self.facing = 'right'

        if self.vx < 0:
            self.facing = 'left'

        self._prev = None
        self.strength = 6

    def loop(self):
        if self.dying != None:
            self.image = 'boss/%s-%d' % (self.facing,
                (self.game.frame / (FPS / 8)) % 8)
            if self.dying % 15 == 0:
                self.game.game.sfx['boss_explode'].play()
            if self.dying % 15 > 10:
                self.image = 'boss/%s-damage-%d' % (self.facing,
                    (self.game.frame / (FPS / 8)) % 8)
            self.dying += 1

            mid_frame = FPS * 3 / 2
            end_frame = FPS * 6 / 2

            if self.dying == mid_frame:
                # explode
                self.game.game.sfx['pop'].play()
                for n in xrange(128):
                    rect = pygame.Rect(random.randint(self.rect.left,
                        self.rect.right), random.randint(self.rect.top,
                        self.rect.bottom), 1, 1)
                    Bub(self.game, rect)

            if self.dying >= mid_frame:
                self.image = None

            if self.dying > end_frame:
                self.dead = True

            return

        if sprite.get_code(self.game, self, sign(self.vx), 0) == CODE_BOSS_TURN:
            self.vx = - self.vx

        if self.phase == 2:
            if self.phase_frames == 240 + 32:
                self.vy = 0
                self.vx = 1.2

        if self.vx > 0:
            self.facing = 'right'
        else:
            self.facing = 'left'

        self.rect.x += sprite.myinc(self.game.frame, self.vx)
        self.rect.y += sprite.myinc(self.game.frame, self.vy)

        self.image = 'boss/%s-%d' % (self.facing,
            (self.game.frame / (FPS / 8)) % 8)

        if self.taking_damage > 0:
            if self.taking_damage % 20 > 10:
                self.image = 'boss/%s-damage-%d' % (self.facing,
                (self.game.frame / (FPS / 8)) % 8)
            self.taking_damage -= 1

        self.phase_frames += 1

        if self.drop == 0:
            if self.vy == 0: # no bombing when flying up to the second phase
                Fireball(self.game, self.rect, self)
            if self.phase == 1:
                self.drop = 120
            if self.phase == 2:
                self.drop = 90
        s.drop -= 1

    def hit(self, a, b):
        self.game.game.sfx['boss_explode'].play()
        a.strength -= 1
        a.taking_damage = 60
        b.active = False
        if a.strength == 3:
            a.vy = -1
            a.vx = 0
            a.phase = 2
            a.phase_frames = 0
        if a.strength == 0:
            a.dying = 0

class Bub(sprite.Sprite3):
    def __init__(self, game, rect):
        sprite.Sprite3.__init__(self, game, rect, 'big-bubble', (0, 0, 16, 16))

        self.rect.centerx = r.centerx
        self.rect.centery = r.centery
        self.game.sprites.append(self)

        speed = random.randint(16, 64)
        angle = random.randint(0, 360) * 6.28 / 360
        self.vx = math.sin(angle) * speed
        self.vy = math.cos(angle) * speed
        self.frame = random.randint(0, FPS * 2)

    def loop(self):
        self.vx *= 0.98
        self.vy *= 0.98
        self.rect.x += sprite.myinc(self.game.frame, self.vx)
        self.rect.y += sprite.myinc(self.game.frame, self.vy)
        self.frame += 1
        if self.frame >= FPS * 2:
            self.active = False
            if random.randint(0, 3) == 1:
                self.game.game.sfx['pop'].play()


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

# Test formulary functions.

__all__ = ('Tests',)
__version__ = '19.05.02'

from base import TestsBase

from pygeodesy import R_M, antipode, equirectangular, euclidean, \
                      haversine, heightOf, horizon, isantipode, \
                      vincentys

class Tests(TestsBase):

    def testDistances(self, a1, b1, a2, b2, x):
        k = x * 0.003  # allow 0.3% margin
        d = haversine(a1, b1, a2, b2)
        self.test('haversine', d, x, fmt='%.3f', known=abs(d - x) < k)

        d = vincentys(a1, b1, a2, b2)
        self.test('vincentys', d, x, fmt='%.3f', known=abs(d - x) < k)

        k = x * 0.02  # allow 2% margin
        d = equirectangular(a1, b1, a2, b2, limit=90)
        self.test('equirectangular', d, x, fmt='%.3f', known=abs(d - x) < k)

        k = x * 0.11  # allow 11% margin
        d = euclidean(a1, b1, a2, b2)
        self.test('euclidean', d, x, fmt='%.3f', known=abs(d - x) < k)

    def testFormy(self):

        self.test('antipode1', antipode( 89,  179), (-89, -1))
        self.test('antipode2', antipode(-89, -179), (89, 1))

        self.test('isantipode1', isantipode( 89,  179, -89, -1), True)
        self.test('isantipode2', isantipode(-89, -179,  89,  1), True)
        self.test('isantipode3', isantipode(-89, -179, -89, -1), False)

        self.test('heightOf0',   heightOf(0,   R_M), 2638958.23912, fmt='%.5f')
        self.test('heightOf45',  heightOf(45,  R_M), 5401080.43931, fmt='%.5f')
        self.test('heightOf90',  heightOf(90,  R_M), R_M)
        self.test('heightOf135', heightOf(135, R_M), 5401080.43931, fmt='%.5f')

        self.test('horizon0',     horizon(0), 0.0)
        self.test('horizon10Km',  horizon(10000), '357099.672', fmt='%.3f')
        self.test('horizon30Kft', horizon(10000, refraction=True), '392310.704', fmt='%.3f')
        self.test('horizon10Kft', horizon( 3000, refraction=True), '214877.422', fmt='%.3f')

        Boston    = 42.3541165, -71.0693514
        Cleveland = 41.499498, -81.695391
        MtDiablo  = 37.8816, -121.9142
        Newport   = 41.49008, -71.312796
        NewYork   = 40.7791472, -73.9680804
        # <https://GeographicLib.SourceForge.io/cgi-bin/GeodSolve>
        for ll1, ll2, x in ((Boston, NewYork,    298396.057),
                            (Boston, Newport,     98071.559),
                            (Cleveland, NewYork, 653456.173),
                            (NewYork, MtDiablo, 4094953.628)):
            abx = ll1 + ll2 + (x,)
            self.testDistances(*abx)

if __name__ == '__main__':

    t = Tests(__file__, __version__)
    t.testFormy()
    t.results()
    t.exit()


# -*- coding: utf-8 -*-
"""
You are climbing a stair case. It takes n steps to reach to the top.
你爬楼梯，到顶端有n阶阶梯
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
每次上升1或2步，你能有几种方法爬到顶
Note: Given n will be a positive integer.
给定n是一个正整数

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps
Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""

# =============================================================================
class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = [1 for i in range(n+1)]
        for i in range(2,n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]
# =============================================================================

a = Solution()
b=a.climbStairs(6)
print(b)

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1 or n == 0:
            return 1
        i,stairs1,stairs2 = 2,1,1
        while i <= n:
            stairs1 = stairs1 + stairs2
            if i == n:# n = 2 ，4时
                 print(stairs1)
                 return stairs1
            i += 1
            stairs2 = stairs1 + stairs2
            if i == n:# n = 3 ，5时
                 print(stairs2)
                 return stairs2
            i += 1

s = Solution()
c=s.climbStairs(6)

class Solution(object):
     def climbStairs(self, n):
         """
         :type n: int
         :rtype: int
         """
         if n == 1 or n == 0:
             return 1
         i,tmp1,tmp2 = 2,1,1
         while i <= n:
             tmp1 = tmp1 + tmp2
             if i == n:
                 return tmp1
             i += 1
             tmp2 = tmp1 + tmp2
             if i == n:
                 return tmp2
             i += 1

s = Solution()
d=s.climbStairs(6)
print(d)


import pandas as pd
import time

"""
number of purchases each user on substitution products.
substitution is defined as similar products inferred by word2vec algorithm
"""

# parameters:
start_time = time.time()
data_folder = "data"
nrows = None
two_way = True

substitute = pd.read_pickle("data/word2vec_substitute.pickle")
substitute = substitute.loc[
    substitute["similarity_score"] > 0.8, ["product_id", "substitute_id"]
]

base = pd.read_pickle("data/base.pickle")[["user_id", "product_id"]]

user_substitute = base.merge(substitute, on=["product_id"], how="inner")
user_substitute.set_index(["user_id", "substitute_id"], inplace=True)
# <user_id, product_id, substitute_id>
del base, substitute

up_purchase = pd.read_pickle("data/up_agg.pickle")[
    ["user_id", "product_id", "up_num_purchases"]
]
up_purchase.columns = [
    "user_id",
    "substitute_id",
    "up_word2vec_substitute_num_purchases",
]
up_purchase.set_index(["user_id", "substitute_id"], inplace=True)
# user_substitute = user_substitute.merge(up_purchase,  left_on=['user_id', 'substitute_id']
#                                         , right_on=['user_id', 'substitute_id'], how='left')

user_substitute = user_substitute.join(
    up_purchase, on=["user_id", "substitute_id"], how="left"
)
del up_purchase

# r5
up_purchases_r5 = pd.read_pickle("data/up_purchase_r5.pickle")[
    ["user_id", "product_id", "up_num_purchases_r5"]
]
up_purchases_r5.columns = [
    "user_id",
    "substitute_id",
    "up_word2vec_substitute_num_purchases_r5",
]
up_purchases_r5.set_index(["user_id", "substitute_id"], inplace=True)
# user_substitute = user_substitute.merge(up_purchases_r5,  left_on=['user_id','substitute_id']
#                                         , right_on=['user_id', 'substitute_id'], how='left')

user_substitute = user_substitute.join(
    up_purchases_r5, on=["user_id", "substitute_id"], how="left"
)
user_substitute.fillna(0, inplace=True)

user_substitute = (
    user_substitute.groupby(["user_id", "product_id"])
    .agg(
        {
            "up_word2vec_substitute_num_purchases": "sum",
            "up_word2vec_substitute_num_purchases_r5": "sum",
        }
    )
    .reset_index()
)

user_substitute.to_pickle(
    "{}/up_word2vec_substitute_purchase.pickle".format(data_folder)
)

end_time = time.time()
print("code using {:.2f} mins".format((end_time - start_time) / 60))


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
File  :   helper.py
Author:   dangjinming(jmdang777@qq.com)
Date  :   2022/3/16
Desc  :   common func
"""

import logging
import numpy as np
# logging.basicConfig(format='%(asctime)s-%(levelname)s - %(message)s', level=logging.INFO)
from sklearn.metrics import  precision_score, recall_score, f1_score

def multi_classify_prf_macro(y_true, y_pre):
    """macro prf
    每个类别看作二分类,每个TP FN FP TN,算prf后平均
    """
    p = precision_score(y_true=y_true, y_pred=y_pre, average="macro")
    r = recall_score(y_true=y_true, y_pred=y_pre, average="macro")
    f = f1_score(y_true=y_true, y_pred=y_pre, average="macro")
    return p,r,f

def multi_classify_prf_micro(y_true, y_pre):
    """micro, prf
    每个类别看作二分类,每个TP FN FP TN,先求和后算一次prf
    """
    p = precision_score(y_true=y_true, y_pred=y_pre, average="micro")
    r = recall_score(y_true=y_true, y_pred=y_pre, average="micro")
    f = f1_score(y_true=y_true, y_pred=y_pre, average="micro")
    return p,r,f

def multi_classify_prf_self(y_true, y_pred):
    """
    除了0类其他类别的PRF
    """
    y_true=np.argmax(y_true,1)
    y_pred = np.argmax(y_pred, 1)
    y_preNotNA = [int(i) for i in np.greater(y_pred, 0)]
    pre_num = np.sum(y_preNotNA)
    y_trueNotNA = [int(i) for i in np.greater(y_true, 0)]
    true_num = np.sum(y_trueNotNA)
    equal_num = np.sum(np.multiply([i for i in np.equal(y_true, y_pred)], y_preNotNA))
    try:
        precision = equal_num / pre_num
        recall = equal_num / true_num
        f1 = (2 * precision * recall) / (precision + recall)
    except ZeroDivisionError:
        precision, recall, f1 = 0, 0, 0
    return precision, recall, f1

def extract_entity_crf(pre_label, predict_length, label_encoder=None):
    """ 从预测标签抽取实体,标签个数: label_encoder.size() * 2 - 1
    [IN]  pre_label: 模型预测结果
          predict_length: 预测数据真实长度
          label_encoder: 标签编码
    """
    pre_entity = []
    for label, length in zip(pre_label, predict_length):
        item = []
        if length >= len(label):
            length = len(label)
        index = 0
        while index < length:
            if label[index] != 0:
                start = index
                start_type_id = label[index]
                end = index + 1
                while end < length and label[end]==start_type_id + 1:
                    end += 1
                    index += 1
                if start_type_id // 2 + 1 not in label_encoder.id_label_dict:
                    break
                item.append([start - 1, end - 1, label_encoder.inverse_transform(start_type_id // 2 + 1)])
            index += 1
        pre_entity.append(item)
    return pre_entity

def extract_entity_crf_BIO(pre_label, predict_length):
    """ 从预测标签抽取实体,只有三种标签   BIO
    [IN]  pre_label: 模型预测结果
          predict_length: 预测数据真实长度
          label_encoder: 标签编码
    """
    pre_entity = []
    for label, length in zip(pre_label, predict_length):
        item = []
        if length >= len(label):
            length = len(label)
        index = 0
        while index < length:
            if label[index] == 1:
                start = index
                end = index + 1
                while end < length and label[end]==2:
                    end += 1
                item.append([start - 1, end - 1])
            index += 1
        pre_entity.append(item)
    return pre_entity

def extract_entity_dp(pre_label, predict_length, label_encoder):
    """ 从预测标签抽取实体
    [IN]  pre_label: 模型预测结果
          predict_length: 预测数据真实长度
          label_encoder: 标签编码
    """
    pre_entity = []
    for label, length in zip(pre_label, predict_length):
        item = []
        if length >= len(label[0]):
            length = len(label[0])
        for start in range(length):
            if (label[0][start] != 0):
                for end in range(start, length):
                    if (label[1][end] != 0):
                        item.append([start - 1, end, label_encoder.inverse_transform(label[1][end])])
                        break
        pre_entity.append(item)
    return pre_entity

if __name__ == '__main__':
    print(extract_entity_crf([[1, 2, 2, 2, 1, 2, 2]], [7]))


# $Id$

__revision__ = '$Rev$'

def xyz2gro(ifname, ofname):
    ifile = file(ifname)
    lines = ifile.readlines()
    ifile.close()

    lines = lines[1:]
    words = [x.split() for x in lines]

    ofile = file(ofname, 'w+')
    ofile.write('GROningen MAchine for Chemical Simulation\n')
    ofile.write('%5d\n' % len(words))

    for x in words:
        no = int(x[0])
        symbol = '%s%d' % (x[1], no)
        cx = float(x[2])/10.0
        cy = float(x[3])/10.0
        cz = float(x[4])/10.0
        ofile.write('%5d%5s%5s%5d%8.3f%8.3f%8.3f\n' %
                    (1, 'DIEST', symbol, no, cx, cy, cz))
    ofile.write('%10.5f%10.5f%10.5f\n' % (0, 0, 0))

    ofile.close()

def main():
    import sys
    if len(sys.argv) != 3:
        import os.path
        print >> sys.stderr, "Usage: %s ifname ofname" % os.path.basename(sys.argv[0])
        sys.exit(1)
    xyz2gro(sys.argv[1], sys.argv[2])

if __name__ == '__main__':
    main()


"""Implement scratch behavior where Reachy use its left arm to scratch its right forearm."""
import asyncio
import numpy as np

from reachy_sdk.trajectory import goto_async, InterpolationMode

from . import Behavior

class Scratch(Behavior):
    """
    Scratch class.

    Makes Reachy scratch its forearm.

    Uses: right_arm, left_arm, head
    Dependencies to other behaviors: none
    """

    def __init__(self, name: str, reachy, sub_behavior: bool = False) -> None:
        """Initialize the behavior."""
        super().__init__(name, reachy, sub_behavior=sub_behavior)

        self.scratch_arm = np.load('movements/scratch.npy')

        self.sampling_frequency = 100

        self.recorded_joints = [
            self.reachy.r_arm.r_shoulder_pitch,
            self.reachy.r_arm.r_shoulder_roll,
            self.reachy.r_arm.r_arm_yaw,
            self.reachy.r_arm.r_elbow_pitch,
            self.reachy.r_arm.r_forearm_yaw,
            self.reachy.r_arm.r_wrist_pitch,
            self.reachy.r_arm.r_wrist_roll,
            self.reachy.l_arm.l_shoulder_pitch,
            self.reachy.l_arm.l_shoulder_roll,
            self.reachy.l_arm.l_arm_yaw,
            self.reachy.l_arm.l_elbow_pitch,
            self.reachy.l_arm.l_forearm_yaw,
            self.reachy.l_arm.l_wrist_pitch,
            self.reachy.l_arm.l_wrist_roll,
            self.reachy.l_arm.l_gripper,
        ]

    async def run(self):
        """Implement the Scratch behavior."""
        for j in self.reachy.r_arm.joints.values():
            j.torque_limit = 100.0
        for j in self.reachy.l_arm.joints.values():
            j.torque_limit = 100.0

        look_down = self.reachy.head.look_at_async(
            0.5,
            -0.1,
            -0.5,
            duration=1.0,
            starting_positions={
                self.reachy.head.neck_roll: self.reachy.head.neck_roll.goal_position,
                self.reachy.head.neck_pitch: self.reachy.head.neck_pitch.goal_position,
                self.reachy.head.neck_yaw: self.reachy.head.neck_yaw.goal_position,
            })

        traj_antennas = goto_async(
            goal_positions={
                self.reachy.head.r_antenna: -30,
                self.reachy.head.l_antenna: 5,
            },
            duration=1.0,
            interpolation_mode=InterpolationMode.MINIMUM_JERK
        )

        first_point = dict(zip(self.recorded_joints, self.scratch_arm[50]))
        # Goes to the start of the trajectory in 1s
        first_pos = goto_async(first_point, duration=1.0)

        await asyncio.gather(
            look_down,
            first_pos,
            traj_antennas,
        )

        for jp_arms in self.scratch_arm[50:]:
            for joint, pos in zip(self.recorded_joints, jp_arms):
                joint.goal_position = pos

            await asyncio.sleep(1 / (self.sampling_frequency*2))

        traj_antennas = goto_async(
            goal_positions={
                self.reachy.head.r_antenna: -10,
                self.reachy.head.l_antenna: 65,
            },
            duration=1.0,
            interpolation_mode=InterpolationMode.MINIMUM_JERK
        )
        hands_back = goto_async({
            self.reachy.l_arm.l_shoulder_pitch: 0.0,
            self.reachy.l_arm.l_shoulder_roll: 0.0,
            self.reachy.l_arm.l_arm_yaw: 0.0,
            self.reachy.l_arm.l_elbow_pitch: 0.0,
            self.reachy.l_arm.l_forearm_yaw: 0.0,
            self.reachy.l_arm.l_wrist_pitch: 0.0,
            self.reachy.l_arm.l_wrist_roll: 0.0},
            duration=1.2,
        )
        watch_arm_head = self.reachy.head.look_at_async(
            0.5,
            -0.1,
            -0.3,
            duration=0.5,
            starting_positions={
                self.reachy.head.neck_roll: self.reachy.head.neck_roll.goal_position,
                self.reachy.head.neck_pitch: self.reachy.head.neck_pitch.goal_position,
                self.reachy.head.neck_yaw: self.reachy.head.neck_yaw.goal_position,
            })
        pose_watch_right_arm = [-21, 7, 38, -102, 27, -10, -4]
        goto_dic = {j: pos for j, pos in zip(self.reachy.r_arm.joints.values(), pose_watch_right_arm)}
        watch_arm_arm = goto_async(goal_positions=goto_dic, duration=0.5)

        await asyncio.gather(
            watch_arm_head,
            watch_arm_arm,
            hands_back,
            traj_antennas,
        )

        await asyncio.sleep(0.3)

        traj_antennas = goto_async(
            goal_positions={
                self.reachy.head.r_antenna: 0,
                self.reachy.head.l_antenna: 0,
            },
            duration=1.0,
            interpolation_mode=InterpolationMode.MINIMUM_JERK
        )

        look_back = self.reachy.head.look_at_async(
            0.5,
            0.0,
            0.0,
            duration=1.5,
            starting_positions={
                self.reachy.head.neck_roll: self.reachy.head.neck_roll.goal_position,
                self.reachy.head.neck_pitch: self.reachy.head.neck_pitch.goal_position,
                self.reachy.head.neck_yaw: self.reachy.head.neck_yaw.goal_position,
            })
        hands_back = goto_async({
            self.reachy.r_arm.r_shoulder_pitch: 0.0,
            self.reachy.r_arm.r_shoulder_roll: 0.0,
            self.reachy.r_arm.r_arm_yaw: 0.0,
            self.reachy.r_arm.r_elbow_pitch: 0.0,
            self.reachy.r_arm.r_forearm_yaw: 0.0,
            self.reachy.r_arm.r_wrist_pitch: 0.0,
            self.reachy.r_arm.r_wrist_roll: 0.0},
            duration=1.2,
        )

        await asyncio.gather(
            traj_antennas,
            look_back,
            hands_back,
        )

        self.reachy.turn_off_smoothly('r_arm')
        self.reachy.turn_off_smoothly('l_arm')

    async def teardown(self):
        """Use the teardown method from parent class."""
        return await super().teardown()


#! /usr/bin/python

"""
Merges several font files into a new font (keeping the original fonts intact).
It can take any font format that Fontforge can open: .ufo, .otf, .sfd...

Usage:
    python mergeFonts.py fonte1.ufo fonte2.ufo ...  fonte17.ufo fonte-out.ufo
"""

import fontforge
import sys

font1 = fontforge.open(sys.argv[1])
font2 = sys.argv[2]
args = len(sys.argv) - 1
print(args)

i = 0
for arg in sys.argv:
    print(i)
    if i > 1 and i < args:
        print(arg)
        font1.mergeFonts(arg)
    i += 1

font1.generate(sys.argv[-1])


"""
Project all the temporal networks to the same eigen-system and measure change of the
total variation in that eigen-system
"""

from utils.readFile import readSubjectFiles
from numpy import linalg as LA
import numpy as np

def diff_eig_val(temp_net):
    print("*** Project all the temporal networks to the "
          "same eigen-system and measure change of the "
          "total variation in that eigen-system ***")

    t = len(temp_net)
    baseline = temp_net[0]
    eigval = np.zeros((len(baseline), t))
    eigval[:, 0], eigvec = LA.eigh(baseline)

    for i in range(1, t):
        D = np.diag(temp_net[i].sum(axis=1))
        L = D - temp_net[i]
        projection = np.matmul(np.matmul(eigvec.T, L), eigvec)
        #eigval[:, i] = np.diag(projection)
        eigval[:, i] = np.diag(np.sqrt(np.dot(projection, projection.T)))

    diff = np.diag(np.ones(t - 1) * -1)
    diff = np.vstack((np.ones((1, t - 1)), diff))
    diff_eigval = np.dot(eigval, diff)
    normalizer = eigval[:, 0][:, np.newaxis]
    #diff_eigval /= normalizer
    print(diff_eigval)

def diff_eig_vec(temp_net, eig_num=0):
    print("*** Angular difference between "
          "eigen vectors of the temporal networks ***")

    t = len(temp_net)
    n = len(temp_net[0])
    eigvec = np.zeros((n, t))

    for i in range(0, t):
        D = np.diag(temp_net[i].sum(axis=1))
        L = D - temp_net[i]
        _, eig = LA.eigh(L)
        eigvec[:, i] = eig[:, eig_num]

    ang_dist = np.abs(np.dot(eigvec.T, eigvec))
    np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)})
    print(ang_dist)

if __name__ == '__main__':
    # Input
    s_name = '027_S_5109'
    _, temp_net = readSubjectFiles(s_name)
    temp_net, _ = readSubjectFiles(s_name)
    diff_eig_vec(temp_net, 4)
    # diff_eig_val(temp_net)


import pathlib

filePath = pathlib.Path("Days/day3/input.txt")

file = open(filePath, "r")
backpacks = list(map(lambda x: x.strip(), file.readlines()))

ascii_a = ord("a")
ascii_z = ord("z")
ascii_A = ord("A")
ascii_Z = ord("Z")

total = 0

for backpack in backpacks:
    middle = len(backpack) // 2
    container1 = backpack[0:middle]
    container2 = backpack[middle:len(backpack)]
    for item1 in container1:
        if (item1 not in container2):
            continue
        if (ascii_a <= ord(item1) <= ascii_z):
            total += ord(item1) - ascii_a + 1
            break
        else:
            total += ord(item1) - ascii_A + 27
            break

print(total)

total_2 = 0
for i in range(0, len(backpacks), 3):
   common = set(backpacks[i]).intersection(set(backpacks[i + 1])).intersection(set(backpacks[i + 2])).pop()

   if (ascii_a <= ord(common) <= ascii_z):
        total_2 += ord(common) - ascii_a + 1
   else:
        total_2 += ord(common) - ascii_A + 27

print(total_2)


import subprocess
import os
from typing import Any
import yaml
import time
import random

def exec_command(command, env=None) -> str:
    if env is None:
        env = os.environ.copy()

    process = subprocess.run(command, capture_output=True, env=env)

    if process.returncode == 0:
        return process.stdout.decode()

    raise Exception('command {} failed\nstdout:\n{}\nstderr:\n{}'.format(
        command,
        process.stdout.decode(),
        process.stderr.decode(),
    ))

def generate_random_config() -> Any:
    ml_config = {
        'adam_lr': 0.01,
        'assets': ['SANHOK', 'MIRAMAR'],
        'batch_size': 1024,
        'hidden_dim': random.randint(20, 30),
        'n_batches_per_epoch': 50,
        'n_epochs': 100,
        'num_lstm_layers': 4,
        'droupout_percent': random.randint(20, 40),
        'sample_top_features': {
            'n_top_features': random.randint(60, 80),
            'feature_importance_path': "feature_importance.csv",
        },
        'scheduler': {'type': 'linear'},
    }
    return {
        'ml': {
            'config': ml_config,
            'path': 'model/ml_regressor',
        }
    }

def main():
    begin = time.time()
    with open('config.yml', 'w') as file:
        yaml.safe_dump(generate_random_config(), file)
    exec_command(['python3', 'train_scripts/train_lstm_regressor.py'])
    print(f'finished in {int(time.time() - begin)}s')

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import os
import sys
import io
import struct
import hashlib

def walk(adr):
	mylist=[]
	for root,dirs,files in os.walk(adr):
		for name in files:
			if name[-4:] != '.bin':
				continue
			adrlist=os.path.join(root, name)
			mylist.append(adrlist)
	return mylist

def main():
	fn_lst = walk('org')
	tbl = open('tbl.txt','r',encoding='utf16')
	dicts = {}
	for rows in tbl:
		row = rows.rstrip('\r\n').split('=')
		if len(row) == 3:
			row[1] = '='
		dicts[row[1]]=int(row[0],16)
	jump_dicts = {}
	jump_dicts_dst = {}
	src = open('St000_SldtDat.txt','r',encoding='utf16')
	for rows in src:
		row = rows.rstrip('\r\n').split('|')
		uid = row[0].split(':')[1] + row[1].split(':')[1][1:]
		if uid not in jump_dicts:
			jump_dicts[uid] = []
			jump_dicts_dst[uid] = []
		jump_dicts[uid].append((int(row[3].split(':')[1],16),int(row[5].split(':')[1],16)))
		jump_dicts_dst[uid].append((int(row[3].split(':')[1],16),int(row[5].split(':')[1],16)))
	src = open('St000_SldtDat.bin','rb')
	jump_data = src.read()
	jump_dst = open('dst\\St000.cpk_unpacked\\St000_SldtDat.bin','wb')
	jump_dst.write(jump_data)
	for fn in fn_lst:
		print(fn)
		uid = fn[fn.find('Cp')+2:fn.find('Cp')+6] + fn[fn.find('St')+2:fn.find('St')+5]
		str_lst = []
		src = open(fn,'rb')
		data = src.read()
		txt = open(fn.replace('.bin','.txt'),'r',encoding='utf16')
		for row in txt.readlines():
			if row[0] == '●':
				str_lst.append((int(row[1:29].split('|')[0]),row[1:29].split('|')[1],int(row[1:29].split('|')[2],16),int(row[1:29].split('|')[3],16),row[30:].rstrip('\r\n')))
		dst = open('dst'+fn[fn.find('\\'):-4]+'.cpk_unpacked'+fn[fn.find('\\'):],'wb')
		offset = 0
		for row in str_lst:
			string = b''
			for ch in row[4]:
				if dicts[ch] > 0xFF:
					string += struct.pack('>H',dicts[ch])
				else:
					string += struct.pack('B',dicts[ch])
			string = string.replace('\\n'.encode('932'),b'\x0D\x0A')
			#string = row[4].encode('932').replace('\\n'.encode('932'),b'\x0D\x0A')
			if row[1] == 'N' and len(string) > 20:
				print(row[4],'N')
				exit()
			elif row[1] == 'C' and len(string) > 0x38:
				print(row[4],'C')
				exit()
			if uid in jump_dicts:
				if len(string) != row[2] and row[1] not in ['N','C']:
					change = len(string) - row[2]
					for c in range(0,len(jump_dicts[uid])):
						if jump_dicts[uid][c][0] >= row[3]:
							jump_dicts_dst[uid][c] = (jump_dicts_dst[uid][c][0] + change,jump_dicts_dst[uid][c][1])
			if row[1] == 'T' or row[1] == 'L':
				dst.write(data[offset:row[3]])
				dst.write(string + b'\x00')
				offset = row[3] + row[2] + 1
			elif row[1] == 'N':
				dst.write(data[offset:row[3]])
				dst.write(string)
				for i in range(0,20 - len(string)):
					dst.write(b'\x00')
				offset = row[3] + 20
			elif row[1] == 'O':
				dst.write(data[offset:row[3]])
				dst.write(string + b'\x00\x00')
				offset = row[3] + row[2] + 2
			elif row[1] == 'C':
				dst.write(data[offset:row[3]])
				dst.write(string)
				for i in range(0,0x38 - len(string)):
					dst.write(b'\x00')
				offset = row[3] + 0x38
		count = len(data) - 1
		while data[count] == 0x88:
			count -= 1
		count += 1
		dst.write(data[offset:count])
		#先填充到0x10
		if dst.tell() % 0x10 != 0:
			for i in range(0,0x10 - dst.tell() % 0x10):
				dst.write(b'\x88')
		#判断填充字节数
		buff = int(hex(dst.tell())[-2],16)
		if (buff + 1) % 2 != 0:
			for i in range(0,0x10):
				dst.write(b'\x88')
		#jump表更新
		if uid in jump_dicts_dst:
			for c in range(0,len(jump_dicts_dst[uid])):
				jump_dst.seek(2 + 8 + jump_dicts_dst[uid][c][1] * 0x96,os.SEEK_SET)
				jump_dst.write(struct.pack('L',jump_dicts_dst[uid][c][0] - 0x60))

def main2():
	fn_lst = walk('org')
	for fn in fn_lst:
		src = open(fn,'rb')
		data = src.read()
		m = hashlib.md5()
		m.update(data)
		src = open(fn.replace('org','dst'),'rb')
		data = src.read()
		m2 = hashlib.md5()
		m2.update(data)
		if m.hexdigest() != m2.hexdigest():
			print(fn)
			print(m.hexdigest())
			print(m2.hexdigest())

main()


from django.urls import path, re_path
# from django.conf.urls import url
from .views import SampleTemplateView, MyCreateView, MyUpdateView, MyDeleteView
from .views import find
#from django.views.generic import TemplateView

urlpatterns = [
    path('sample/', SampleTemplateView.as_view(), name='index'),
    path('sample/create', MyCreateView.as_view(), name='create'),
    path('sample/find', find, name='find'),
    re_path('sample/edit/(?P<pk>\d+)$', MyUpdateView.as_view(), name='edit'),  #汎用viewでURLに値を渡すには、re_pathがいいかな？
    re_path('sample/delete/(?P<pk>\d+)$', MyDeleteView.as_view(), name='delete')
]


from datetime import datetime, timedelta
from django.db.models import Avg
import copy

from ..enums.definitions import platform_map
from ..analyzer.models import Analysis

def combine_search_scores(search_id):
    result = Analysis.objects.filter(search_id=search_id).aggregate(Avg('compound'))
    return result['compound__avg']

# expects list of analysis models
def combine_analysis_scores(analysis_list, start, end, query=""):
    buckets = {}
    avg_results = []
    delta = timedelta(days=1)
    start = datetime.combine(start, datetime.min.time())
    end = datetime.combine(end, datetime.min.time())

    bucket_dates = []
    bucket_filled = False
    original_start = start

    platforms = set([])
    for analysis in analysis_list:
        key = query + ' (' + platform_map['reverse'][analysis.collector_type] + ')'
        platforms.add(key)

    for platform in platforms:
        buckets[platform] = {}
        while start <= end:
            buckets[platform][start] = []
            if not bucket_filled:
                bucket_dates.append(start)
            start += delta
        start = original_start
        bucket_filled = True

    for analysis in analysis_list:
        floor = floor_by_day(analysis.date)
        key = query + ' (' + platform_map['reverse'][analysis.collector_type] + ')'
        buckets[key][floor].append(analysis.compound)

    for date_bucket in bucket_dates:
        result_obj = {'time': date_bucket}
        for platform in platforms:
            scores = buckets[platform][date_bucket]
            avg_score = 0
            if len(scores) != 0:
                avg_score = round(sum(scores)/len(scores), 2)
            result_obj[platform] = avg_score
        avg_results.append(result_obj)

    return avg_results

# datescores should look like [{'time': DATETIME, platform1: COMPOUNDSCORE, platform2: COMPOUNDSCORE, ...}, ...]
def union_scores(datescores1, datescores2, startdate, enddate):
    # variable number of platforms in each datescore
    platforms_all = set([])
    platforms1 = set([])
    platforms2 = set([])
    for item in datescores1:
        platforms1 = platforms1.union(item.keys())
    for item in datescores2:
        platforms2 = platforms2.union(item.keys())
    if 'time' in platforms1: platforms1.remove('time')
    if 'time' in platforms2: platforms2.remove('time')
    platforms_all = platforms1.union(platforms2)
    empty_platforms_obj = {platform: None for platform in platforms_all}
    time_to_scores = {}
    for item in datescores1:
        datekey = datetime.combine(item['time'], datetime.min.time())
        time_to_scores[datekey] = copy.deepcopy(empty_platforms_obj)
        for platform in platforms1:
            time_to_scores[datekey][platform] = item[platform]

    for item in datescores2:
        datekey = datetime.combine(item['time'], datetime.min.time())
        if datekey not in time_to_scores:
            time_to_scores[datekey] = copy.deepcopy(empty_platforms_obj)
        for platform in platforms2:
            time_to_scores[datekey][platform] = item[platform]

    # bucketing by days only for now
    delta = timedelta(days=1)
    date = datetime.combine(startdate, datetime.min.time())
    limit = datetime.combine(enddate, datetime.min.time())
    union = []
    while date <= limit:
        pt = {'time': date}
        pt.update(empty_platforms_obj)
        if date in time_to_scores:
            for platform in platforms_all:
                pt[platform] = time_to_scores[date][platform]
        union.append(pt)
        date += delta
    return union

#returns item in dates that is closest to date
def nearest(dates, date):
    date = date.replace(tzinfo=None)
    return min(dates, key=lambda x: abs(x - date))

def floor_by_day(dt):
    return datetime.combine(dt.date(), datetime.min.time())


import time
import torch
import subprocess
import os
from model import EAST
from detect import detect_dataset, detect, plot_boxes
import numpy as np
import shutil
from PIL import Image
import cv2
from binary_eval import confusion_matrix
import pandas as pd

def evaluation(model_path, test_img_path, test_gt_path, iou_thres, scroe_thres, nms_thres):
	device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

	valid_images = os.listdir(test_img_path)
	if '.DS_Store' in valid_images:
		valid_images.remove('.DS_Store')

	# Init.
	fTP, fFP, fFN, total_recall, total_precision, total_pred_boxes, total_gt_boxes, total_success_boxes = 0, 0, 0, 0, 0, 0, 0, 0
	pred_times = []

	model = EAST().to(device) # to gpu
	print('\nCurrent Model Path: ', model_path)
	model.load_state_dict(torch.load(model_path))
	print('\nSuccess load model ...')

	err_images = []
	diff_list = []

	model = model.eval()
	for i in valid_images:
		img = Image.open(test_img_path + '/' + i)

		pred_start = time.time()
		# Prediction boxes
		pred_boxes = detect(img, model, device, score_threshold=scroe_thres, nms_threshold=nms_thres)

		pred_end = time.time() - pred_start
		pred_times.append(pred_end)

		gt_boxes = []
		# GT boxes
		anno = test_gt_path + '/' + i.split('.')[0] + '.txt'

		with open(anno, 'r') as f:
			while True:
				l = f.readline()
				if l == '':
					break

				if '\n' in l:
					l = l.split('\n')[0]

				gt_boxes.append([int(x) for x in l.split(',')[:8]])

		# number of boxes
		n_gt_boxes = len(gt_boxes)
		n_pred_boxes = 0

		if pred_boxes is not None:
			n_pred_boxes = len(pred_boxes)

			total_pred_boxes += n_pred_boxes
			total_gt_boxes += n_gt_boxes
			diff_boxes = n_gt_boxes - n_pred_boxes
			diff_list.append(diff_boxes)

			# Current Image Acc
			TP, FP, FN, r, p, thresh_bboxes = confusion_matrix(pred_boxes, gt_boxes, iou_thres)
			total_success_boxes += len(thresh_bboxes)

			# Draw pred boxes
			plot_img = plot_boxes(img, thresh_bboxes, False)
			plot_img = plot_boxes(img, gt_boxes, True)
			plot_img = plot_img.convert('RGB')
			plot_img = np.array(plot_img)
			plot_img = cv2.cvtColor(plot_img, cv2.COLOR_RGB2BGR)
			plot_img = cv2.putText(plot_img, 'Inf Box : '+str(len(thresh_bboxes)), (10,50),
									cv2.FONT_HERSHEY_COMPLEX_SMALL, 3., (0,0,255), 2)# plot prediction
			plot_img = cv2.putText(plot_img, 'GT Box : '+str(len(gt_boxes)), (int(plot_img.shape[1]/2),50),
									cv2.FONT_HERSHEY_COMPLEX_SMALL, 3., (255,0,0), 2)# plot gt
			cv2.imwrite('./test_output/' + i, plot_img)

			if r == 0.:
				err_images.append(i)

			# print('Image: {}  Recall: {:.4f}  Precision: {:.4f}  PredBoxes: {}  GTBox: {}  PredTime: {:.4f}sec'.format(
			# 	i, r, p, len(pred_boxes), len(gt_boxes), pred_end))

		else: # Detection false
			TP, FP = 0, 0
			FN = n_gt_boxes
			diff_list.append(n_gt_boxes)

			# print('Image: {},  Recall: {:.4f}  Precision: {:.4f}  PredBoxes: {}  GTBox: {}  PredTime: {:.4f}sec'.format(
			# 		i, 0, 0, 0, len(gt_boxes), pred_end))

		# Total confusion matrix
		fTP += TP
		fFP += FP
		fFN += FN

	if fTP != 0:
		total_recall = fTP / total_gt_boxes
		total_precision = fTP / total_pred_boxes

	print("total gt boxes: {}, total pred boxes: {}, success boxes: {}".format(total_gt_boxes, total_pred_boxes, total_success_boxes))
	# print('IoU: {}, ConfScore: {}, TP: {}, FN: {}, FP: {}, avgTP: {:.2f}, avgFN: {:.2f}, avgFP: {:.2f}'.format(
	# 	iou_thres, scroe_thres,
	# 	fTP, fFN, fFP,
	# 	(fTP / 100), (fFN / 100), (fFP / 100)
	# ))

	print('='*50)
	print('TestImage: {}  Recall: {:.4f}  Precision: {:.4f}  AvgPredTime: {:.4f}sec'.format(
		len(valid_images),
		total_recall,
		total_precision,
		sum(pred_times)/len(pred_times)
	))
	print()

	# Calc RMSE
	min_diff_boxes = min(diff_list)
	max_diff_boxes = max(diff_list)
	m = 0
	for i in diff_list:
		m += (i ** 2)

	mse = m / len(diff_list)
	rmse = mse ** 0.5

	print('Higher: {}, Lower: {}, MSE: {}, RMSE: {}'.format(min_diff_boxes, max_diff_boxes, mse, rmse))

	return total_recall, total_precision

if __name__ == '__main__':
	model_name = './pths/ENKR_epoch_198.pth'
	test_img_path = os.path.abspath('./ENKR_DATA/test_img')
	test_gt_path = os.path.abspath('./ENKR_DATA/test_gt')

	# recall, precision = evaluation(
	# 	model_name,
	# 	test_img_path,
	# 	test_gt_path,
	# 	iou_thres=0.5,
	# 	scroe_thres=0.9,
	# 	nms_thres=0.4)

	# Eval
	# conf_score = [0.9, 0.99, 0.999, 0.9999, 0.99999, 0.999999]
	conf_score = [0.5, 0.7]
	# iou_list = [x/10 for x in range(3, 9)]
	iou_list = [0.5]

	for score in conf_score:
		scores, ious, rc, pc = [], [], [], []

		for i in iou_list:
			if os.path.isfile('./pths/optimize2.csv'):
				optimize_df = pd.read_csv('./pths/optimize2.csv')

				scores = optimize_df['conf_score'].to_list()
				ious = optimize_df['iou'].to_list()
				rc = optimize_df['recall'].to_list()
				pc = optimize_df['precision'].to_list()

			optimize_df = pd.DataFrame(columns=['conf_score', 'iou', 'recall', 'precision'])

			recall, precision = evaluation(
									model_name,
									test_img_path,
									test_gt_path,
									iou_thres=i,
									scroe_thres=score,
									nms_thres=0.4)

			scores.append(score)
			ious.append(i)
			rc.append(recall)
			pc.append(precision)

			optimize_df['conf_score'] = scores
			optimize_df['iou'] = ious
			optimize_df['recall'] = rc
			optimize_df['precision'] = pc

			optimize_df.to_csv('./pths/optimize2.csv', index=False)


import os
from zipfile import ZipFile

def create_assets_archive(directory):
    assets_name=directory.replace("assets-", "").split(".")[-1]
    print(f"Creating Assets.{assets_name}.zip for folder {directory}")
    with ZipFile(f'Assets.{assets_name}.zip', 'w') as myzip:
        dir_leaf = ""
        for root, _, files in os.walk(directory, topdown=False):
            for fi in files:
                print(f"Adding bin {fi} to Assets.{assets_name}.zip")
                myzip.write(os.path.join(root, fi), arcname=f"assets/{fi}")
                dir_leaf = os.path.join(root, fi)
        asset_path = directory.replace("assets-", "").replace(".", "/")
        for root, _, files in os.walk(os.path.join("Assets", asset_path, "fonts"), topdown=False):
            for fi in files:
                print(f"Adding mks_font/{fi} to Assets.{assets_name}.zip")
                myzip.write(os.path.join(root, fi), arcname=f"assets/{fi}")

def create_firmware_archive(directory):
    firmware_name = directory.replace("firmware-", "")
    print(f"Creating {firmware_name}.zip for folder {directory}")
    with ZipFile(f'{firmware_name}.zip', 'w') as myzip:
        myzip.write(f"{directory}/Robin_nano35.bin", arcname="Robin_nano35.bin")

for directory in os.listdir("."):
    if directory.startswith("assets-"):
        create_assets_archive(directory)
    elif directory.startswith("firmware-"):
        create_firmware_archive(directory)


"""pandas基礎
Seriesの作成方法
(リストから作成する)

[説明ページ]
https://tech.nkhn37.net/pandas-series-create-basic/#NumPy
"""
import pandas as pd

# リストからSeriesを作成する
# int
data = pd.Series([1, 5, 2, 4, 5])
print(data, "\n")

# float
data = pd.Series([1.0, 1.5, 2.0, 4.0, 5.0])
print(data)