import plotly.plotly as py
from plotly.graph_objs import Scatter
import plotly

import datetime

def set_credentials():

#   Set credentials for online plotting
#     plotly.tools.set_credentials_file(username='aarjay00', api_key='89q89hwig4')

    plotly.tools.set_credentials_file(username='aarjay80', api_key='7dzds0fegi')

def basic_scatter_plot_online(xy,graph_name):
    set_credentials()
    x=[i[0] for i in xy ]
    y=[i[1] for i in xy]
    trace=Scatter(x=x,y=y,mode='markers')
    plotly.plotly.plot([trace],filename=graph_name)

def basic_scatter_plot_offline(xy,graph_name):
    set_credentials()
    x=[i[0] for i in xy ]
    y=[i[1] for i in xy]

    marker=dict(color='red',size='5',symbol='square-dot')
    trace=Scatter(x=x,y=y,mode='markers',name='col_name',marker=marker,connectgaps=True)
    plotly.offline.iplot([trace],filename=graph_name)

dev_1 = ['U','U','E','D','D','D','U','X']
dev_2 = ['U','U','U','D','D','U']
activity_color_map={'U':'blue','E':'green','D':'red'}

def create_trace_from_dev_activity(dev_activity,dev_name):

        # trace_x_understand = [idx for idx,activity in enumerate(dev_activity) if activity=='U']
        # trace_x_edit = [idx for idx,activity in enumerate(dev_activity) if activity=='E']
        # trace_x_debug= [idx for idx,activity in enumerate(dev_activity) if activity=='D']
        # trace_x_none  = [idx for idx,activity in enumerate(dev_activity) if activity=='X']

        trace_x_understand = [datetime.datetime.fromtimestamp(int(activity[1])) for activity in dev_activity if activity[0] == 'U']
        trace_x_edit = [datetime.datetime.fromtimestamp(int(activity[1])) for activity in dev_activity if activity[0] == 'E']
        trace_x_debug   = [datetime.datetime.fromtimestamp(int(activity[1])) for activity in dev_activity if activity[0] == 'D']
        trace_x_none = [datetime.datetime.fromtimestamp(int(activity[1])) for activity in dev_activity if activity[0] == 'X']

        marker_understand =dict(color='blue',size='15',symbol='square-dot')
        marker_edit =dict(color='green',size='15',symbol='square-dot')
        marker_debug =dict(color='red',size='15',symbol='square-dot')
        marker_none = dict(color='black',size='15',symbol='square-dot')

        trace_understand = Scatter(x=trace_x_understand,y=[dev_name]*len(trace_x_understand)
                                   ,marker=marker_understand
                                   ,hoverinfo='none'
                                   ,mode='markers'
                                   ,showlegend=False
                                  ,name='understand_actions')

        trave_edit = Scatter(x=trace_x_edit,y=[dev_name]*len(trace_x_edit)
                             ,marker=marker_edit
                             ,hoverinfo='none'
                             ,mode='markers'
                             ,showlegend=False
                            ,name='edit_actions')

        trace_debug = Scatter(x=trace_x_debug,y=[dev_name]*len(trace_x_debug)
                              ,marker=marker_debug,
                              hoverinfo='none',
                              mode='markers'
                              ,showlegend=False
                             ,name='debug_actions')

        trace_none = Scatter(x=trace_x_none,y=[dev_name]*len(trace_x_none)
                              ,marker=marker_none,
                              hoverinfo='none',
                              mode='markers'
                              ,showlegend=False
                             ,name='none_actions')

        return [trace_understand,trave_edit,trace_debug,trace_none]

def create_dev_activity_graph(dev_activity,dev_name):
    # plotly.offline.init_notebook_mode()
    dev_name=dev_name.split('/')[-1].strip()
    set_credentials()
    trace_collection=[]
    trace_collection.extend(create_trace_from_dev_activity(dev_activity,dev_name))
#     plotly.plotly.image.save_as(trace_collection,dev_name+'.png')
    plotly.plotly.plot(trace_collection,filename=dev_name)
    # plotly.offline.iplot(trace_collection)
# trace_collection.extend(create_trace_from_dev_activity(dev_2,'dev_2'))

def create_all_dev_activity_graph(dev_activity_dict):

    set_credentials()
    trace_collection=[]

    for user_name,user_activity in dev_activity_dict.iteritems():

        trace_collection.extend(create_trace_from_dev_activity(user_activity,user_name))

    plotly.plotly.plot(trace_collection,"All_Dev")

# basic_scatter_plot_offline([[1,'b'],[2,'a']],'trial')


# -*- coding: utf-8 -*-
import psycopg2
import time
from openerp import models, api, _
from openerp.exceptions import ValidationError

class AccountVoucher(models.Model):
    _inherit = 'account.voucher'

    @api.multi
    def action_move_line_create(self):
        for voucher in self:
            # get doctype
            refer_type = voucher.type
            doctype = self.env['res.doctype'].get_doctype(refer_type)
            # --
            voucher = voucher.with_context(doctype_id=doctype.id)
            super(AccountVoucher, voucher).action_move_line_create()
        return True

    @api.multi
    def signal_workflow(self, trigger):
        """ Ensure that, when sequence is locked, it will repeat again """
        try:
            #  This part should not exists (but we need to avoid error)
            return super(AccountVoucher, self).signal_workflow(trigger)
        except psycopg2.OperationalError:
            # Let's retry 3 times, each to wait 0.5 seconds
            retry = self._context.get('retry', 1)
            if retry <= 5:
                time.sleep(0.5)
                retry += 1
                self._cr.rollback()
                return self.with_context(retry=retry).signal_workflow(trigger)
            raise ValidationError(
                _('Waiting for next number, please try again later!'))
        except Exception:
            raise


from typing import Callable, List

import pytest

from twoSumAllAnswers import Solution

solution = Solution()

@pytest.mark.parametrize(
    "fn",
    (
        (solution.twoSumAlbert),
        (solution.twoSumDorian),
    ),
)
@pytest.mark.parametrize(
    "nums, target, want",
    (
        (
            [1, 1, 1, 1],
            2,
            [
                (0, 1),
                (0, 2),
                (0, 3),
                (1, 2),
                (1, 3),
                (2, 3),
            ],
        ),
        (
            [1, 2, 2, 1, 2, 1],
            2,
            [(0, 3), (0, 5), (3, 5)],
        ),
    ),
)
def test_twoSumAllAnswers(fn: Callable, nums: List[int], target: int, want: List[str]):
    got = fn(nums, target)
    got = sorted(tuple(sorted((a, b))) for a, b in got)
    assert got == want

@pytest.mark.benchmark()
@pytest.mark.parametrize(
    "fn",
    (
        (solution.twoSumAlbert),
        (solution.twoSumDorian),
    ),
)
@pytest.mark.parametrize(
    "nums, target",
    (
        ([1] * 100, 2),
        ([1] * 100, 0),
    ),
)
def test_benchmark_twoSumAllAnswers(
    benchmark, fn: Callable, nums: List[int], target: int
):
    benchmark(fn, nums, target)


import re
import csv

#these are the regexes that match the time formats
patterns = ['[0-9][0-9]\:[0-9][0-9]\:[0-9][0-9]', '[0-9]\:[0-9][0-9]\:[0-9][0-9]']

with open('sr4.csv', 'r') as infile:
	outfile = open('Crime_Out.csv', 'w')
	reader = csv.DictReader(infile, delimiter = ',')
	writer = csv.writer(outfile, delimiter = ',')
	for row in reader:
		match = re.search('(([0-9][0-9])|[0-9])\:', row['REPORT_DAT'])
		if not match:
			print('No Match Found')
		else:
			writer.writerow([('2010-1-1 ' + match.group(0) + '00:00'), ('2010-1-1 ' + match.group(0) + '00:10'), row['XBLOCK'], row['YBLOCK']])
	outfile.close()
	infile.close()


# each item to be packed is represented as a set of triples (size,value,name)
def itemSize(item): return item[0]
def itemValue(item): return item[1]
def itemName(item): return item[2]

# example used in lecture
exampleItems = [(3,3,'A'),
        (4,1,'B'),
        (8,3,'C'),
        (10,4,'D'),
        (15,3,'E'),
        (20,6,'F')]

exampleSizeLimit = 32

def pack(items,sizeLimit):
    P = {}
    for nItems in range(len(items)+1):
        for lim in range(sizeLimit+1):
            if nItems == 0:
                P[nItems,lim] = 0
            elif itemSize(items[nItems-1]) > lim:
                P[nItems,lim] = P[nItems-1,lim]
            else:
                P[nItems,lim] = max(P[nItems-1,lim],
                    P[nItems-1,lim-itemSize(items[nItems-1])] +
                    itemValue(items[nItems-1]))

    L = []
    nItems = len(items)
    lim = sizeLimit
    while nItems > 0:
        if P[nItems,lim] == P[nItems-1,lim]:
            nItems -= 1
        else:
            nItems -= 1
            L.append(itemName(items[nItems]))
            lim -= itemSize(items[nItems])

    L.reverse()
    return L


import sys

def check_current_number(number, preamble):
    found = False

    for i in range(0,len(preamble)-1):
        for j in range(1,len(preamble)):
            if preamble[i] + preamble[j] == number:
                found = True
                break

    return found

def get_invalid_number(data, preamble_size):
    number_ok = True
    preamble_index = 0

    while number_ok:
        current_number = data[preamble_index + preamble_size]
        number_ok = check_current_number(current_number, data[preamble_index:preamble_index + preamble_size])
        preamble_index += 1

    return current_number

def find_weakness(data, current_number):
    for i in range(0,len(data)):
        sum = data[i]
        pivot = i + 1
        while (pivot < len(data)) and (sum < current_number):
            sum += data[pivot]
            pivot += 1
            if sum == current_number:
                numbers_list = [data[x] for x in range(i, pivot)]
                print("Weakness: %d " % (max(numbers_list) + min(numbers_list)))
                sys.exit(0)

def main():
    with open('input.txt') as f:
        lines = f.readlines()

    data = [int(line) for line in lines]
    preamble_size = 25
    invalid_number = get_invalid_number(data, preamble_size)
    find_weakness(data, invalid_number)

if __name__ == '__main__':
    main()


import os

# our imports
from mockbuild.trace_decorator import getLog, traceLog
import mockbuild.util

requires_api_version = "1.1"

# plugin entry point
@traceLog()
def init(plugins, conf, buildroot):
    system_ram_bytes = os.sysconf(os.sysconf_names['SC_PAGE_SIZE']) * os.sysconf(os.sysconf_names['SC_PHYS_PAGES'])
    system_ram_mb = system_ram_bytes / (1024 * 1024)
    if system_ram_mb > conf['required_ram_mb']:
        Tmpfs(plugins, conf, buildroot)
    else:
        getLog().warning(
            "Tmpfs plugin disabled. "
            "System does not have the required amount of RAM to enable the tmpfs plugin. "
            "System has %sMB RAM, but the config specifies the minimum required is %sMB RAM. ",
            system_ram_mb, conf['required_ram_mb'])

class Tmpfs(object):
    """Mounts a tmpfs on the chroot dir"""
    # pylint: disable=too-few-public-methods
    @traceLog()
    def __init__(self, plugins, conf, buildroot):
        self.buildroot = buildroot
        self.main_config = buildroot.config
        self.state = buildroot.state
        self.conf = conf
        self.maxSize = self.conf['max_fs_size']
        self.mode = self.conf['mode']
        self.optArgs = ['-o', 'mode=%s' % self.mode]
        self.optArgs += ['-o', 'nr_inodes=0']
        if self.maxSize:
            self.optArgs += ['-o', 'size=' + self.maxSize]
        plugins.add_hook("mount_root", self._tmpfsMount)
        plugins.add_hook("postumount", self._tmpfsPostUmount)
        plugins.add_hook("umount_root", self._tmpfsUmount)
        if not os.path.ismount(self.buildroot.make_chroot_path()):
            self.mounted = False
        else:
            self.mounted = True
        getLog().info("tmpfs initialized")

    @traceLog()
    def _tmpfsMount(self):
        getLog().info("mounting tmpfs at %s.", self.buildroot.make_chroot_path())

        if not self.mounted:
            mountCmd = ["mount", "-n", "-t", "tmpfs"] + self.optArgs + \
                       ["mock_chroot_tmpfs", self.buildroot.make_chroot_path()]
            mockbuild.util.do(mountCmd, shell=False)
        else:
            getLog().info("reusing tmpfs at %s.", self.buildroot.make_chroot_path())
        self.mounted = True

    @traceLog()
    def _tmpfsPostUmount(self):
        if "keep_mounted" in self.conf and self.conf["keep_mounted"]:
            self.mounted = False
        else:
            self._tmpfsUmount()

    @traceLog()
    def _tmpfsUmount(self):
        if not self.mounted:
            return
        force = False
        getLog().info("unmounting tmpfs.")
        umountCmd = ["umount", "-n", self.buildroot.make_chroot_path()]
        # since we're in a separate namespace, the mount will be cleaned up
        # on exit, so just warn if it fails here
        try:
            mockbuild.util.do(umountCmd, shell=False)
        # pylint: disable=bare-except
        except:
            getLog().warning("tmpfs-plugin: exception while umounting tmpfs! (cwd: %s)", mockbuild.util.pretty_getcwd())
            force = True

        if force:
            # try umounting with force option
            umountCmd = ["umount", "-R", "-n", "-f", self.buildroot.make_chroot_path()]
            try:
                mockbuild.util.do(umountCmd, shell=False)
            # pylint: disable=bare-except
            except:
                getLog().warning(
                    "tmpfs-plugin: exception while force umounting tmpfs! (cwd: %s)", mockbuild.util.pretty_getcwd())
        self.mounted = False


class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize != 0: return False

        dic = {}
        for k in hand:
            dic[k] = dic.get(k, 0) + 1

        minH = list(dic.keys())
        heapify(minH)

        while minH:
            first = minH[0]

            for i in range(first, first + groupSize):
                if i not in dic:
                    return False
                dic[i] -= 1
                if dic[i] == 0:
                    heapq.heappop(minH)
        return True


import argparse
import asyncio
import sys
import traceback as tb
import types
from typing import Any, Optional, Union

import quamash
from PyQt5.QtCore import Qt, QThread, pyqtRemoveInputHook
from PyQt5.QtGui import QColor, QGradient, QPaintEvent, QPixmap
from PyQt5.QtWidgets import QApplication, QSplashScreen

from bubblesub.api import Api
from bubblesub.api.log import LogLevel
from bubblesub.cfg import ConfigError
from bubblesub.ui.assets import ASSETS_DIR
from bubblesub.ui.main_window import MainWindow

class MySplashScreen(QSplashScreen):
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self._painted = False

        self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
        self.setWindowFlags(
            Qt.WindowType(
                Qt.WindowType.SplashScreen
                | Qt.WindowType.FramelessWindowHint
                | Qt.WindowType.WindowStaysOnTopHint
            )
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

    def paintEvent(self, event: QPaintEvent) -> None:
        super().paintEvent(event)
        self._painted = True

    def showMessage(
        self,
        text: str,
        alignment: int = Qt.AlignmentFlag.AlignLeft,
        color: Union[QColor, Qt.GlobalColor, QGradient] = Qt.GlobalColor.black,
    ) -> None:
        self._painted = False
        super().showMessage(
            text, Qt.AlignmentFlag.AlignBottom, Qt.GlobalColor.white
        )
        self._ensure_painted()

    def _ensure_painted(self) -> None:
        while not self._painted:
            QThread.usleep(1000)
            QApplication.processEvents()

class Logger:
    def __init__(self, api: Api) -> None:
        self._api = api
        self._main_window: Optional[MainWindow] = None
        self._queued_logs: list[tuple["LogLevel", str]] = []

        sys.excepthook = self._on_error
        api.log.logged.connect(self._on_log)

    def set_main_window(self, main_window: MainWindow) -> None:
        self._main_window = main_window
        for log_level, text in self._queued_logs:
            self._on_log(log_level, text)
        self._queued_logs.clear()

    def _on_log(self, level: LogLevel, text: str) -> None:
        if self._main_window:
            self._main_window.console.log_window.log(level, text)
        else:
            self._queued_logs.append((level, text))

    def _on_error(
        self,
        type_: type[BaseException],
        value: BaseException,
        traceback: types.TracebackType,
    ) -> None:
        self._api.log.error("An unhandled error occurred: ")
        self._api.log.error(
            "".join(tb.format_exception(type_, value, traceback))
        )

class Application:
    def __init__(self, args: argparse.Namespace):
        self._args = args
        self._splash: Optional[QSplashScreen] = None

        pyqtRemoveInputHook()

        self._app = QApplication(sys.argv)
        self._app.setApplicationName("bubblesub")
        self._loop = quamash.QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

    def splash_screen(self) -> None:
        pixmap = QPixmap(str(ASSETS_DIR / "bubblesub.png"))
        pixmap = pixmap.scaledToWidth(640)
        self._splash = MySplashScreen(pixmap)
        self._splash.show()
        self._splash.showMessage("Loading API...")

    def run(self, api: Api) -> None:
        with self._loop:
            logger = Logger(api)

            try:
                if self._splash:
                    self._splash.showMessage("Loading config...")
                if not self._args.no_config:
                    api.cfg.load(api.cfg.DEFAULT_PATH)
            except ConfigError as ex:
                api.log.error(str(ex))

            if self._splash:
                self._splash.showMessage("Loading commands...")
            api.cmd.reload_commands()

            if self._splash:
                self._splash.showMessage("Loading UI...")
            main_window = MainWindow(api)
            api.gui.set_main_window(main_window)
            logger.set_main_window(main_window)

            # load empty file
            api.subs.unload()

            main_window.show()

            def save_config() -> None:
                if not self._args.no_config:
                    assert api.cfg.root_dir is not None
                    api.cfg.save(api.cfg.root_dir)

            api.cfg.opt.changed.connect(save_config)

            if self._args.file:
                api.cmd.run_cmdline([["open", "--path", self._args.file]])

            if self._splash:
                self._splash.finish(main_window)

            self._loop.run_forever()

        save_config()


#!/usr/bin/env python
import os
import sys

classes = [
    "AddDocumentFloatingActionButton",
    "DocumentActionsButton",
    "DocumentForm",
    "DocumentListMapView",
    "DocumentListScaffold",
    "DocumentListSortButton",
    "DocumentListView",
    "DocumentPage",
    "TypedInputField",
    "SortOrder",
    "DocumentList",
]

url_base = "https://pub.dartlang.org/documentation/rapido/latest/rapido/"
url_tail = "-class.html"

input = sys.stdin
output = sys.stdout
input = open(sys.argv[1])
output = open(sys.argv[2], 'w')
for line in input.xreadlines():
    for c in classes:
        rtext = " [" + c + "](" + url_base + c + url_tail + ") "
        rtext1 = " [" + c + "](" + url_base + c + url_tail + "). "
        rtext2 = " [" + c + "](" + url_base + c + url_tail + "), "
        rtext3 = "[" + c + "](" + url_base + c + url_tail + ")"

        stext = " " + c + " "
        stext1 = " " + c + ". "
        stext2 = " " + c + ", "

        line = line.replace(stext, rtext)
        line = line.replace(stext1, rtext1)
        line = line.replace(stext2, rtext2)

        if(line.find(c) == 0):
            line = line.replace(c, rtext3, 1)
    output.write(line)
output.close()
input.close()


# -*- coding: utf-8 -*-
#剩余单张牌的数量来模拟概率
import matplotlib.pyplot as plt
import numpy as np
c_zhuang = 0#庄赢的次数
ya_zhuang_sum = 0
ya_zhuang_win_sum = 0
c_xian = 0#闲赢的次数
c_he = 0#和的次数

#xian_10 = 0
#he_10 = 0

counter = 0
yazhuang_counter = 0
c_z10 = []
c_win = 0
def diff(z, x):#庄赢1，闲赢-1，和是0
    if z>x:
        r = 1
    elif z<x:
        r = -1
    else:
        r = 0
    return r

def p2(f, s):#返回前两张牌加起来的点数

    if f > 9:
        f = 0
    if s > 9:
        s = 0
    sum = f+s
    if sum >= 10:
        return sum-10
    else:
        return sum

def add(z_point, x_third):#庄是否补牌
    if z_point < 4 and x_third != 8:
        return True
    elif z_point == 4 and (x_third > 1 and x_third < 8):
        return  True
    elif z_point == 5 and (x_third > 3 and x_third < 8):
        return  True
    elif z_point == 6 and (x_third > 5 and x_third < 8):
        return  True
    else:
        return False

def play(z):#玩一局牌
    global c_zhuang
    global c_xian
    global c_he
    global counter
    global yazhuang_counter
    global c_win
    global ya_zhuang_sum
    global ya_zhuang_win_sum
    rand_play_time = 10
    ya_zhuang_win_within_done = 0
    ya_zhuang_within_done_sum = 0
    ya_zhuang_win_within_10 = 0
    kaiguan = 0
    while len(z) >= 2:
        if len(z) < 10:
            break
        zhuang = z[0:2]
        xian = z[2:4]
        zhuang_point = p2(zhuang[0],zhuang[1])
        xian_point = p2(xian[0],xian[1])
        if xian_point > 5:#闲不补牌
            if zhuang_point <=5:#闲不补牌的情况下庄补牌
                zhuang_point = p2(zhuang_point,z[4])
                result = diff(zhuang_point,xian_point)
#                if z.tolist().count(left_num) == left_counter:
                if result == 1:
                    c_zhuang += 1
                elif result == -1:
                    c_xian += 1
                elif result == 0:
                    c_he += 1
                    #print(z)
                z = z[5::]  #通过上面的操作把运算过的牌去掉，只保留剩下的牌

            else:#庄闲都不补牌
                result = diff(zhuang_point,xian_point)
#                if z.tolist().count(left_num) == left_counter:
                if result == 1:
                    c_zhuang += 1
                elif result == -1:
                    c_xian += 1
                elif result == 0:
                    c_he += 1
                    #print(z)
                z = z[4::]

        else:#闲补牌
            xian_point = p2(xian_point,z[4])
            is_z_add = add(zhuang_point,z[4])
            if is_z_add:#闲补牌庄补牌
                zhuang_point = p2(zhuang_point,z[5])
                result = diff(zhuang_point,xian_point)
#                if z.tolist().count(left_num) == left_counter:
                if result == 1:
                    c_zhuang += 1
                elif result == -1:
                    c_xian += 1
                elif result == 0:
                    c_he += 1
                    #print(z)
                z = z[6::]

            else:#闲补牌庄不补牌
                result = diff(zhuang_point,xian_point)
                if result == 1:
                    c_zhuang += 1
                elif result == -1:
                    c_xian += 1
                elif result == 0:
                    c_he += 1
                    #print(z)
                z = z[5::]
        if kaiguan == 0:
            rand_play_time = rand_play_time - 1#计数器，每玩1局减1
        else:
            rand_paly_time = 10
        if result == 1 and kaiguan == 0:#如果庄赢+1
            ya_zhuang_win_within_10 += 1 #统计10局内庄赢的次数，10次内小于3次就开始押注
        #print("rand_play_time: ",rand_play_time," ya_zhuang_win_within_10 ",ya_zhuang_win_within_10)
        if rand_play_time == 0:
            if ya_zhuang_win_within_10 <= 3:
                kaiguan = 1
                ya_zhuang_sum += 1
                ya_zhuang_within_done_sum += 1
                if result == 1:
                    ya_zhuang_win_sum += 1
                    ya_zhuang_win_within_done += 1
            else:#如果不满足10次内仅仅中3次庄的话，那就归零重新来
                rand_play_time = 10
                kaiguan = 0
                ya_zhuang_win_within_10 = 0
                ya_zhuang_win_within_done=0
                ya_zhuang_within_done_sum=0
        if ya_zhuang_within_done_sum >9 and ya_zhuang_win_within_done/ya_zhuang_within_done_sum >= 0.7:
        #if ya_zhuang_within_done_sum ==20:
            rand_play_time = 10
            kaiguan = 0
            ya_zhuang_win_within_10 = 0
            ya_zhuang_win_within_done=0
            ya_zhuang_within_done_sum=0

        counter += 1
#        if counter%10 == 0:
#            if c_zhuang <= 3:
#            c_z10.append(c_zhuang)
#            c_zhuang = 0
#            c_xian = 0
#            c_he = 0

x = np.arange(1,14,1)

for i in range(10000):
    z=x.repeat(32)
    np.random.shuffle(z)#生成牌局
    play(z)
print(ya_zhuang_win_sum,ya_zhuang_sum,ya_zhuang_win_sum/ya_zhuang_sum)
#print(c_z10)

#plt.figure(1,figsize=(12,5))   #创建图表1
#plt.plot(c_z10)
#plt.show()

#开仓逻辑：如果10次里面押庄中标次数小于3次，那么就一直押庄；出场：1、有仓位2、10次里面押庄中的次数超过6次，或者收益超过20%
#print("庄: ",round(c_zhuang,4)," 闲: ",round(c_xian,4)," 和： ",round(c_he,4)," 压庄局数: ",yazhuang_counter," 总局数: ",counter)

#if z.tolist().count(left_num) == left_counter:


import numpy as np
from keras.layers import Layer, InputSpec
from keras import backend as K

class Normalize(Layer):
    def __init__(self, scale, **kwargs):
        self.axis = 3 if K.image_dim_ordering() == 'tf' else 1
        self.scale = scale
        super(Normalize, self).__init__(**kwargs)

    def build(self, input_shape):
        self.input_spec = [InputSpec(shape=input_shape)]
        self.W_shape = (input_shape[self.axis],)
        gamma = np.ones(self.W_shape) * self.scale
        self.gamma = K.variable(gamma, name='{}_gamma'.format(self.name))
        self.trainable_weights = [self.gamma]

    def compute_output_shape(self, input_shape):
        return input_shape

    def call(self, x, mask=None):
        x_normed = K.l2_normalize(x, self.axis)
        x_normed *= self.gamma
        return x_normed

    def get_config(self):
        config = { 'scale': self.scale, }
        base_config = super(Normalize, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

class PriorBox(Layer):
    def __init__(self, img_size, min_size, max_size=None, aspect_ratios=None,
                 flip=True, variances=[1.0], clip=False, **kwargs):
        if min_size <= 0:
            raise Exception('min_size must be positive.')
        if max_size:
            if max_size < min_size:
                raise Exception('max_size must be greater than min_size.')
        if K.image_dim_ordering() == 'tf':
            self.haxis = 1
            self.waxis = 2
        else:
            self.haxis = 2
            self.waxis = 3
        self.img_size = img_size
        self.min_size = min_size
        self.max_size = max_size
        self.aspect_ratios = [1.0, 1.0]
        if aspect_ratios:
            for ar in aspect_ratios:
                if ar in self.aspect_ratios:
                    continue
                self.aspect_ratios.append(ar)
                if flip:
                    self.aspect_ratios.append(1.0 / ar)
        self.variances = np.array(variances)
        self.clip = clip
        self.flip = flip
        super(PriorBox, self).__init__(**kwargs)

    def compute_output_shape(self, input_shape):
        num_priors = len(self.aspect_ratios)
        layer_width = input_shape[self.waxis]
        layer_height = input_shape[self.haxis]
        num_boxes = num_priors * layer_width * layer_height
        return (input_shape[0], num_boxes, 8)

    def call(self, x, mask=None):
        if hasattr(x, '_keras_shape'):
            input_shape = x._keras_shape
        elif hasattr(K, 'int_shape'):
            input_shape = K.int_shape(x)
        layer_width = input_shape[self.waxis]
        layer_height = input_shape[self.haxis]
        img_width = self.img_size[0]
        img_height = self.img_size[1]
        num_priors = len(self.aspect_ratios)

        step_x = float(img_width) / float(layer_width)
        step_y = float(img_height) / float(layer_height)

        linx = np.linspace(0.5 * step_x, img_width - 0.5 * step_x, layer_width)
        liny = np.linspace(0.5 * step_y, img_height - 0.5 * step_y, layer_height)

        centers_x, centers_y = np.meshgrid(linx, liny)
        centers_x = centers_x.reshape(-1, 1)
        centers_y = centers_y.reshape(-1, 1)

        prior_boxes = np.concatenate((centers_x, centers_y), axis=1)
        prior_boxes = np.tile(prior_boxes, (1, 2 * num_priors))

        box_widths = []
        box_heights = []
        for ar in self.aspect_ratios:
            if ar == 1 and len(box_widths) == 0:
                box_widths.append(self.min_size)
                box_heights.append(self.min_size)
            elif ar == 1 and len(box_widths) > 0:
                box_widths.append(np.sqrt(self.min_size * self.max_size))
                box_heights.append(np.sqrt(self.min_size * self.max_size))
            elif ar != 1:
                box_widths.append(self.min_size * np.sqrt(ar))
                box_heights.append(self.min_size / np.sqrt(ar))
        box_widths = 0.5 * np.array(box_widths)
        box_heights = 0.5 * np.array(box_heights)

        prior_boxes[:, ::4] -= box_widths
        prior_boxes[:, 1::4] -= box_heights
        prior_boxes[:, 2::4] += box_widths
        prior_boxes[:, 3::4] += box_heights
        prior_boxes[:, ::2] /= img_width
        prior_boxes[:, 1::2] /= img_height
        prior_boxes = prior_boxes.reshape(-1, 4)
        if self.clip:
            prior_boxes = np.minimum(np.maximum(prior_boxes, 0.0), 1.0)

        num_boxes = len(prior_boxes)
        if len(self.variances) == 1:
            variances = np.ones((num_boxes, 4)) * self.variances[0]
        elif len(self.variances) == 4:
            variances = np.tile(self.variances, (num_boxes, 1))
        else:
            raise Exception('Must provide one or four variances.')

        prior_boxes = np.concatenate((prior_boxes, variances), axis=1)
        prior_boxes_tensor = K.expand_dims(K.variable(prior_boxes), 0)
        pattern = [K.shape(x)[0], 1, 1]
        prior_boxes_tensor = K.tile(prior_boxes_tensor, pattern)
        return prior_boxes_tensor

    def get_config(self):
        config = {
            'img_size': tuple(self.img_size),
            'min_size': self.min_size,
            'max_size': self.max_size,
            'aspect_ratios': tuple(self.aspect_ratios),
            'variances': tuple(self.variances),
            'flip': self.flip,
            'clip': self.clip }
        base_config = super(PriorBox, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))


import json
import logging
import os

from kafka import KafkaProducer

from configuration import constants

class LogRetrievalMessage:
    def __init__(self, experiment_id: str, host_name: str, target_path: str, node_id: str):
        self.experimentId = experiment_id
        self.hostName = host_name
        self.userName = os.getlogin()
        self.targetPath = target_path
        self.nodeId = node_id

def resolve_local_log_path(working_directory: str, experiment_id: str):
    return os.path.join(working_directory, experiment_id, "logs", "*")

class LogTransfer:
    def __init__(self, host_name: str, node_id: str, working_directory: str, kafka_bootstrap: str):
        self.host_name = host_name
        self.node_id = node_id
        self.working_directory = working_directory
        self.retrieval_msg_producer = KafkaProducer(
            bootstrap_servers=kafka_bootstrap,
            value_serializer=lambda x: json.dumps(x, default=lambda o: o.__dict__).encode("utf-8")
        )

    def initiate_log_retrieval(self, experiment_id: str):
        local_log_path = resolve_local_log_path(self.working_directory, experiment_id)

        logging.info("Initiating log retrieval")

        self.retrieval_msg_producer.send(
            constants.LOG_RETRIEVAL_TOPIC,
            LogRetrievalMessage(
                experiment_id,
                self.host_name,
                local_log_path,
                self.node_id
            )
        )

    def create_logging_directory(self, experiment_id: str):
        os.makedirs(os.path.join(self.working_directory, experiment_id, "logs"), exist_ok=True)

transfer_handler = None  # To be populated by main program


import bpy
import os
import json
import shutil
import numpy as np
import math
import sys
from shutil import copy

scene=bpy.context.scene
scene_name=scene.name
render=scene.render

cwd = os.getcwd()

scene_path_dtam=cwd+"/../prova_dr/dataset/"+scene_name+"/"
json_path=scene_path_dtam+scene_name+".json"

rem = False
con = False

if os.path.isdir(scene_path_dtam):
    print("directory "+scene_path_dtam+" already exists")
    while(True):
        print("Enter:")
        print("r to remove existing dataset")
        print("c to continue the existing dataset")
        print("q to quit")
        input1 = input()
        if (input1=="r"):
            rem=True
            break
        elif (input1=="c"):
            con=True
            break
        elif (input1=="q"):
            sys.exit()

if(rem):
    shutil.rmtree(scene_path_dtam, ignore_errors=True)

scene.display_settings.display_device = 'sRGB'

#############################################################################
#		generate json for dtam and render images
#############################################################################

engine=''
argv=sys.argv;
if argv[-2]=='CYCLES':
    engine='CYCLES'
    bpy.context.scene.cycles.samples = int(argv[-1])
else:
    engine='BLENDER_EEVEE'

engine_eevee='BLENDER_EEVEE'

scene.use_nodes = True
tree = scene.node_tree
links = tree.links

data_ = {}
data_['cameras']={}

argv = sys.argv

for n in tree.nodes:
    tree.nodes.remove(n)

rl = tree.nodes.new('CompositorNodeRLayers')
d = tree.nodes.new('CompositorNodeDenoise')
l1=links.new(rl.outputs['Image'], d.inputs[0])

v = tree.nodes.new('CompositorNodeComposite')
v.use_alpha = False

mm = tree.nodes.new('CompositorNodeMath')
mm.operation='MULTIPLY'
min_depth_=bpy.data.cameras[0].clip_start
mm.inputs[1].default_value=1.0/min_depth_

links.new(rl.outputs['Depth'], mm.inputs[0])

mp = tree.nodes.new('CompositorNodeMath')
mp.operation='POWER'
mp.inputs[1].default_value=-1
links.new(mm.outputs[0], mp.inputs[0])

render.image_settings.compression=0
#render.image_settings.exr_codec='ZIP'
render.image_settings.exr_codec='NONE'

i=0
# iterate through objects
for obj_ in bpy.data.objects:
    if obj_.type=="CAMERA":

        name_=obj_.name
        name_rgb="rgb_"+name_
        name_depth="depth_"+name_

        path_rgb=scene_path_dtam+name_rgb
        path_depth=scene_path_dtam+name_depth

        camera=bpy.data.cameras[name_]
        scene.frame_current=i

        l1=links.new(d.outputs['Image'], v.inputs[0])
        if( (con and not os.path.isfile(path_rgb+".png")) or not con ):
            render.image_settings.file_format='PNG'
            render.image_settings.color_mode='RGB'
            render.image_settings.color_depth='16'
            scene.view_settings.view_transform = 'Standard'
            render.engine=engine
            render.filepath = os.path.join(scene_path_dtam,name_rgb )
            bpy.ops.render.render(write_still = True)

        links.remove(l1)
        l2=links.new(mp.outputs[0], v.inputs[0])
        if( (con and not os.path.isfile(path_depth+".exr")) or not con ):
            render.image_settings.file_format='OPEN_EXR'
            render.image_settings.color_mode='BW'
            render.image_settings.color_depth='32'

            scene.view_settings.view_transform = 'Raw'
            render.engine=engine_eevee
            render.filepath = os.path.join(scene_path_dtam,name_depth )
            bpy.ops.render.render(write_still = True)

        pi=math.pi

        eul_ang_=obj_.rotation_euler
        ex_=eul_ang_.x
        ey_=eul_ang_.y
        ez_=eul_ang_.z

        Rx_ = np.matrix([[1, 0, 0],[0, math.cos(ex_), -math.sin(ex_)],[0, math.sin(ex_), math.cos(ex_)]])
        Ry_ = np.matrix([[math.cos(ey_), 0, math.sin(ey_)],[0, 1, 0],[-math.sin(ey_), 0, math.cos(ey_)]])
        Rz_ = np.matrix([[math.cos(ez_), -math.sin(ez_), 0],[math.sin(ez_), math.cos(ez_), 0],[0, 0, 1]])

        # here euler angles are applyied in zyx order
        Rzy_=np.dot(Rz_,Ry_)
        R_=np.dot(Rzy_,Rx_)
        l_=obj_.location

        frame_=[ R_.item(0), R_.item(1), R_.item(2),
                R_.item(3), R_.item(4), R_.item(5),
                R_.item(6), R_.item(7), R_.item(8),
                l_[0], l_[1], l_[2] ]

        resolution_x=render.resolution_x
        resolution_y=render.resolution_y
        aspect=resolution_x/resolution_y
        lens=bpy.data.cameras[name_].lens/1000
        min_depth=bpy.data.cameras[name_].clip_start
        max_depth=bpy.data.cameras[name_].clip_end
        width=bpy.data.cameras[name_].sensor_width/1000

        data_['cameras'][name_]={}
        data_['cameras'][name_]['aspect']=aspect
        data_['cameras'][name_]['width']=width
        data_['cameras'][name_]['resolution']=resolution_x
        data_['cameras'][name_]['frame']=frame_
        data_['cameras'][name_]['lens']=lens
        data_['cameras'][name_]['max_depth']=max_depth
        data_['cameras'][name_]['min_depth']=min_depth
        data_['cameras'][name_]['lens']=lens

        with open(json_path, 'w') as outfile_:
            json.dump(data_, outfile_)

        i=i+1


import requests
from urllib.parse import urlencode
import pandas as pd
import random
import time
import json
import os
import csv
from lxml import etree
import re

class Lagou_Position(object):

    def __init__(self):
        self.User_Agent = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
        ]
        self.headers = {
            "Host":"www.lagou.com",
            "Referer": "https://www.lagou.com/jobs/list_%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8/p-city_2?px=default",
            "User_Agent": random.choice(self.User_Agent),
            "X-Requested-With": "XMLHttpRequest"
        }
        self.headers1 = {
            "Host": "www.lagou.com",
            "Referer": "https://www.lagou.com/jobs/list_%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8/p-city_2?px=default",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": random.choice(self.User_Agent)
        }
        self.First_url = "https://www.lagou.com/jobs/list_%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8/p-city_2?px=default"
        #搜索网络安全
        self.Target_url = "https://www.lagou.com/jobs/positionAjax.json?px=default&city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false"
        #网络安全页下ajax页面

    #请求原始链接获得cookie
    def Get_First_Url(self):
        rs = requests.session()
        rs.get(self.First_url, headers = self.headers, timeout=3)
        cookies = rs.cookies
        print(cookies)
        return cookies

    #构造请求Ajax的数据包
    def Post_Target_Url(self):
        cookie = self.Get_First_Url()
        return_cookie = requests.utils.dict_from_cookiejar(cookie)
        cookie.update(return_cookie)
        pn = 1
        for pn in range(30):
            params = {
                "first":"false",
                "pn":pn,
                "kd":"网络安全"
            }
            pn += 1
            response = requests.post(self.Target_url,data=params, cookies = cookie, headers = self.headers, timeout=3)
            print(response.text)
            self.Analysis(response)
            time.sleep(60)

    #解析Ajax返回请求内职位信息
    def Analysis(self,response):
        items = []
        data = json.loads(response.text)["content"]["positionResult"]["result"]
        if len(data):
            for i in range(len(data)):
                positionID = data[i]["positionId"]
                positionName = data[i]["positionName"]
                education = data[i]['education']
                companyShortName = data[i]["companyShortName"]
                workYear = data[i]["workYear"]
                salary = data[i]["salary"] + "*" + data[i]["salaryMonth"]
        self.Save_ajax_data(items)
        time.sleep(1.3)

    # 保存在ajax里收集到的职位和条目信息
    def Save_ajax_data(self, items):
        file_size = os.path.getsize(r'C:\Users\Administrator\PycharmProjects\pythonlearn1\Strain\Lagou_Spider\analyst.csv')
        if file_size == 0:
            name = ["ID","职位名称","学历要求","公司名称","工作年限","薪水待遇"]
            file_test = pd.DataFrame(columns=name, data=items)
            file_test.to_csv(r"analyst.csv", encoding="gbk", index=False)
        else:
            with open(r"analyst.csv", "a+", newline="") as file_test:
                writer = csv.writer(file_test)
                writer.writerows(items)

    #请求职位详情页
    def Get_Url(self):
        urls = []
        with open("analyst.csv","r",newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                if row[0] != "ID":
                    url = "https://www.lagou.com/jobs/{}.html".format(row[0])
                    urls.append(url)
        return  urls

    #对职位详情页的内容进行解析
    def Get_Detail(self):
        urls = self.Get_Url()
        length = len(urls)
        for url in urls:
            description = ""
            print(url)
            rs = requests.get(url, headers = self.headers1)
            rs.encoding = "utf-8"
            time.sleep(5)
            content = etree.HTML(rs.text)
            detail = content.xpath('//*[@id="job_detail"]/dd[2]/div/p/text()')
            print(detail)

            for i in range(1, len(detail)):

                if '要求' in detail[i - 1]:
                    for j in range(i, len(detail)):
                        detail[j] = detail[j].replace('\xa0', '')
                        detail[j] = re.sub('[、;；.0-9。]', '', detail[j])
                        description = description + detail[j] + '/'
                    print(description)
            self.Save_Position_Detail(description)
            length -= 1
            time.sleep(3)
    #保存职位详情页的信息
    def Save_Position_Detail(self,description):
        with open("description.txt", "a+", encoding="utf-8") as file:
            file.write(description)

spider = Lagou_Position()
spider.Post_Target_Url()
spider.Get_Detail()


import calendar

# Get user input for year and month
year = int(input("Enter the year: "))
month = int(input("Enter the month (1-12): "))

# Create a calendar object
cal = calendar.monthcalendar(year, month)

# Print the calendar header
print(calendar.month_name[month] + " " + str(year))
print("Mo Tu We Th Fr Sa Su")

# Print the calendar body
for week in cal:
    for day in week:
        if day == 0:
            print("  ", end="")
        else:
            print("{0:2d}".format(day), end=" ")
    print()


# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: 性能工具
"""

# python -m cProfile  profile_demo.py

def is_prime(num):
    for factor in range(2, int(num ** 0.5) + 1):
        if num % factor == 0:
            return False
    return True

class PrimeIter:
    def __init__(self, total):
        self.counter = 0
        self.current = 1
        self.total = total

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter < self.total:
            self.current += 1
            while not is_prime(self.current):
                self.current += 1
            self.counter += 1
            return self.current
        raise StopIteration()

if __name__ == '__main__':
    list(PrimeIter(10000))


"""
- 使用生成器函数得到生成器对象， 并反复的调用对象next() 方法实现数据的生成
- 函数中的yeild关键字的作用就是直接生成一个迭代器， 之后这个迭代器会调用next()
- 直到抛出stopIteration
- 使用生成器的好处
    - 数据是按需生成的，不用一次性在内存中创建大量空间
- 例子：
    - 生成300w个4位随机的验证码
"""
import random

def verify_code(num: int = 3000000, is_test: bool = False):
    assert isinstance(num, int), 'the type of num must be int...'
    if is_test:
        print(f'gengerate codes at once ...')
        code = [random.randint(1000, 9999) for _ in range(num)]
        idx = random.randint(0, num - 1)
        return code[idx]
    else:
        count = 0
        while count < num:
            code = random.randint(1000, 9999)
            yield code
            count += 1

if __name__ == "__main__":
    # print(verify_code(10).__next__())
    g = verify_code(10)
    # __iter__  __next__ 这些方法在生成器对象g中
    attr = dir(g)
    print(attr)
    for i in g:
        print(i)


class Solution:
    def longestPalindrome(self, s):
        dp = [[False for _ in range(len(s))] for _ in range(len(s))]
        # dp[i][j] s[i][j]
        rst = [0, 0, 0]
        #0: length 1: start 2: end

        # set length = 1 to true
        for i in range(len(s)):
            dp[i][i] = True

        # set length = 2, baseline
        for i in range(len(s) - 1):
            if s[i] == s[i+1]:
                dp[i][i+1] = True
                if 2 > rst[0] and dp[i][i+1]:
                    rst = [2, i, i+1]

        # start iteration
        # dp[i][j] = True if dp[i+1][j-1] == True
        for length in range(2, len(s)):
            for i in range(len(s) - length):
                if s[i] == s[i+length]:
                    dp[i][i+length] = dp[i+1][i+length-1]
                    if length + 1 > rst[0] and dp[i][i+length]:
                        rst = [length+1, i, i+length]
        return s[rst[1]:rst[2]+1]

print(Solution().longestPalindrome("aab"))


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

from openerp import models, fields, api
import logging

_logger = logging.getLogger(__name__)

class certifications_certification_task(models.Model):
	_name = 'certifications.certification.task'

	name = fields.Char(required=True)
	description = fields.Text(required=True)
	certification = fields.Many2one('certifications.certification',required=True)

	color = fields.Integer('Color Index')

	fechaFin = fields.Datetime()

	operadora_id = fields.Char("Operadora", help="La operadora a la que pertenece esta tarea", related='certification.operadora_id.name')

	stage = fields.Many2one('certifications.certification.task.stage','Etapa', required=True, copy=False)

	def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
		if context is None:
			context = {}
		stage_obj = self.pool.get('certifications.certification.task.stage')
		order = stage_obj._order
#		access_rights_uid = access_rights_uid or uid
		if read_group_order == 'stage_id desc':
			order = '%s desc' % order
		search_domain = []
		stage_ids = stage_obj._search(cr, None, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
		result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
		# restore order of the search
		result.sort(lambda x, y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))

		fold = {}
		for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
			fold[stage.id] = stage.fold or False
		return result, fold

	_group_by_full = {
		'stage': _read_group_stage_ids,
	}


import asyncio
import datetime
import logging
import time
import unittest
from io import StringIO
import sys
from os.path import dirname, abspath, join
from unittest.mock import patch, MagicMock

from flask import Flask
from flask.ctx import AppContext
from flask.testing import FlaskClient

path = join(join(dirname(__file__), ".."), "")
path = abspath(path)
if path not in sys.path:
    sys.path.insert(0, path)

from src.phanos import phanos_profiler, publisher
from src.phanos.publisher import (
    StreamHandler,
    ImpProfHandler,
    LoggerHandler,
    BaseHandler,
)
from src.phanos.tree import MethodTreeNode
from test import testing_data, dummy_api
from test.dummy_api import app, dummy_method, DummyDbAccess
from src.phanos.metrics import (
    Histogram,
    Summary,
    Counter,
    Info,
    Gauge,
    Enum,
    TimeProfiler,
)

class TestTree(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        phanos_profiler.config(job="TEST")

    def tearDown(self) -> None:
        pass

    def test_tree(self):
        root = MethodTreeNode()
        # classmethod
        first = MethodTreeNode(dummy_api.DummyDbAccess.test_class)
        root.add_child(first)
        self.assertEqual(first.parent, root)
        self.assertEqual(root.children, [first])
        self.assertEqual(first.context, "DummyDbAccess:test_class")
        root.delete_child()
        self.assertEqual(root.children, [])
        self.assertEqual(first.parent, None)
        # method
        first = MethodTreeNode(dummy_api.DummyDbAccess.test_method)
        root.add_child(first)
        self.assertEqual(first.context, "DummyDbAccess:test_method")
        root.delete_child()
        # function
        first = MethodTreeNode(dummy_method)
        root.add_child(first)
        self.assertEqual(first.context, "dummy_api:dummy_method")
        root.delete_child()
        # descriptor
        access = DummyDbAccess()
        first = MethodTreeNode(access.__getattribute__)
        root.add_child(first)
        self.assertEqual(first.context, "object:__getattribute__")
        root.delete_child()
        # staticmethod
        first = MethodTreeNode(access.test_static)
        root.add_child(first)
        self.assertEqual(first.context, "DummyDbAccess:test_static")
        root.delete_child()

        first = MethodTreeNode(self.tearDown)
        root.add_child(first)
        self.assertEqual(first.context, "TestTree:tearDown")

    def test_clear_tree(self):
        root = phanos_profiler._root
        _1 = MethodTreeNode(self.tearDown)
        root.add_child(_1)
        self.assertEqual(_1.context, "TestTree:tearDown")
        _1.add_child(MethodTreeNode(self.tearDown))
        _1.add_child(MethodTreeNode(self.tearDown))
        _1.add_child(MethodTreeNode(self.tearDown))
        with patch.object(MethodTreeNode, "clear_children") as mock:
            phanos_profiler.clear()

        mock.assert_any_call()
        self.assertEqual(mock.call_count, 5)

        phanos_profiler.clear()
        # no children exist but error should not be raised
        phanos_profiler._root.delete_child()

    def test_methods_between(self):
        output = StringIO()
        str_handler = StreamHandler("str_handler", output)
        phanos_profiler.add_handler(str_handler)
        dummy_api.test_list_comp()
        dummy_api.DummyResource().get_()
        output.seek(0)
        methods = []
        for line in output.readlines():
            methods.append(line.split(", ")[1][8:])
        phanos_profiler.delete_handlers()
        self.assertEqual([methods[0], methods[3]], testing_data.methods_between_out)

class TestHandlers(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        phanos_profiler.config(job="TEST")

    def tearDown(self) -> None:
        phanos_profiler.delete_handlers()

    def test_stream_handler(self):
        # base handler test
        base = BaseHandler("test_handler")
        self.assertRaises(NotImplementedError, base.handle, "test_profiler", {})
        # stream handler
        output = StringIO()
        str_handler = StreamHandler("str_handler", output)
        str_handler.handle(testing_data.test_handler_in, "test_name")
        str_handler.handle(testing_data.test_handler_in_no_lbl, "test_name")
        output.seek(0)
        self.assertEqual(
            output.read(),
            testing_data.test_handler_out + testing_data.test_handler_out_no_lbl,
        )

    def test_log_handler(self):
        tmp = sys.stdout
        output = StringIO()
        sys.stdout = output
        logger = logging.getLogger()
        logger.setLevel(10)
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(10)
        logger.addHandler(handler)
        log_handler = LoggerHandler("log_handler", logger)
        log_handler.handle(testing_data.test_handler_in, "test_name")
        output.seek(0)
        result = output.read()
        self.assertEqual(result, testing_data.test_handler_out)
        log_handler = LoggerHandler("log_handler1")
        self.assertEqual(log_handler.logger.name, "PHANOS")
        output.seek(0)
        result = output.read()
        self.assertEqual(result, testing_data.test_handler_out)
        sys.stdout = tmp

    def test_handlers_management(self):
        length = len(phanos_profiler.handlers)
        log1 = LoggerHandler("log_handler1")
        phanos_profiler.add_handler(log1)
        log2 = LoggerHandler("log_handler2")
        phanos_profiler.add_handler(log2)
        self.assertEqual(len(phanos_profiler.handlers), length + 2)
        phanos_profiler.delete_handler("log_handler1")
        self.assertEqual(phanos_profiler.handlers.get("log_handler1"), None)
        phanos_profiler.delete_handlers()
        self.assertEqual(phanos_profiler.handlers, {})

        self.assertRaises(KeyError, phanos_profiler.delete_handler, "nonexistent")

        handler1 = StreamHandler("handler")
        handler2 = StreamHandler("handler")
        phanos_profiler.add_handler(handler1)
        self.assertEqual(handler1, phanos_profiler.handlers["handler"])
        phanos_profiler.add_handler(handler2)
        self.assertEqual(handler2, phanos_profiler.handlers["handler"])

    def test_rabbit_handler_connection(self):
        self.assertRaises(RuntimeError, ImpProfHandler, "handle")

    def test_rabbit_handler_publish(self):
        handler = None
        with patch("src.phanos.publisher.BlockingPublisher") as test_publisher:
            handler = ImpProfHandler("rabbit")
            test_publisher.assert_called()
            # noinspection PyDunderSlots,PyUnresolvedReferences
            test_publish = handler.publisher.publish = MagicMock(return_value=3)

            handler.handle(profiler_name="name", records=testing_data.test_handler_in)
            test_publish.assert_called()

class TestMetrics(unittest.TestCase):
    app: Flask
    client: FlaskClient
    context: AppContext

    @classmethod
    def setUpClass(cls) -> None:
        cls.app = app

    def test_histogram(self):
        with app.test_request_context():
            hist_no_lbl = Histogram(
                "hist_no_lbl",
                "V",
                "TEST",
            )
            # invalid label
            self.assertRaises(
                ValueError,
                hist_no_lbl.store_operation,
                "test:method",
                "observe",
                2.0,
                label_values={"nonexistent": "123"},
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                hist_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                2.0,
            )
            # invalid value
            self.assertRaises(
                TypeError,
                hist_no_lbl.store_operation,
                "test:method",
                "observe",
                "asd",
            )
            hist_no_lbl.cleanup()
            # valid operation
            hist_no_lbl.store_operation("test:method", operation="observe", value=2.0),
            self.assertEqual(hist_no_lbl.to_records(), testing_data.hist_no_lbl)

            hist_w_lbl = Histogram("hist_w_lbl", "V", "TEST", labels=["test"])

            # missing label
            self.assertRaises(
                ValueError,
                hist_w_lbl.store_operation,
                "test:method",
                "observe",
                2.0,
            )
            hist_w_lbl.cleanup()
            # default operation
            hist_w_lbl.store_operation(method="test:method", value=2.0, label_values={"test": "test"})
            self.assertEqual(hist_w_lbl.to_records(), testing_data.hist_w_lbl)

    def test_summary(self):
        with app.test_request_context():
            sum_no_lbl = Summary("sum_no_lbl", "V", job="TEST")
            # invalid label
            self.assertRaises(
                ValueError,
                sum_no_lbl.store_operation,
                "test:method",
                "observe",
                2.0,
                label_values={"nonexistent": "123"},
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                sum_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                2.0,
            )
            # invalid value
            self.assertRaises(
                TypeError,
                sum_no_lbl.store_operation,
                "test:method",
                "observe",
                "asd",
            )
            sum_no_lbl.cleanup()
            # valid operation
            sum_no_lbl.store_operation("test:method", operation="observe", value=2.0),
            self.assertEqual(sum_no_lbl.to_records(), testing_data.sum_no_lbl)

    def test_counter(self):
        with app.test_request_context():
            cnt_no_lbl = Counter(
                "cnt_no_lbl",
                "V",
                "TEST",
            )
            # invalid label
            self.assertRaises(
                ValueError,
                cnt_no_lbl.store_operation,
                "test:method",
                "inc",
                2.0,
                label_values={"nonexistent": "123"},
            )
            # invalid value type
            self.assertRaises(
                TypeError,
                cnt_no_lbl.store_operation,
                "test:method",
                "inc",
                "asd",
            )
            # invalid value
            self.assertRaises(
                TypeError,
                cnt_no_lbl.store_operation,
                "test:method",
                "inc",
                -1,
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                cnt_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                2.0,
            )
            cnt_no_lbl.cleanup()

            # valid operation
            cnt_no_lbl.store_operation("test:method", operation="inc", value=2.0),
            self.assertEqual(cnt_no_lbl.to_records(), testing_data.cnt_no_lbl)

    def test_info(self):
        with app.test_request_context():
            inf_no_lbl = Info(
                "inf_no_lbl",
                job="TEST",
            )
            # invalid value type
            self.assertRaises(
                ValueError,
                inf_no_lbl.store_operation,
                "test:method",
                "info",
                "asd",
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                inf_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                2.0,
            )
            inf_no_lbl.cleanup()
            # valid operation
            inf_no_lbl.store_operation("test:method", operation="info", value={"value": "asd"}),
            self.assertEqual(inf_no_lbl.to_records(), testing_data.inf_no_lbl)

    def test_gauge(self):
        with app.test_request_context():
            gauge_no_lbl = Gauge(
                "gauge_no_lbl",
                "V",
                "TEST",
            )
            # invalid label
            self.assertRaises(
                ValueError,
                gauge_no_lbl.store_operation,
                "test:method",
                "inc",
                2.0,
                label_values={"nonexistent": "123"},
            )
            # invalid value type
            self.assertRaises(
                TypeError,
                gauge_no_lbl.store_operation,
                "test:method",
                "inc",
                "asd",
            )
            # invalid value
            self.assertRaises(
                TypeError,
                gauge_no_lbl.store_operation,
                "test:method",
                "inc",
                -1,
            )
            # invalid value
            self.assertRaises(
                TypeError,
                gauge_no_lbl.store_operation,
                "test:method",
                "dec",
                -1,
            )
            # invalid value
            self.assertRaises(
                TypeError,
                gauge_no_lbl.store_operation,
                "test:method",
                "set",
                False,
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                gauge_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                2.0,
            )
            gauge_no_lbl.cleanup()
            # valid operation
            gauge_no_lbl.store_operation("test:method", operation="inc", value=2.0),
            gauge_no_lbl.store_operation("test:method", operation="dec", value=2.0),
            gauge_no_lbl.store_operation("test:method", operation="set", value=2.0),
            self.assertEqual(gauge_no_lbl.to_records(), testing_data.gauge_no_lbl)

    def test_enum(self):
        with app.test_request_context():
            enum_no_lbl = Enum(
                "enum_no_lbl",
                ["true", "false"],
                job="TEST",
            )
            # invalid value
            self.assertRaises(
                ValueError,
                enum_no_lbl.store_operation,
                "test:method",
                "state",
                "maybe",
            )
            # invalid operation
            self.assertRaises(
                ValueError,
                enum_no_lbl.store_operation,
                "test:method",
                "nonexistent",
                "true",
            )
            enum_no_lbl.cleanup()
            # valid operation
            enum_no_lbl.store_operation("test:method", operation="state", value="true")
            self.assertEqual(enum_no_lbl.to_records(), testing_data.enum_no_lbl)

            enum_no_lbl.store_operation("test:method", operation="state", value="true")
            enum_no_lbl._values.pop(0)
            self.assertRaises(RuntimeError, enum_no_lbl.to_records)

    def test_builtin_profilers(self):
        time_profiler = TimeProfiler("test_time_prof", "TEST")

        time_profiler.start()
        time_profiler.start()
        self.assertEqual(len(time_profiler._start_ts), 2)
        time.sleep(0.2)
        time_profiler.store_operation("test:method", operation="stop")
        self.assertEqual(len(time_profiler._start_ts), 1)
        time.sleep(0.2)
        time_profiler.store_operation("test:method", operation="stop")
        self.assertEqual(len(time_profiler._start_ts), 0)
        self.assertEqual(time_profiler._values[0][1] // 100, 2)
        self.assertEqual(time_profiler._values[1][1] // 100, 4)

        self.assertRaises(RuntimeError, time_profiler.store_operation, "test:method", "stop")

class TestProfiling(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        phanos_profiler.config(job="TEST")
        cls.app = app
        cls.client = cls.app.test_client()  # type: ignore[attr-defined]

    def setUp(self) -> None:
        phanos_profiler.create_time_profiler()
        phanos_profiler.create_response_size_profiler()
        self.output = StringIO()
        profile_handler = StreamHandler("name", self.output)
        phanos_profiler.add_handler(profile_handler)

    def tearDown(self) -> None:
        phanos_profiler.delete_handlers()
        phanos_profiler.delete_metrics(True, True)
        phanos_profiler.before_root_func = None
        phanos_profiler.after_root_func = None
        phanos_profiler.before_func = None
        phanos_profiler.after_func = None
        self.output.close()

    def test_metric_management(self):
        length = len(phanos_profiler.metrics)
        # create metrics
        hist = Histogram("name", "TEST", "units")
        phanos_profiler.add_metric(hist)
        hist1 = Histogram("name1", "TEST", "units")
        phanos_profiler.add_metric(hist1)
        self.assertEqual(len(phanos_profiler.metrics), length + 2)
        # delete metric
        phanos_profiler.delete_metric("name")
        self.assertEqual(len(phanos_profiler.metrics), length + 1)
        self.assertEqual(phanos_profiler.metrics.get("name"), None)
        # delete time_profiling metric
        phanos_profiler.delete_metric(publisher.TIME_PROFILER)
        self.assertEqual(phanos_profiler.metrics.get(publisher.TIME_PROFILER), None)
        self.assertEqual(phanos_profiler.time_profile, None)
        # delete response size metric
        phanos_profiler.delete_metric(publisher.RESPONSE_SIZE)
        self.assertEqual(phanos_profiler.metrics.get(publisher.RESPONSE_SIZE), None)
        self.assertEqual(phanos_profiler.resp_size_profile, None)
        # create response size metric
        phanos_profiler.create_response_size_profiler()
        self.assertIsNotNone(phanos_profiler.resp_size_profile)
        self.assertEqual(len(phanos_profiler.metrics), 2)

        # delete all metrics (without response size and time profiling metrics)
        phanos_profiler.delete_metrics()
        self.assertEqual(len(phanos_profiler.metrics), 1)
        self.assertIsNotNone(phanos_profiler.resp_size_profile, None)
        self.assertIsNotNone(phanos_profiler.metrics.get(publisher.RESPONSE_SIZE))
        phanos_profiler.delete_metrics(rm_time_profile=True, rm_resp_size_profile=True)
        self.assertEqual(phanos_profiler.metrics, {})
        self.assertEqual(phanos_profiler.metrics.get(publisher.RESPONSE_SIZE), None)

        self.assertRaises(KeyError, phanos_profiler.delete_metric, "nonexistent")

        metric1 = Histogram("hist", "TEST", "xz")
        metric2 = Histogram("hist", "TEST", "xz")
        phanos_profiler.add_metric(metric1)
        self.assertEqual(metric1, phanos_profiler.metrics["hist"])
        phanos_profiler.add_metric(metric2)
        self.assertEqual(metric2, phanos_profiler.metrics["hist"])

    def test_profiling(self):
        # do not handle records
        phanos_profiler.handle_records = False
        _ = self.client.get("http://localhost/api/dummy/one")
        self.output.seek(0)
        lines = self.output.readlines()
        self.assertEqual(lines, [])

        # test of api call inside same api call with error risen
        phanos_profiler.handle_records = True
        _ = self.client.post("http://localhost/api/dummy/one")
        self.output.seek(0)
        self.assertEqual(self.output.readlines(), [])
        # cleanup assertion
        for metric in phanos_profiler.metrics.values():
            self.assertEqual(metric._values, [])
            self.assertEqual(metric._label_values, [])
            self.assertEqual(metric.method, [])
            self.assertEqual(metric.item, [])
        # error_occurred will be set to false before root function of next profiling
        self.assertEqual(phanos_profiler.error_occurred, True)
        self.assertEqual(phanos_profiler.current_node, phanos_profiler._root)

        # profiling after request, where error_occurred
        _ = self.client.get("http://localhost/api/dummy/one")
        self.assertEqual(phanos_profiler.error_occurred, False)
        self.output.seek(0)
        lines = self.output.readlines()
        time_lines = lines[:-1]
        size_line = lines[-1]
        for i in range(len(time_lines)):
            line = time_lines[i][:-1]
            value = line.split("value: ")[1][:-3]
            self.assertEqual(
                (float(value)) // 100,
                testing_data.profiling_out[i]["value"],
            )
            method = line.split(", ")[1][8:]
            self.assertEqual(
                method,
                testing_data.profiling_out[i]["method"],
            )

        size_line = size_line[:-1]
        value = size_line.split("value: ")[1][:-2]
        self.assertEqual(
            (float(value)),
            testing_data.profiling_out[-1]["value"],
        )
        method = size_line.split(", ")[1][8:]
        self.assertEqual(
            method,
            testing_data.profiling_out[-1]["method"],
        )

        self.assertEqual(phanos_profiler.current_node, phanos_profiler._root)
        self.assertEqual(phanos_profiler._root.children, [])

        access = dummy_api.DummyDbAccess()
        self.output.truncate(0)
        self.output.seek(0)
        self.assertRaises(RuntimeError, access.raise_access)
        self.output.seek(0)
        # len 1 cuz DummyDbAccess.first_access finished, but then raise error so raise_access wasn't measured
        self.assertEqual(len(self.output.readlines()), 1)

        # cleanup assertion
        for metric in phanos_profiler.metrics.values():
            self.assertEqual(metric._values, [])
            self.assertEqual(metric._label_values, [])
            self.assertEqual(metric.method, [])
            self.assertEqual(metric.item, [])

    def test_custom_profile_addition(self):
        hist = Histogram("test_name", "TEST", "test_units", ["place"])
        self.assertEqual(len(phanos_profiler.metrics), 2)
        phanos_profiler.add_metric(hist)
        self.assertEqual(len(phanos_profiler.metrics), 3)
        phanos_profiler.delete_metric(publisher.TIME_PROFILER)
        phanos_profiler.delete_metric(publisher.RESPONSE_SIZE)

        def before_root_func(func, args, kwargs):
            print(func)
            print(args)
            print(kwargs)
            hist.store_operation(
                method=phanos_profiler.current_node.context,
                operation="observe",
                value=1.0,
                label_values={"place": "before_root"},
            )

        phanos_profiler.before_root_func = before_root_func

        def before_func(func, args, kwargs):
            _ = args
            _ = kwargs
            _ = func
            hist.store_operation(
                method=phanos_profiler.current_node.context,
                operation="observe",
                value=2.0,
                label_values={"place": "before_func"},
            )

        phanos_profiler.before_func = before_func

        def after_func(fn_result, args, kwargs):
            _ = args
            _ = kwargs
            _ = fn_result
            hist.store_operation(
                method=phanos_profiler.current_node.context,
                operation="observe",
                value=3.0,
                label_values={"place": "after_func"},
            )

        phanos_profiler.after_func = after_func

        def after_root_func(fn_result, args, kwargs):
            _ = args
            _ = kwargs
            _ = fn_result
            hist.store_operation(
                method=phanos_profiler.current_node.context,
                operation="observe",
                value=4.0,
                label_values={"place": "after_root"},
            )

        phanos_profiler.after_root_func = after_root_func

        dummy_access = DummyDbAccess()
        _ = dummy_access.second_access()
        self.output.seek(0)
        logs = self.output.readlines()
        for i in range(len(logs)):
            line = logs[i].split(", ")
            method = line[1][8:]
            value = line[2][7:10]
            place = line[3][14:-1]
            self.assertEqual(method, testing_data.custom_profile_out[i]["method"])
            self.assertEqual(float(value), testing_data.custom_profile_out[i]["value"])
            self.assertEqual(place, testing_data.custom_profile_out[i]["place"])

class TestAsync(unittest.IsolatedAsyncioTestCase):
    @classmethod
    def setUpClass(cls) -> None:
        phanos_profiler.config(job="TEST", request_size_profile=False)
        cls.app = app
        cls.client = cls.app.test_client()  # type: ignore[attr-defined]

    def setUp(self) -> None:
        self.output = StringIO()
        profile_handler = StreamHandler("name", self.output)
        phanos_profiler.add_handler(profile_handler)

    def tearDown(self) -> None:
        phanos_profiler.delete_handlers()
        phanos_profiler.delete_metrics(True, True)
        self.output.close()

    async def test_profiling(self):
        async_access = dummy_api.AsyncTest()
        loop = asyncio.get_event_loop()
        task_long = loop.create_task(async_access.async_access_long())
        task_short = loop.create_task(async_access.async_access_short())
        start = datetime.datetime.now()
        await asyncio.wait([task_long, task_short])
        stop = datetime.datetime.now() - start
        # total time of execution is 0.2 (long_task)
        self.assertEqual(round(stop.total_seconds(), 1), 0.2)
        self.output.seek(0)
        output = []
        for line in self.output.readlines():
            output.append(float(line.split("value: ")[1][:-4]) // 100)
        # [short_task, long_task] execution time from phanos profiler
        self.assertEqual(output, [1.0, 2.0])


from __future__ import print_function

import getopt
import glob
import os
import re
import string
import sys
import xml

from xml.dom.minidom import parse

try:
  _basestr = basestring
except NameError:
  _basestr = str

# Dictionary of subtitution args
substitution_args_context = {}

class XacroException(Exception):
  pass

def isnumber(x):
  return hasattr(x, '__int__')

# Better pretty printing of xml
# Taken from http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/
def fixed_writexml(self, writer, indent="", addindent="", newl=""):
  # indent = current indentation
  # addindent = indentation to add to higher levels
  # newl = newline string
  writer.write(indent + "<" + self.tagName)

  attrs = self._get_attributes()
  a_names = list(attrs.keys())
  a_names.sort()

  for a_name in a_names:
    writer.write(" %s=\"" % a_name)
    xml.dom.minidom._write_data(writer, attrs[a_name].value)
    writer.write("\"")
  if self.childNodes:
    if len(self.childNodes) == 1 \
       and self.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE:
      writer.write(">")
      self.childNodes[0].writexml(writer, "", "", "")
      writer.write("</%s>%s" % (self.tagName, newl))
      return
    writer.write(">%s" % (newl))
    for node in self.childNodes:
      # skip whitespace-only text nodes
      if node.nodeType == xml.dom.minidom.Node.TEXT_NODE and \
         not node.data.strip():
        continue
      node.writexml(writer, indent + addindent, addindent, newl)
    writer.write("%s</%s>%s" % (indent, self.tagName, newl))
  else:
    writer.write("/>%s" % (newl))

# replace minidom's function with ours
xml.dom.minidom.Element.writexml = fixed_writexml

class Table:

  def __init__(self, parent=None):
    self.parent = parent
    self.table = {}

  def __getitem__(self, key):
    if key in self.table:
      return self.table[key]
    elif self.parent:
      return self.parent[key]
    else:
      raise KeyError(key)

  def __setitem__(self, key, value):
    self.table[key] = value

  def __contains__(self, key):
    return \
        key in self.table or \
        (self.parent and key in self.parent)

class QuickLexer(object):

  def __init__(self, **res):
    self.str = ""
    self.top = None
    self.res = []
    for k, v in res.items():
      self.__setattr__(k, len(self.res))
      self.res.append(v)

  def lex(self, str):
    self.str = str
    self.top = None
    self.next()

  def peek(self):
    return self.top

  def next(self):
    result = self.top
    self.top = None
    for i in range(len(self.res)):
      m = re.match(self.res[i], self.str)
      if m:
        self.top = (i, m.group(0))
        self.str = self.str[m.end():]
        break
    return result

def first_child_element(elt):
  c = elt.firstChild
  while c:
    if c.nodeType == xml.dom.Node.ELEMENT_NODE:
      return c
    c = c.nextSibling
  return None

def next_sibling_element(elt):
  c = elt.nextSibling
  while c:
    if c.nodeType == xml.dom.Node.ELEMENT_NODE:
      return c
    c = c.nextSibling
  return None

# Pre-order traversal of the elements
def next_element(elt):
  child = first_child_element(elt)
  if child:
    return child
  while elt and elt.nodeType == xml.dom.Node.ELEMENT_NODE:
    next = next_sibling_element(elt)
    if next:
      return next
    elt = elt.parentNode
  return None

# Pre-order traversal of all the nodes
def next_node(node):
  if node.firstChild:
    return node.firstChild
  while node:
    if node.nextSibling:
      return node.nextSibling
    node = node.parentNode
  return None

def child_nodes(elt):
  c = elt.firstChild
  while c:
    yield c
    c = c.nextSibling

all_includes = []

# Deprecated message for <include> tags that don't have <xacro:include> prepended:
deprecated_include_msg = """DEPRECATED IN HYDRO:
  The <include> tag should be prepended with 'xacro' if that is the intended use
  of it, such as <xacro:include ...>. Use the following script to fix incorrect
  xacro includes:
     sed -i 's/<include/<xacro:include/g' `find . -iname *.xacro`"""

include_no_matches_msg = """Include tag filename spec \"{}\" matched no files."""

## @throws XacroException if a parsing error occurs with an included document
def process_includes(doc, base_dir):
  namespaces = {}
  previous = doc.documentElement
  elt = next_element(previous)
  while elt:
    # Xacro should not use plain 'include' tags but only namespaced ones. Causes conflicts with
    # other XML elements including Gazebo's <gazebo> extensions
    is_include = False
    if elt.tagName == 'xacro:include' or elt.tagName == 'include':

      is_include = True
      # Temporary fix for ROS Hydro and the xacro include scope problem
      if elt.tagName == 'include':

        # check if there is any element within the <include> tag. mostly we are concerned
        # with Gazebo's <uri> element, but it could be anything. also, make sure the child
        # nodes aren't just a single Text node, which is still considered a deprecated
        # instance
        if elt.childNodes and not (len(elt.childNodes) == 1 and
                                   elt.childNodes[0].nodeType == elt.TEXT_NODE):
          # this is not intended to be a xacro element, so we can ignore it
          is_include = False
        else:
          # throw a deprecated warning
          print(deprecated_include_msg, file=sys.stderr)

    # Process current element depending on previous conditions
    if is_include:
      filename_spec = eval_text(elt.getAttribute('filename'), {})
      if not os.path.isabs(filename_spec):
        filename_spec = os.path.join(base_dir, filename_spec)

      if re.search('[*[?]+', filename_spec):
        # Globbing behaviour
        filenames = sorted(glob.glob(filename_spec))
        if len(filenames) == 0:
          print(include_no_matches_msg.format(filename_spec), file=sys.stderr)
      else:
        # Default behaviour
        filenames = [filename_spec]

      for filename in filenames:
        global all_includes
        all_includes.append(filename)
        try:
          with open(filename) as f:
            try:
              included = parse(f)
            except Exception as e:
              raise XacroException(
                  "included file \"%s\" generated an error during XML parsing: %s" %
                  (filename, str(e)))
        except IOError as e:
          raise XacroException("included file \"%s\" could not be opened: %s" % (filename, str(e)))

        # Replaces the include tag with the elements of the included file
        for c in child_nodes(included.documentElement):
          elt.parentNode.insertBefore(c.cloneNode(deep=True), elt)

        # Grabs all the declared namespaces of the included document
        for name, value in included.documentElement.attributes.items():
          if name.startswith('xmlns:'):
            namespaces[name] = value

      elt.parentNode.removeChild(elt)
      elt = None
    else:
      previous = elt

    elt = next_element(previous)

  # Makes sure the final document declares all the namespaces of the included documents.
  for k, v in namespaces.items():
    doc.documentElement.setAttribute(k, v)

# Returns a dictionary: { macro_name => macro_xml_block }
def grab_macros(doc):
  macros = {}

  previous = doc.documentElement
  elt = next_element(previous)
  while elt:
    if elt.tagName == 'macro' or elt.tagName == 'xacro:macro':
      name = elt.getAttribute('name')

      macros[name] = elt
      macros['xacro:' + name] = elt

      elt.parentNode.removeChild(elt)
      elt = None
    else:
      previous = elt

    elt = next_element(previous)
  return macros

# Returns a Table of the properties
def grab_properties(doc):
  table = Table()

  previous = doc.documentElement
  elt = next_element(previous)
  while elt:
    if elt.tagName == 'property' or elt.tagName == 'xacro:property':
      name = elt.getAttribute('name')
      value = None

      if elt.hasAttribute('value'):
        value = elt.getAttribute('value')
      else:
        name = '**' + name
        value = elt  # debug

      bad = string.whitespace + "${}"
      has_bad = False
      for b in bad:
        if b in name:
          has_bad = True
          break

      if has_bad:
        sys.stderr.write('Property names may not have whitespace, ' + '"{", "}", or "$" : "' +
                         name + '"')
      else:
        table[name] = value

      elt.parentNode.removeChild(elt)
      elt = None
    else:
      previous = elt

    elt = next_element(previous)
  return table

def eat_ignore(lex):
  while lex.peek() and lex.peek()[0] == lex.IGNORE:
    lex.next()

def eval_lit(lex, symbols):
  eat_ignore(lex)
  if lex.peek()[0] == lex.NUMBER:
    return float(lex.next()[1])
  if lex.peek()[0] == lex.SYMBOL:
    try:
      key = lex.next()[1]
      value = symbols[key]
    except KeyError as ex:
      raise XacroException("Property wasn't defined: %s" % str(ex))
    if not (isnumber(value) or isinstance(value, _basestr)):
      if value is None:
        raise XacroException("Property %s recursively used" % key)
      raise XacroException("WTF2")
    try:
      return int(value)
    except:
      try:
        return float(value)
      except:
        # prevent infinite recursion
        symbols[key] = None
        result = eval_text(value, symbols)
        # restore old entry
        symbols[key] = value
        return result
  raise XacroException("Bad literal")

def eval_factor(lex, symbols):
  eat_ignore(lex)

  neg = 1
  if lex.peek()[1] == '-':
    lex.next()
    neg = -1

  if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL]:
    return neg * eval_lit(lex, symbols)
  if lex.peek()[0] == lex.LPAREN:
    lex.next()
    eat_ignore(lex)
    result = eval_expr(lex, symbols)
    eat_ignore(lex)
    if lex.next()[0] != lex.RPAREN:
      raise XacroException("Unmatched left paren")
    eat_ignore(lex)
    return neg * result

  raise XacroException("Misplaced operator")

def eval_term(lex, symbols):
  eat_ignore(lex)

  result = 0
  if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL, lex.LPAREN] \
          or lex.peek()[1] == '-':
    result = eval_factor(lex, symbols)

  eat_ignore(lex)
  while lex.peek() and lex.peek()[1] in ['*', '/']:
    op = lex.next()[1]
    n = eval_factor(lex, symbols)

    if op == '*':
      result = float(result) * float(n)
    elif op == '/':
      result = float(result) / float(n)
    else:
      raise XacroException("WTF")
    eat_ignore(lex)
  return result

def eval_expr(lex, symbols):
  eat_ignore(lex)

  op = None
  if lex.peek()[0] == lex.OP:
    op = lex.next()[1]
    if not op in ['+', '-']:
      raise XacroException("Invalid operation. Must be '+' or '-'")

  result = eval_term(lex, symbols)
  if op == '-':
    result = -float(result)

  eat_ignore(lex)
  while lex.peek() and lex.peek()[1] in ['+', '-']:
    op = lex.next()[1]
    n = eval_term(lex, symbols)

    if op == '+':
      result = float(result) + float(n)
    if op == '-':
      result = float(result) - float(n)
    eat_ignore(lex)
  return result

def eval_text(text, symbols):

  def handle_expr(s):
    lex = QuickLexer(IGNORE=r"\s+",
                     NUMBER=r"(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?",
                     SYMBOL=r"[a-zA-Z_]\w*",
                     OP=r"[\+\-\*/^]",
                     LPAREN=r"\(",
                     RPAREN=r"\)")
    lex.lex(s)
    return eval_expr(lex, symbols)

  def handle_extension(s):
    return ("$(%s)" % s)

  results = []
  lex = QuickLexer(DOLLAR_DOLLAR_BRACE=r"\$\$+\{",
                   EXPR=r"\$\{[^\}]*\}",
                   EXTENSION=r"\$\([^\)]*\)",
                   TEXT=r"([^\$]|\$[^{(]|\$$)+")
  lex.lex(text)
  while lex.peek():
    if lex.peek()[0] == lex.EXPR:
      results.append(handle_expr(lex.next()[1][2:-1]))
    elif lex.peek()[0] == lex.EXTENSION:
      results.append(handle_extension(lex.next()[1][2:-1]))
    elif lex.peek()[0] == lex.TEXT:
      results.append(lex.next()[1])
    elif lex.peek()[0] == lex.DOLLAR_DOLLAR_BRACE:
      results.append(lex.next()[1][1:])
  return ''.join(map(str, results))

# Expands macros, replaces properties, and evaluates expressions
def eval_all(root, macros, symbols):
  # Evaluates the attributes for the root node
  for at in root.attributes.items():
    result = eval_text(at[1], symbols)
    root.setAttribute(at[0], result)

  previous = root
  node = next_node(previous)
  while node:
    if node.nodeType == xml.dom.Node.ELEMENT_NODE:
      if node.tagName in macros:
        body = macros[node.tagName].cloneNode(deep=True)
        params = body.getAttribute('params').split()

        # Parse default values for any parameters
        defaultmap = {}
        for param in params[:]:
          splitParam = param.split(':=')

          if len(splitParam) == 2:
            defaultmap[splitParam[0]] = splitParam[1]
            params.remove(param)
            params.append(splitParam[0])

          elif len(splitParam) != 1:
            raise XacroException("Invalid parameter definition")

        # Expands the macro
        scoped = Table(symbols)
        for name, value in node.attributes.items():
          if not name in params:
            raise XacroException("Invalid parameter \"%s\" while expanding macro \"%s\"" %
                                 (str(name), str(node.tagName)))
          params.remove(name)
          scoped[name] = eval_text(value, symbols)

        # Pulls out the block arguments, in order
        cloned = node.cloneNode(deep=True)
        eval_all(cloned, macros, symbols)
        block = cloned.firstChild
        for param in params[:]:
          if param[0] == '*':
            while block and block.nodeType != xml.dom.Node.ELEMENT_NODE:
              block = block.nextSibling
            if not block:
              raise XacroException("Not enough blocks while evaluating macro %s" %
                                   str(node.tagName))
            params.remove(param)
            scoped[param] = block
            block = block.nextSibling

        # Try to load defaults for any remaining non-block parameters
        for param in params[:]:
          if param[0] != '*' and param in defaultmap:
            scoped[param] = defaultmap[param]
            params.remove(param)

        if params:
          raise XacroException("Parameters [%s] were not set for macro %s" %
                               (",".join(params), str(node.tagName)))
        eval_all(body, macros, scoped)

        # Replaces the macro node with the expansion
        for e in list(child_nodes(body)):  # Ew
          node.parentNode.insertBefore(e, node)
        node.parentNode.removeChild(node)

        node = None
      elif node.tagName == 'arg' or node.tagName == 'xacro:arg':
        name = node.getAttribute('name')
        if not name:
          raise XacroException("Argument name missing")
        default = node.getAttribute('default')
        if default and name not in substitution_args_context['arg']:
          substitution_args_context['arg'][name] = default

        node.parentNode.removeChild(node)
        node = None

      elif node.tagName == 'insert_block' or node.tagName == 'xacro:insert_block':
        name = node.getAttribute('name')

        if ("**" + name) in symbols:
          # Multi-block
          block = symbols['**' + name]

          for e in list(child_nodes(block)):
            node.parentNode.insertBefore(e.cloneNode(deep=True), node)
          node.parentNode.removeChild(node)
        elif ("*" + name) in symbols:
          # Single block
          block = symbols['*' + name]

          node.parentNode.insertBefore(block.cloneNode(deep=True), node)
          node.parentNode.removeChild(node)
        else:
          raise XacroException("Block \"%s\" was never declared" % name)

        node = None
      elif node.tagName in ['if', 'xacro:if', 'unless', 'xacro:unless']:
        value = eval_text(node.getAttribute('value'), symbols)
        try:
          if value == 'true': keep = True
          elif value == 'false': keep = False
          else: keep = float(value)
        except ValueError:
          raise XacroException(
              "Xacro conditional evaluated to \"%s\". Acceptable evaluations are one of [\"1\",\"true\",\"0\",\"false\"]"
              % value)
        if node.tagName in ['unless', 'xacro:unless']: keep = not keep
        if keep:
          for e in list(child_nodes(node)):
            node.parentNode.insertBefore(e.cloneNode(deep=True), node)

        node.parentNode.removeChild(node)
      else:
        # Evals the attributes
        for at in node.attributes.items():
          result = eval_text(at[1], symbols)
          node.setAttribute(at[0], result)
        previous = node
    elif node.nodeType == xml.dom.Node.TEXT_NODE:
      node.data = eval_text(node.data, symbols)
      previous = node
    else:
      previous = node

    node = next_node(previous)
  return macros

# Expands everything except includes
def eval_self_contained(doc):
  macros = grab_macros(doc)
  symbols = grab_properties(doc)
  eval_all(doc.documentElement, macros, symbols)

def print_usage(exit_code=0):
  print("Usage: %s [-o <output>] <input>" % 'xacro.py')
  print("       %s --deps       Prints dependencies" % 'xacro.py')
  print("       %s --includes   Only evalutes includes" % 'xacro.py')
  sys.exit(exit_code)

def set_substitution_args_context(context={}):
  substitution_args_context['arg'] = context

def open_output(output_filename):
  if output_filename is None:
    return sys.stdout
  else:
    return open(output_filename, 'w')

def main():
  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "ho:", ['deps', 'includes'])
  except getopt.GetoptError as err:
    print(str(err))
    print_usage(2)

  just_deps = False
  just_includes = False

  output_filename = None
  for o, a in opts:
    if o == '-h':
      print_usage(0)
    elif o == '-o':
      output_filename = a
    elif o == '--deps':
      just_deps = True
    elif o == '--includes':
      just_includes = True

  if len(args) < 1:
    print("No input given")
    print_usage(2)

  # Process substitution args
  # set_substitution_args_context(load_mappings(sys.argv))
  set_substitution_args_context((sys.argv))

  f = open(args[0])
  doc = None
  try:
    doc = parse(f)
  except xml.parsers.expat.ExpatError:
    sys.stderr.write("Expat parsing error.  Check that:\n")
    sys.stderr.write(" - Your XML is correctly formed\n")
    sys.stderr.write(" - You have the xacro xmlns declaration: " +
                     "xmlns:xacro=\"http://www.ros.org/wiki/xacro\"\n")
    sys.stderr.write("\n")
    raise
  finally:
    f.close()

  process_includes(doc, os.path.dirname(args[0]))
  if just_deps:
    for inc in all_includes:
      sys.stdout.write(inc + " ")
    sys.stdout.write("\n")
  elif just_includes:
    doc.writexml(open_output(output_filename))
    print()
  else:
    eval_self_contained(doc)
    banner = [
        xml.dom.minidom.Comment(c) for c in [
            " %s " % ('=' * 83),
            " |    This document was autogenerated by xacro from %-30s | " % args[0],
            " |    EDITING THIS FILE BY HAND IS NOT RECOMMENDED  %-30s | " % "",
            " %s " % ('=' * 83)
        ]
    ]
    first = doc.firstChild
    for comment in banner:
      doc.insertBefore(comment, first)

    open_output(output_filename).write(doc.toprettyxml(indent='  '))
    print()

if __name__ == '__main__':
  main()


# Given an integer n, return a string array answer (1-indexed) where:
#
# answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
# answer[i] == "Fizz" if i is divisible by 3.
# answer[i] == "Buzz" if i is divisible by 5.
# answer[i] == i (as a string) if none of the above conditions are true.
from typing import List

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        result = []

        for i in range(1, n + 1):
            if i % 5 == 0 and i % 3 == 0:
                result.append("FizzBuzz")
            elif i % 5 == 0:
                result.append("Buzz")
            elif i % 3 == 0:
                result.append("Fizz")
            else:
                result.append(str(i))

        return result

obj = Solution()

n = 3
print(obj.fizzBuzz(n))  # Output: ["1","2","Fizz"]

n = 5
print(obj.fizzBuzz(n))  # Output: ["1","2","Fizz","4","Buzz"]

n = 15
print(obj.fizzBuzz(n))
# Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz",
# "Buzz","11","Fizz","13","14","FizzBuzz"]


#@+leo-ver=5-thin
#@+node:ekr.20210911052754.1: * @file ../unittests/core/test_leoExternalFiles.py
"""Tests of leoExternalFiles.py"""

from leo.core import leoGlobals as g
import leo.core.leoApp as leoApp
from leo.core.leoTest2 import LeoUnitTest
import leo.core.leoExternalFiles as leoExternalFiles

#@+others
#@+node:ekr.20210911052754.2: ** class TestExternalFiles (LeoUnitTest)
class TestExternalFiles(LeoUnitTest):
    #@+others
    #@+node:ekr.20210911052754.3: *3* TestExternalFiles.setUp
    def setUp(self):
        """setUp for TestFind class"""
        super().setUp()
        c = self.c
        g.app.idleTimeManager = leoApp.IdleTimeManager()
        g.app.idleTimeManager.start()
        g.app.externalFilesController = leoExternalFiles.ExternalFilesController(c=c)
    #@+node:ekr.20210911052754.4: *3* TestExternalFiles.test_on_idle
    def test_on_idle(self):
        """
        A minimal test of the on_idle and all its helpers.

        More detail tests would be difficult.
        """
        efc = g.app.externalFilesController
        for i in range(100):
            efc.on_idle()
    #@-others
#@-others
#@-leo