'''

    Make Two Figures Set as One Figures Using Shape Detect

    This is only for Toner. Take Contour of Figures and find rectangle which have smallest area.

    Because two figures(normal and defect) rotate with different angle, Make them match by this module

    Keypoint detection should spend too much time, so I use shape detection, make them match as fast.
'''

import cv2
import numpy as np
import math

PI = 3.141592

# 여백
whiteScreen = 10

def ShapeDetector(inputImage1, inputImage2):
    XPixelOfInputimage2 = 3840
    YPixelOfInputimage2 = 2160
    # Call Normal Image
    normal_image = cv2.imread(inputImage1)
    normal_image = cv2.resize(normal_image, dsize=(640, 480), interpolation=cv2.INTER_AREA)
    gray = cv2.cvtColor(normal_image, cv2.COLOR_BGR2GRAY)
    ret, blmage = cv2.threshold(gray,220, 255, cv2.THRESH_BINARY_INV)
    blmage = cv2.dilate(blmage, None)

    # Backup normal image for cut
    # This image has 4096 X 2160
    normalImageForCut = cv2.imread(inputImage1)

    # Find Contours of Figures
    mode = cv2.RETR_EXTERNAL
    method = cv2.CHAIN_APPROX_SIMPLE
    contours, hierarchy = cv2.findContours(blmage, mode, method)
    print('len(contours) = ', len(contours))

    maxLength = 0
    k = 0
    for i, cnt in enumerate(contours):
        perimeter = cv2.arcLength(cnt, closed = True)
        if perimeter > maxLength:
            maxLength = perimeter
            k = i
    print('maxLength = ', maxLength)
    cnt = contours[k]
    dst2 = normal_image.copy()
    cv2.drawContours(dst2, [cnt], 0, (255, 0, 0), 3)

    # After Find Contour, Find Smallest area BOX.
    # The pixel number of BOX is saved at box
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int32(box)
    dst4 = dst2.copy()
    cv2.drawContours(dst4, [box], 0, (0,0,255), 2)
    cv2.imshow('normalImage', dst4)
    cv2.imwrite('./img/normalImage_dst4.png', dst4)

    # Call Defect Image
    defect = cv2.imread(inputImage2)
    defect = cv2.resize(defect, dsize=(640, 480), interpolation=cv2.INTER_AREA)
    gray_defect = cv2.cvtColor(defect, cv2.COLOR_BGR2GRAY)
    ret_defect, bImage_defect = cv2.threshold(gray_defect,220, 255, cv2.THRESH_BINARY_INV)
    bImage_defect = cv2.dilate(bImage_defect, None)

    # Backup Defect Image for Image Matching
    defectImageForMatching = cv2.imread(inputImage2)
    defectImageForMatching = cv2.resize(defectImageForMatching, dsize=(640, 480), interpolation=cv2.INTER_AREA)

    # Backup Defect Image for Cut
    defectImageForCut = cv2.imread(inputImage2)

    # Find Contours of Figures
    mode = cv2.RETR_EXTERNAL
    method = cv2.CHAIN_APPROX_SIMPLE
    contours_defect, hierarchy = cv2.findContours(bImage_defect, mode, method)
    print('len(contours_defect) = ', len(contours_defect))

    maxLength_defect = 0
    k_defect = 0
    for i, cnt in enumerate(contours_defect):
        perimeter = cv2.arcLength(cnt, closed = True)
        if perimeter > maxLength_defect:
            maxLength_defect = perimeter
            k_defect = i
    print('maxLength_defect = ', maxLength_defect)
    cnt_defect = contours_defect[k_defect]
    dst2_defect = defect.copy()
    cv2.drawContours(dst2_defect, [cnt], 0, (255, 0, 0), 3)

    # After Find Contour, Find Smallest area BOX.
    # The pixel number of BOX is saved at box_defect
    rect_defect = cv2.minAreaRect(cnt_defect)
    box_defect = cv2.boxPoints(rect_defect)
    box_defect = np.int32(box_defect)
    dst4_defect = dst2_defect.copy()
    cv2.drawContours(dst4_defect, [box_defect], 0, (0,0,255), 2)
    cv2.imshow('dst4_defect', dst4_defect)
    cv2.imwrite('./img/dst_defect.png', dst4_defect)

    print(' Box Coordinate for normal : ', box)
    print(' Box Coordinate for defect : ', box_defect)

    # Calculate With Mathematics
    # Calculate How many Rotate of Normal & Defect Image

    #
    # The order of components of box -> [Left Downside], [Left Upside], [Right Upside], [Right Downside]
    #

    slopeForHorizontalNormalImage = (box[2][1] - box[1][1]) / (box[2][0] - box[1][0])
    slopeForHorizontalDefectImage = (box_defect[2][1] - box_defect[1][1]) / (box_defect[2][0] - box_defect[1][0])

    if(slopeForHorizontalNormalImage != slopeForHorizontalDefectImage):
        print('Two Images are not matched. Start Matching...')
        print('Standard image is Normal Image.')

        AngleForNormalImage = math.atan(slopeForHorizontalNormalImage)
        AngleForDefectImage = math.atan(slopeForHorizontalDefectImage)

        print('Angle of Normal Image : ', AngleForNormalImage, ' Angle of Defect Image = ', AngleForDefectImage)

        # If normal image has bigger angle, below variable will be 0. if not, 1
        whichImageHasBiggerAngle = 0

        if(AngleForNormalImage > AngleForDefectImage):
            AngleDiscrepancy = AngleForNormalImage - AngleForDefectImage
        else :
            AngleDiscrepancy = AngleForDefectImage - AngleForNormalImage
            whichImageHasBiggerAngle = 1

        AngleDiscrepancyInDegree = AngleDiscrepancy*180/PI
        print('Difference between two angle : ', AngleDiscrepancy)
        print('Rotate defect Image as ', AngleDiscrepancyInDegree, 'degree')

        # Rotates Small Figures
        rows, cols, channels = defectImageForMatching.shape
        if whichImageHasBiggerAngle == 0:
            M1 = cv2.getRotationMatrix2D((rows/2, cols/2), -AngleDiscrepancyInDegree, 1.0)
        else:
            M1 = cv2.getRotationMatrix2D((rows/2, cols/2), AngleDiscrepancyInDegree, 1.0)
        rotatedDefectImage = cv2.warpAffine(defectImageForMatching, M1, (640, 480))

        # Rotates Image be cut
        rows, cols, channels = defectImageForCut.shape
        if whichImageHasBiggerAngle == 0:
            M2 = cv2.getRotationMatrix2D((rows/2, cols/2), -AngleDiscrepancyInDegree, 1.0)
        else:
            M2 = cv2.getRotationMatrix2D((rows/2, cols/2), AngleDiscrepancyInDegree, 1.0)
        rotatedDefectImageCut = cv2.warpAffine(defectImageForCut, M2, (XPixelOfInputimage2, YPixelOfInputimage2))

        # Find Smallest area box
        gray_rotatedDefect = cv2.cvtColor(rotatedDefectImage, cv2.COLOR_BGR2GRAY)
        ret_rotatedDefect, bImage_rotatedDefect = cv2.threshold(gray_rotatedDefect, 220, 255, cv2.THRESH_BINARY_INV)
        bImage_rotatedDefect = cv2.dilate(bImage_rotatedDefect, None)

        # Find Contours of Figures
        mode = cv2.RETR_EXTERNAL
        method = cv2.CHAIN_APPROX_SIMPLE
        contours_rotatedDefect, hierarchy_rotatedDefect = cv2.findContours(bImage_rotatedDefect, mode, method)
        print('len(contours_rotatedDefect) = ', len(contours_rotatedDefect))

        maxLength_rotatedDefect = 0
        k_rotatedDefect = 0
        for i, cnt in enumerate(contours_rotatedDefect):
            perimeter = cv2.arcLength(cnt, closed=True)
            if perimeter > maxLength_rotatedDefect:
                maxLength_rotatedDefect = perimeter
                k_rotatedDefect = i
        print('maxLength_defect = ', maxLength_rotatedDefect)
        cnt_rotatedDefect = contours_rotatedDefect[k_rotatedDefect]
        dst2_rotatedDefect = rotatedDefectImage.copy()
        cv2.drawContours(dst2_rotatedDefect, [cnt], 0, (255, 0, 0), 3)

        # After Find Contour, Find Smallest area BOX.
        # The pixel number of BOX is saved at box_defect
        rect_rotatedDefect = cv2.minAreaRect(cnt_rotatedDefect)
        box_rotatedDefect = cv2.boxPoints(rect_rotatedDefect)
        box_rotatedDefect = np.int32(box_rotatedDefect)
        dst4_rotatedDefect = dst2_rotatedDefect.copy()
        cv2.drawContours(dst4_rotatedDefect, [box_rotatedDefect], 0, (0, 0, 255), 2)
        print('Box point of rotated Image : ', box_rotatedDefect)
        cv2.imshow('Box point for rotated Image ', rotatedDefectImageCut)

        # This image has 4096 X 2160

        XDirectionPixelDefect = []
        YDirectionPixelDefect = []
        XDirectionPixelNormal = []
        YDirectionPixelNormal = []

        XDirectionPixelDefect.append((min([box_rotatedDefect[2][1] - whiteScreen , box_rotatedDefect[3][1] - whiteScreen])
                                     *YPixelOfInputimage2/480,
                                     max([box_rotatedDefect[3][1] + whiteScreen , box_rotatedDefect[0][1] + whiteScreen])
                                     *YPixelOfInputimage2/480))

        YDirectionPixelDefect.append((min([box_rotatedDefect[1][0] - whiteScreen , box_rotatedDefect[0][0] - whiteScreen])
                                      *XPixelOfInputimage2/640,
                                      max([box_rotatedDefect[2][0] + whiteScreen , box_rotatedDefect[3][0] + whiteScreen])
                                      *XPixelOfInputimage2/640))

        XDirectionPixelNormal.append((min([box[2][1] - whiteScreen , box[3][1] - whiteScreen])*YPixelOfInputimage2/480,
                                     max([box[3][1] + whiteScreen , box[0][1] + whiteScreen])*YPixelOfInputimage2/480))

        YDirectionPixelNormal.append((min([box[1][0] - whiteScreen , box[0][0] - whiteScreen])*XPixelOfInputimage2/640,
                                      max([box[2][0] + whiteScreen , box[3][0] + whiteScreen])*XPixelOfInputimage2/640))

        print('min and max value for Defect Image : ', XDirectionPixelDefect, YDirectionPixelDefect)
        print('min and max value for Normal Image : ', XDirectionPixelNormal, YDirectionPixelNormal)

        print('round number = ', int(round(XDirectionPixelDefect[0][0])),round(XDirectionPixelDefect[0][1]),
                                 round(YDirectionPixelDefect[0][0]),round(YDirectionPixelDefect[0][1]), 'For Defect')

        print('round number = ', int(round(XDirectionPixelNormal[0][0])),int(round(XDirectionPixelNormal[0][1])),
                                 int(round(YDirectionPixelNormal[0][0])),int(round(YDirectionPixelNormal[0][1])), 'For normal')

        CutRotatedDefectImage = rotatedDefectImageCut[int(round(XDirectionPixelDefect[0][0])):int(round(XDirectionPixelDefect[0][1])),
                                                      int(round(YDirectionPixelDefect[0][0])):int(round(YDirectionPixelDefect[0][1]))]

        CutNormalImage = normalImageForCut[int(round(XDirectionPixelNormal[0][0])):int(round(XDirectionPixelNormal[0][1])),
                                           int(round(YDirectionPixelNormal[0][0])):int(round(YDirectionPixelNormal[0][1]))]

        rowsDefect, colsDefect, channelsDefect = CutRotatedDefectImage.shape
        rowsNormal, colsNormal, channelsNormal = CutNormalImage.shape

        print('Pixel Size for images : ', rowsDefect , ' X', colsDefect, ' and channels : ', channelsDefect, 'For Defect')
        print('Pixel Size for images : ', rowsNormal , ' X', colsNormal, ' and channels : ', channelsNormal, 'For Normal')

        cv2.imwrite('./img/rotatedDefectImage.png', CutRotatedDefectImage)
        cv2.imwrite('./img/rotatedNormalImage.png', CutNormalImage)

        cv2.waitKey(0)
        cv2.destroyAllWindows()


#!/usr/bin/env python3

from gi.repository import GLib

import subprocess
import threading
from datetime import datetime

from nwg_panel.tools import check_key

import gi

gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')

from gi.repository import Gtk, Gdk

class Clock(Gtk.EventBox):
    def __init__(self, settings):
        self.settings = settings
        Gtk.EventBox.__init__(self)
        self.box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        self.add(self.box)
        self.label = Gtk.Label("")

        check_key(settings, "root-css-name", "root-clock")
        check_key(settings, "css-name", "clock")
        check_key(settings, "tooltip-text", "")
        check_key(settings, "on-left-click", "")
        check_key(settings, "on-right-click", "")
        check_key(settings, "on-middle-click", "")
        check_key(settings, "on-scroll-up", "")
        check_key(settings, "on-scroll-down", "")

        check_key(settings, "interval", 1)

        self.set_property("name", settings["root-css-name"])
        self.label.set_property("name", settings["css-name"])

        if settings["tooltip-text"]:
            self.set_tooltip_text(settings["tooltip-text"])

        if "format" not in settings:
            self.settings["format"] = "%a, %d. %b  %H:%M:%S"

        if settings["on-left-click"] or settings["on-right-click"] or settings["on-middle-click"] or settings[
            "on-scroll-up"] or settings["on-scroll-down"]:
            self.connect('button-press-event', self.on_button_press)
            self.add_events(Gdk.EventMask.SCROLL_MASK)
            self.connect('scroll-event', self.on_scroll)

            self.connect('enter-notify-event', self.on_enter_notify_event)
            self.connect('leave-notify-event', self.on_leave_notify_event)

        self.build_box()
        self.refresh()

        if settings["interval"] > 0:
            Gdk.threads_add_timeout_seconds(GLib.PRIORITY_LOW, settings["interval"], self.refresh)

    def update_widget(self, output):
        self.label.set_text(output)

        return False

    def get_output(self):
        now = datetime.now()
        try:
            time = now.strftime(self.settings["format"])
            GLib.idle_add(self.update_widget, time)
        except Exception as e:
            print(e)

    def refresh(self):
        thread = threading.Thread(target=self.get_output)
        thread.daemon = True
        thread.start()
        return True

    def build_box(self):
        self.box.pack_start(self.label, False, False, 4)
        self.label.show()

    def on_enter_notify_event(self, widget, event):
        self.get_style_context().set_state(Gtk.StateFlags.SELECTED)

    def on_leave_notify_event(self, widget, event):
        self.get_style_context().set_state(Gtk.StateFlags.NORMAL)

    def on_button_press(self, widget, event):
        if event.button == 1 and self.settings["on-left-click"]:
            self.launch(self.settings["on-left-click"])
        elif event.button == 2 and self.settings["on-middle-click"]:
            self.launch(self.settings["on-middle-click"])
        elif event.button == 3 and self.settings["on-right-click"]:
            self.launch(self.settings["on-right-click"])

    def on_scroll(self, widget, event):
        if event.direction == Gdk.ScrollDirection.UP and self.settings["on-scroll-up"]:
            self.launch(self.settings["on-scroll-up"])
        elif event.direction == Gdk.ScrollDirection.DOWN and self.settings["on-scroll-up"]:
            self.launch(self.settings["on-scroll-up"])
        else:
            print("No command assigned")

    def launch(self, cmd):
        print("Executing '{}'".format(cmd))
        subprocess.Popen('exec {}'.format(cmd), shell=True)


# -*- coding: utf-8 -*-
import importlib

def num2str(number, lang='pl'):
    module = importlib.import_module('.'.join(['langs', lang]))

    if number == 0:
        return module.numbers[0]

    result = ''
    digits = 0
    while number > 0:
        result = module.three_digits_str(number % 1000, digits) + result
        digits += 3
        number //= 1000

    return " ". join(result.split())


from typing import Tuple, Optional

from src.internal.adapters.entities.error import Error
from src.internal.biz.dao.base_dao import BaseDao
from src.internal.biz.deserializers.auth_code import AuthCodeDeserializer, DES_AUTH_CODE_FROM_DB_FULL, AUTH_CODE_ID, \
    AUTH_CODE_EDITED_AT
from src.internal.biz.entities.auth_code import AuthCode

class AuthCodeDao(BaseDao):

    async def get_by_account_main_id_code(self, auth_code: AuthCode) -> Tuple[Optional[AuthCode], Optional[Error]]:
        async with self.pool.acquire() as conn:
            row = await conn.fetchrow(
                """
                SELECT
                    id,
                    edited_at
                FROM
                    auth_code
                WHERE
                    account_main_id = $1 AND code = $2
                """, auth_code.account_main.id, auth_code.code
            )

            if not row:
                return None, None
            auth_code.id = row['id']
            auth_code.edited_at = row['edited_at']

            return auth_code, None

    async def remove_by_id(self, auth_code_id: int) -> Tuple[None, Optional[Error]]:
        async with self.pool.acquire() as conn:
            await conn.execute(
                """
                DELETE
                FROM auth_code
                WHERE id = $1
                """, auth_code_id
            )

            return None, None

    async def get_by_account_main_id(self, account_main_id: int) -> Tuple[Optional[AuthCode], Optional[Error]]:
        async with self.pool.acquire() as conn:
            row = await conn.fetchrow(
                f"""
                SELECT
                    id          {AUTH_CODE_ID},
                    edited_at   {AUTH_CODE_EDITED_AT}
                FROM
                    auth_code
                WHERE
                    account_main_id = $1
                """, account_main_id
            )

            if not row:
                return None, None
            return AuthCodeDeserializer.deserialize(row, DES_AUTH_CODE_FROM_DB_FULL), None

    async def update(self, auth_code_id: int, auth_code: AuthCode) -> Tuple[Optional[AuthCode], Optional[Error]]:
        async with self.pool.acquire() as conn:
            await conn.execute(
                """
                UPDATE
                    auth_code
                SET
                    edited_at = CURRENT_TIMESTAMP,
                    code = $1
                """, auth_code.code
            )

            return auth_code, None

    async def add(self, auth_code: AuthCode) -> Tuple[Optional[AuthCode], Optional[Error]]:
        async with self.pool.acquire() as conn:
            await conn.execute(
                """
                INSERT INTO auth_code(account_main_id, code) VALUES ($1, $2);
                """, auth_code.account_main.id, auth_code.code
            )

            return auth_code, None

    async def set_is_confirm(self, is_confirmed: bool) -> Tuple[None, Optional[Error]]:
        async with self.pool.acquire() as conn:
            await conn.execute(
                """
                UPDATE account_main
                SET is_confirmed = $1
                """, is_confirmed
            )
            return None, None


from setuptools import setup, find_packages

with open('README.md', 'r') as fi:
    long_description = fi.read()

setup(
    name='tdh-tcd',
    version='2.5.3',

    author='Dmitry Karikh',
    author_email='the.dr.hax@gmail.com',

    description='Twitch Chat Downloader',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/TheDrHax/Twitch-Chat-Downloader',

    install_requires=[
        'requests',
        'progressbar2',
        'iso8601'
    ],

    packages=find_packages(),
    package_data={'tcd': ['example.settings.json']},
    include_package_data=True,

    entry_points='''
    [console_scripts]
    tcd=tcd:main
    ''',

    classifiers=[
        'Environment :: Console',
        'Programming Language :: Python :: 3.6',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Topic :: Utilities'
    ]
)


#!/usr/bin/env python
"""Process simtel data for the training of the estimator models."""

import numpy as np
import astropy.units as u
from astropy.coordinates.angle_utilities import angular_separation
from sys import exit
from glob import glob
import signal
import tables as tb

from ctapipe.utils.CutFlow import CutFlow
from ctapipe.io import event_source
from ctapipe.reco.energy_regressor import EnergyRegressor

from protopipe.pipeline import EventPreparer
from protopipe.pipeline.utils import (
    make_argparser,
    prod3b_array,
    str2bool,
    load_config,
    SignalHandler,
    bcolors,
)

def main():

    # Argument parser
    parser = make_argparser()

    parser.add_argument(
        "--debug", action="store_true", help="Print debugging information",
    )

    parser.add_argument(
        "--save_images", action="store_true", help="Save also all images",
    )

    parser.add_argument(
        "--estimate_energy",
        type=str2bool,
        default=False,
        help="Estimate the events' energy with a regressor from\
         protopipe.scripts.build_model",
    )
    parser.add_argument(
        "--regressor_dir", type=str, default="./", help="regressors directory"
    )
    args = parser.parse_args()

    # Read configuration file
    cfg = load_config(args.config_file)

    try:  # If the user didn't specify a site and/or and array...
        site = cfg["General"]["site"]
        array = cfg["General"]["array"]
    except KeyError:  # ...raise an error and exit.
        print(
            "\033[91m ERROR: make sure that both 'site' and 'array' are "
            "specified in the analysis configuration file! \033[0m"
        )
        exit()

    if args.infile_list:
        filenamelist = []
        for f in args.infile_list:
            filenamelist += glob("{}/{}".format(args.indir, f))
        filenamelist.sort()
    else:
        raise ValueError("don't know which input to use...")

    if not filenamelist:
        print("no files found; check indir: {}".format(args.indir))
        exit(-1)
    else:
        print("found {} files".format(len(filenamelist)))

    # Get the IDs of the involved telescopes and associated cameras together
    # with the equivalent focal lengths from the first event
    allowed_tels, cams_and_foclens, subarray = prod3b_array(
        filenamelist[0], site, array
    )

    # keeping track of events and where they were rejected
    evt_cutflow = CutFlow("EventCutFlow")
    img_cutflow = CutFlow("ImageCutFlow")

    preper = EventPreparer(
        config=cfg,
        subarray=subarray,
        cams_and_foclens=cams_and_foclens,
        mode=args.mode,
        event_cutflow=evt_cutflow,
        image_cutflow=img_cutflow,
    )

    # catch ctr-c signal to exit current loop and still display results
    signal_handler = SignalHandler()
    signal.signal(signal.SIGINT, signal_handler)

    # Regressor method
    regressor_method = cfg["EnergyRegressor"]["method_name"]

    # wrapper for the scikit-learn regressor
    if args.estimate_energy is True:
        regressor_files = (
            args.regressor_dir + "/regressor_{mode}_{cam_id}_{regressor}.pkl.gz"
        )
        reg_file = regressor_files.format(
            **{
                "mode": args.mode,
                "wave_args": "mixed",  # ToDo, control
                "regressor": regressor_method,
                "cam_id": "{cam_id}",
            }
        )

        regressor = EnergyRegressor.load(reg_file, cam_id_list=cams_and_foclens.keys())

    # COLUMN DESCRIPTOR AS DICTIONARY
    # Column descriptor for the file containing output training data."""
    DataTrainingOutput = dict(
        # ======================================================================
        # ARRAY
        obs_id=tb.Int16Col(dflt=1, pos=0),
        event_id=tb.Int32Col(dflt=1, pos=1),
        tel_id=tb.Int16Col(dflt=1, pos=2),
        N_LST=tb.Int16Col(dflt=1, pos=3),
        N_MST=tb.Int16Col(dflt=1, pos=4),
        N_SST=tb.Int16Col(dflt=1, pos=5),
        n_tel_reco=tb.FloatCol(dflt=1, pos=6),
        n_tel_discri=tb.FloatCol(dflt=1, pos=7),
        # ======================================================================
        # DL1
        hillas_intensity_reco=tb.Float32Col(dflt=1, pos=8),
        hillas_intensity=tb.Float32Col(dflt=1, pos=9),
        hillas_x_reco=tb.Float32Col(dflt=1, pos=10),
        hillas_y_reco=tb.Float32Col(dflt=1, pos=11),
        hillas_x=tb.Float32Col(dflt=1, pos=12),
        hillas_y=tb.Float32Col(dflt=1, pos=13),
        hillas_r_reco=tb.Float32Col(dflt=1, pos=14),
        hillas_r=tb.Float32Col(dflt=1, pos=15),
        hillas_phi_reco=tb.Float32Col(dflt=1, pos=16),
        hillas_phi=tb.Float32Col(dflt=1, pos=17),
        hillas_length_reco=tb.Float32Col(dflt=1, pos=18),
        hillas_length=tb.Float32Col(dflt=1, pos=19),
        hillas_width_reco=tb.Float32Col(dflt=1, pos=20),
        hillas_width=tb.Float32Col(dflt=1, pos=21),
        hillas_psi_reco=tb.Float32Col(dflt=1, pos=22),
        hillas_psi=tb.Float32Col(dflt=1, pos=23),
        hillas_skewness_reco=tb.Float32Col(dflt=1, pos=24),
        hillas_skewness=tb.Float32Col(dflt=1, pos=25),
        hillas_kurtosis=tb.Float32Col(dflt=1, pos=26),
        hillas_kurtosis_reco=tb.Float32Col(dflt=1, pos=27),
        leakage_intensity_width_1_reco=tb.Float32Col(dflt=np.nan, pos=28),
        leakage_intensity_width_2_reco=tb.Float32Col(dflt=np.nan, pos=29),
        leakage_intensity_width_1=tb.Float32Col(dflt=np.nan, pos=30),
        leakage_intensity_width_2=tb.Float32Col(dflt=np.nan, pos=31),
        # The following are missing from current ctapipe DL1 output
        # Not sure if it's worth to add them
        hillas_ellipticity_reco=tb.FloatCol(dflt=1, pos=32),
        hillas_ellipticity=tb.FloatCol(dflt=1, pos=33),
        max_signal_cam=tb.Float32Col(dflt=1, pos=34),
        pixels=tb.Int16Col(dflt=1, pos=35),
        clusters=tb.Int16Col(dflt=-1, pos=36),
        # ======================================================================
        # DL2 - DIRECTION RECONSTRUCTION
        impact_dist=tb.Float32Col(dflt=1, pos=37),
        h_max=tb.Float32Col(dflt=1, pos=38),
        alt=tb.Float32Col(dflt=np.nan, pos=39),
        az=tb.Float32Col(dflt=np.nan, pos=40),
        err_est_pos=tb.Float32Col(dflt=1, pos=41),
        err_est_dir=tb.Float32Col(dflt=1, pos=42),
        xi=tb.Float32Col(dflt=np.nan, pos=43),
        offset=tb.Float32Col(dflt=np.nan, pos=44),
        mc_core_x=tb.FloatCol(dflt=1, pos=45),
        mc_core_y=tb.FloatCol(dflt=1, pos=46),
        reco_core_x=tb.FloatCol(dflt=1, pos=47),
        reco_core_y=tb.FloatCol(dflt=1, pos=48),
        mc_h_first_int=tb.FloatCol(dflt=1, pos=49),
        mc_x_max=tb.Float32Col(dflt=np.nan, pos=50),
        is_valid=tb.BoolCol(dflt=False, pos=51),
        good_image=tb.Int16Col(dflt=1, pos=52),
        # ======================================================================
        # DL2 - ENERGY ESTIMATION
        true_energy=tb.FloatCol(dflt=1, pos=53),
        reco_energy=tb.FloatCol(dflt=np.nan, pos=54),
        reco_energy_tel=tb.Float32Col(dflt=np.nan, pos=55),
        # ======================================================================
        # DL1 IMAGES
        # this is optional data saved by the user
        # since these data declarations require to know how many pixels
        # each saved image will have,
        # we add them later on, right before creating the table
        # We list them here for reference
        # true_image=tb.Float32Col(shape=(1855), pos=56),
        # reco_image=tb.Float32Col(shape=(1855), pos=57),
        # cleaning_mask_reco=tb.BoolCol(shape=(1855), pos=58),  # not in ctapipe
    )

    outfile = tb.open_file(args.outfile, mode="w")
    outTable = {}
    outData = {}

    for i, filename in enumerate(filenamelist):

        print("file: {} filename = {}".format(i, filename))

        source = event_source(
            input_url=filename, allowed_tels=allowed_tels, max_events=args.max_events
        )

        # loop that cleans and parametrises the images and performs the
        # reconstruction for each event
        for (
            event,
            reco_image,
            cleaning_mask_reco,
            cleaning_mask_clusters,
            true_image,
            n_pixel_dict,
            hillas_dict,
            hillas_dict_reco,
            leakage_dict,
            n_tels,
            max_signals,
            n_cluster_dict,
            reco_result,
            impact_dict,
            good_event,
            good_for_reco,
        ) in preper.prepare_event(
            source, save_images=args.save_images, debug=args.debug
        ):

            # Angular quantities
            run_array_direction = event.mcheader.run_array_direction

            if good_event:

                xi = angular_separation(
                    event.mc.az, event.mc.alt, reco_result.az, reco_result.alt
                )

                offset = angular_separation(
                    run_array_direction[0],  # az
                    run_array_direction[1],  # alt
                    reco_result.az,
                    reco_result.alt,
                )

                # Impact parameter
                reco_core_x = reco_result.core_x
                reco_core_y = reco_result.core_y

                # Height of shower maximum
                h_max = reco_result.h_max
                # Todo add conversion in number of radiation length,
                # need an atmosphere profile

                is_valid = True

            else:  # something went wrong and the shower's reconstruction failed

                xi = np.nan * u.deg
                offset = np.nan * u.deg
                reco_core_x = np.nan * u.m
                reco_core_y = np.nan * u.m
                h_max = np.nan * u.m
                reco_result.alt = np.nan * u.deg
                reco_result.az = np.nan * u.deg
                is_valid = False

            reco_energy = np.nan
            reco_energy_tel = dict()

            # Not optimal at all, two loop on tel!!!
            # For energy estimation
            # Estimate energy only if the shower was reconstructed
            if (args.estimate_energy is True) and is_valid:
                weight_tel = np.zeros(len(hillas_dict.keys()))
                energy_tel = np.zeros(len(hillas_dict.keys()))

                for idx, tel_id in enumerate(hillas_dict.keys()):

                    # use only images that survived cleaning and
                    # parametrization
                    if not good_for_reco[tel_id]:
                        # bad images will get an undetermined energy
                        # this is a per-telescope energy
                        # NOT the estimated energy for the shower
                        reco_energy_tel[tel_id] = np.nan
                        continue

                    cam_id = source.subarray.tel[tel_id].camera.camera_name
                    moments = hillas_dict[tel_id]
                    model = regressor.model_dict[cam_id]

                    features_img = np.array(
                        [
                            np.log10(moments.intensity),
                            np.log10(impact_dict[tel_id].value),
                            moments.width.value,
                            moments.length.value,
                            h_max.value,
                        ]
                    )

                    energy_tel[idx] = model.predict([features_img])
                    weight_tel[idx] = moments.intensity
                    reco_energy_tel[tel_id] = energy_tel[idx]

                reco_energy = np.sum(weight_tel * energy_tel) / sum(weight_tel)
            else:
                for idx, tel_id in enumerate(hillas_dict.keys()):
                    reco_energy_tel[tel_id] = np.nan

            for idx, tel_id in enumerate(hillas_dict.keys()):
                cam_id = source.subarray.tel[tel_id].camera.camera_name

                if cam_id not in outData:

                    if args.save_images is True:
                        # we define and save images content here, to make it
                        # adaptive to different cameras

                        n_pixels = source.subarray.tel[tel_id].camera.geometry.n_pixels
                        DataTrainingOutput["true_image"] = tb.Float32Col(
                            shape=(n_pixels), pos=56
                        )
                        DataTrainingOutput["reco_image"] = tb.Float32Col(
                            shape=(n_pixels), pos=57
                        )
                        DataTrainingOutput["cleaning_mask_reco"] = tb.BoolCol(
                            shape=(n_pixels), pos=58
                        )  # not in ctapipe
                        DataTrainingOutput["cleaning_mask_clusters"] = tb.BoolCol(
                            shape=(n_pixels), pos=58
                        )  # not in ctapipe

                    outTable[cam_id] = outfile.create_table(
                        "/", cam_id, DataTrainingOutput,
                    )
                    outData[cam_id] = outTable[cam_id].row

                moments = hillas_dict[tel_id]
                ellipticity = moments.width / moments.length

                # Write to file also the Hillas parameters that have been used
                # to calculate reco_results

                moments_reco = hillas_dict_reco[tel_id]
                ellipticity_reco = moments_reco.width / moments_reco.length

                outData[cam_id]["good_image"] = good_for_reco[tel_id]
                outData[cam_id]["is_valid"] = is_valid
                outData[cam_id]["impact_dist"] = impact_dict[tel_id].to("m").value
                outData[cam_id]["max_signal_cam"] = max_signals[tel_id]
                outData[cam_id]["hillas_intensity"] = moments.intensity
                outData[cam_id]["N_LST"] = n_tels["LST_LST_LSTCam"]
                outData[cam_id]["N_MST"] = (
                    n_tels["MST_MST_NectarCam"]
                    + n_tels["MST_MST_FlashCam"]
                    + n_tels["MST_SCT_SCTCam"]
                )
                outData[cam_id]["N_SST"] = (
                    n_tels["SST_1M_DigiCam"]
                    + n_tels["SST_ASTRI_ASTRICam"]
                    + n_tels["SST_GCT_CHEC"]
                )
                outData[cam_id]["hillas_width"] = moments.width.to("deg").value
                outData[cam_id]["hillas_length"] = moments.length.to("deg").value
                outData[cam_id]["hillas_psi"] = moments.psi.to("deg").value
                outData[cam_id]["hillas_skewness"] = moments.skewness
                outData[cam_id]["hillas_kurtosis"] = moments.kurtosis
                outData[cam_id]["h_max"] = h_max.to("m").value
                outData[cam_id]["err_est_pos"] = np.nan
                outData[cam_id]["err_est_dir"] = np.nan
                outData[cam_id]["true_energy"] = event.mc.energy.to("TeV").value
                outData[cam_id]["hillas_x"] = moments.x.to("deg").value
                outData[cam_id]["hillas_y"] = moments.y.to("deg").value
                outData[cam_id]["hillas_phi"] = moments.phi.to("deg").value
                outData[cam_id]["hillas_r"] = moments.r.to("deg").value

                outData[cam_id]["pixels"] = n_pixel_dict[tel_id]
                outData[cam_id]["obs_id"] = event.index.obs_id
                outData[cam_id]["event_id"] = event.index.event_id
                outData[cam_id]["tel_id"] = tel_id
                outData[cam_id]["xi"] = xi.to("deg").value
                outData[cam_id]["reco_energy"] = reco_energy
                outData[cam_id]["hillas_ellipticity"] = ellipticity.value
                outData[cam_id]["clusters"] = n_cluster_dict[tel_id]
                outData[cam_id]["n_tel_discri"] = n_tels["GOOD images"]
                outData[cam_id]["mc_core_x"] = event.mc.core_x.to("m").value
                outData[cam_id]["mc_core_y"] = event.mc.core_y.to("m").value
                outData[cam_id]["reco_core_x"] = reco_core_x.to("m").value
                outData[cam_id]["reco_core_y"] = reco_core_y.to("m").value
                outData[cam_id]["mc_h_first_int"] = event.mc.h_first_int.to("m").value
                outData[cam_id]["offset"] = offset.to("deg").value
                outData[cam_id]["mc_x_max"] = event.mc.x_max.value  # g / cm2
                outData[cam_id]["alt"] = reco_result.alt.to("deg").value
                outData[cam_id]["az"] = reco_result.az.to("deg").value
                outData[cam_id]["reco_energy_tel"] = reco_energy_tel[tel_id]
                # Variables from hillas_dist_reco
                outData[cam_id]["n_tel_reco"] = n_tels["GOOD images"]
                outData[cam_id]["hillas_x_reco"] = moments_reco.x.to("deg").value
                outData[cam_id]["hillas_y_reco"] = moments_reco.y.to("deg").value
                outData[cam_id]["hillas_phi_reco"] = moments_reco.phi.to("deg").value
                outData[cam_id]["hillas_ellipticity_reco"] = ellipticity_reco.value
                outData[cam_id]["hillas_r_reco"] = moments_reco.r.to("deg").value
                outData[cam_id]["hillas_skewness_reco"] = moments_reco.skewness
                outData[cam_id]["hillas_kurtosis_reco"] = moments_reco.kurtosis
                outData[cam_id]["hillas_width_reco"] = moments_reco.width.to(
                    "deg"
                ).value
                outData[cam_id]["hillas_length_reco"] = moments_reco.length.to(
                    "deg"
                ).value
                outData[cam_id]["hillas_psi_reco"] = moments_reco.psi.to("deg").value
                outData[cam_id]["hillas_intensity_reco"] = moments_reco.intensity
                outData[cam_id]["leakage_intensity_width_1_reco"] = leakage_dict[
                    tel_id
                ]["leak1_reco"]
                outData[cam_id]["leakage_intensity_width_2_reco"] = leakage_dict[
                    tel_id
                ]["leak2_reco"]
                outData[cam_id]["leakage_intensity_width_1"] = leakage_dict[tel_id][
                    "leak1"
                ]
                outData[cam_id]["leakage_intensity_width_2"] = leakage_dict[tel_id][
                    "leak2"
                ]

                # =======================
                # IMAGES INFORMATION
                # =======================

                if args.save_images is True:
                    # we define and save images content here, to make it
                    # adaptive to different cameras

                    outData[cam_id]["true_image"] = true_image[tel_id]
                    outData[cam_id]["reco_image"] = reco_image[tel_id]
                    outData[cam_id]["cleaning_mask_reco"] = cleaning_mask_reco[tel_id]
                    outData[cam_id]["cleaning_mask_clusters"] = cleaning_mask_clusters[
                        tel_id
                    ]
                # =======================

                outData[cam_id].append()

            if signal_handler.stop:
                break
        if signal_handler.stop:
            break
    # make sure that all the events are properly stored
    for table in outTable.values():
        table.flush()

    print(
        bcolors.BOLD
        + "\n\n==================================================\n"
        + "Statistical summary of processed events and images\n"
        + "==================================================\n"
        # + bcolors.ENDC
    )

    evt_cutflow()

    # Catch specific cases
    triggered_events = evt_cutflow.cuts["min2Tels trig"][1]
    reconstructed_events = evt_cutflow.cuts["min2Tels reco"][1]

    if triggered_events == 0:
        print(
            "\033[93mWARNING: No events have been triggered"
            " by the selected telescopes! \033[0m"
        )
    else:
        print("\n")
        img_cutflow()
        if reconstructed_events == 0:
            print(
                "\033[93m WARNING: None of the triggered events have been "
                "properly reconstructed by the selected telescopes!\n"
                "DL1 file will be empty! \033[0m"
            )
        print(bcolors.ENDC)

if __name__ == "__main__":
    main()


from selenium import  webdriver # 调用selenium模块、webdriver模块
from selenium.webdriver.chrome.options import Options # 调用Option模块
from bs4 import BeautifulSoup
import time

chrome_options = Options() # 实例化Option对象
chrome_options.add_argument('--headless') # 把Chrome设置为静默模式
driver = webdriver.Chrome(options = chrome_options) # 声明浏览器对象
driver.get('https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html') # 访问页面
time.sleep(2)

button = driver.find_element_by_class_name('js_get_more_hot') # 根据类名找到【点击加载更多】
button.click() # 点击
time.sleep(2) # 等待两秒

comments = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li') # 使用
print(len(comments)) # 打印获取到的评论个数
for comment in comments: # 循环
    sweet = comment.find_element_by_tag_name('p') # 找到评论
    print ('评论：%s\n ---\n'%sweet.text) # 打印评论


import os
import sys
import glob

import cv2
import numpy as np

IMAGETYPES = ('*.bmp', '*.png', '*.jpg', '*.jpeg', '*.tif') # Supported image types

def get_image_paths(file_root, pattern=None):
    """ Get ordered list of filepaths
    """
    file_paths = []
    for typ in IMAGETYPES:
		# search all files conforming to the IMAGE_TYPES extensions
        file_paths.extend(glob.glob(os.path.join(file_root,'**',typ), recursive=True))
    # filter filenames
    if pattern is not None:
        filtered = []
        filtered = [f for f in file_paths if pattern in os.path.split(f)[-1]]
        file_paths = filtered
        del filtered
	# sort image file paths
    file_paths.sort()
    return file_paths

def load_face_dataset(file_root):
    """ Load all images and also list out the filepaths
    """
    if not os.path.isdir(file_root):
        raise FileNotFoundError("Face dataset file root: {} not found.".format(file_root))

    file_paths = get_image_paths(file_root)

    if len(file_paths) == 0:
        warnings.warn("No image found in face dataset file root: {}".format(file_root))
        return []

    images = [cv2.imread(file_path) for file_path in file_paths]
    return images, file_paths


import requests
from bs4 import BeautifulSoup as BS

url = 'https://www.sti.gov.kg/'

def get_html():
    response = requests.get(url)
    return response.text

# https://www.sti.gov.kg/allnews
# https://www.sti.gov.kg/allnews/page/59
all_pages = []
pagination = 'allnews/page/'
def get_all_pages():
    for page in range(0, 59):
        page += 1
        page_url = f'{url}{pagination}{page}'
        all_pages.append(page_url)
        with open('all_pages.txt', 'w') as file:
            for i in all_pages:
                file.write(f'{i}\n')
get_all_pages()

# /html/body/form/div[6]/div/div/div[2]/div/div[2]/div[1]/div/ul/li[1]/h2/a
# /html/body/form/div[6]/div/div/div[2]/div/div[2]/div[1]/div/ul/li[5]/h2/a
# /html/body/form/div[6]/div/div/div[2]/div/div[2]/div[2]/div/ul/li[1]/h2/a
# /html/body/form/div[5]/div/div/div[2]/div/div/div/div/ul/li[2]/a

all_news = []
html = get_html()
soup = BS(html, 'html.parser')
def get_all_news():
    h2 = soup.find('body').find_all('h2')
    for news1 in h2:
        try:
                a = news1.find('a').get('href')
                a = f'{url}{pagination}{a}'
                all_news.append(a)
                print(a)
        except Exception as ex:
            pass
    with open('all_news.txt', 'w') as file:
        for news1 in all_news:
            file.write(f'{news1}\n')
get_all_news()


from django.http import HttpResponse
from django_email import djemail

def send_email_view(request):
    """
    Simple example on how to send an email in a view.
    """
    # djemail.send_email(
    #     to="email@test.com",
    #     template="email/notification", # .txt and/or .html
    #     context={'variable': 'Variable Content'},
    #     subject="My Subject"
    # )

    djemail.send_email(
        to="email@test.com",
        message="This is the message",
        subject="My Subject"
    )

    return HttpResponse('Please check your console')


#!/usr/bin/python
"""
Test Cases for the CyberQInterface Library

ChangeLog:
A00 - 11/04/2012 - Bryan Kemp - Initial release
"""

__author__ = "Bryan Kemp <bryan@thebrilliantidea.com>"
__version__ = "A00"
__date__ = '11/04/2012'
__license__ = "BSD New"
__license_text__ = """
Copyright (c) 2012, The Brilliant Idea
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the The Brilliant Idea, LLC. nor the names of its contributors may
   be used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import unittest
import requests
from mock import patch
from cyberqinterface.cyberqinterface import CyberQInterface
from cyberqinterface.cyberqinterface_exceptions import *
TestCyberQInterfaceSuite = unittest.TestLoader()

class TestCyberQInterfaceInit(unittest.TestCase):
    """Test that the initializer works and gets all of the needed variables"""
    def setUp(self):
        pass

    def tearDown(self):
        """None"""
        pass

    def testProperInit(self):
        """Test host property is set to proper value"""
        cqi = CyberQInterface("localhost")
        self.assertEqual(cqi.host, "localhost")

    def testInitWithHeaders(self):
        """Test supplying custom headers"""
        cqi = CyberQInterface("localhost", {"Test-Header": "Test"})
        self.assertEqual(cqi.headers["Test-Header"], "Test")

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceInit)

class TestCyberQInterfaceValidateParameters(unittest.TestCase):
    """Test to make sure that the validate parameters function is working"""
    def setUp(self):
        """Setup: None"""

    def tearDown(self):
        """TearDown: None"""
        pass

    def testAllParameters(self):
        """Test the full set of parameters are correct"""
        cqi = CyberQInterface("127.0.0.1")
        assert cqi._validateParameters( {"COOK_NAME": 1, "COOK_SET": 1,
                                         "FOOD1_NAME": 1, "FOOD1_SET": 1,
                                         "FOOD2_NAME": 1, "FOOD2_SET": 1,
                                         "FOOD3_NAME": 1, "FOOD3_SET": 1,
                                         "_COOK_TIMER": 1, "COOK_TIMER": 1,
                                         "COOKHOLD": 1, "TIMEOUT_ACTION": 1,
                                         "ALARMDEV": 1, "COOK_RAMP": 1,
                                         "OPENDETECT": 1, "CYCTIME": 1,
                                         "PROPBAND": 1, "MENU_SCROLLING": 1,
                                         "LCD_BACKLIGHT": 1, "LCD_CONTRAST": 1,
                                         "DEG_UNITS": 1, "ALARM_BEEPS": 1,
                                         "KEY_BEEPS": 1}) == {}

    def testBadParameters(self):
        """Test parameters with 3 bad parameters"""
        cqi = CyberQInterface("127.0.0.1")
        assert len(cqi._validateParameters( {"COK_NAME": 1, "COOK_SET": 1,
                                             "FOOD1_NAME": 1, "FOOD1_SET": 1,
                                             "FOOD2_NAME": 1, "FOOD2_SET": 1,
                                             "FOOD3_NAME": 1, "FOOD3_SET": 1,
                                             "_COOK_TIMER": 1, "COOK_TIMER": 1,
                                             "COOKHOLD": 1, "TIEOUT_ACTION": 1,
                                             "ALARMDEV": 1, "COOK_RAMP": 1,
                                             "OPENDETECT": 1, "CYCTIME": 1,
                                             "PROPBAND": 1, "MNU_SCROLLING": 1,
                                             "LCD_BACKLIGHT": 1,
                                             "LCD_CONTRAST": 1, "DEG_UNITS": 1,
                                             "ALARM_BEEPS": 1,
                                             "KEY_BEEPS": 1})) == 3
TestCyberQInterfaceSuite.loadTestsFromTestCase(
    TestCyberQInterfaceValidateParameters)

class TestCyberQInterfaceRequests(unittest.TestCase):
    """
    Test the interaction with the CyberQ web interface and XML to object
    translation
    """

    def setUp(self):
        """Setup: None"""

    def tearDown(self):
        """TearDown: None"""

    def testInvalidReturnCode(self):
        """
        Test that the proper exception is thrown if the server returns bad
        status code
        """
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(ResponseHTTPException):
                cqi = CyberQInterface("127.0.0.1")
                mockMethod.return_value.status_code = 500
                cqi.getConfigXML()

    def testValidReturnCode(self):
        """Test that a 200 code returns a string"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = "testcase"
            xml = CyberQInterface("127.0.0.1").getConfigXML()
            self.assertEqual(xml, "testcase")

    def testGetStatusWithBadXML(self):
        """Test that the correct Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(ResponseValidationException):
                mockMethod.return_value.status_code = 200
                mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEM2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOKTUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
                CyberQInterface("127.0.0.1").getStatus()

    def testGetStatus(self):
        """Test that the correct Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEMP>OPEN</FOOD2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOK_STATUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
            status = CyberQInterface("127.0.0.1").getStatus()
            self.assertEqual(status.tag, "nutcstatus")

    def testGetAll(self):
        """Test that the All Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(AttributeError):
                mockMethod.return_value.status_code = 200
                mockMethod.return_value.text = """
<nutcallstatus>
<!--this is similar to status.xml, but with more values-->
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<COOK>
  <COOK_NAME>Big Green Egg</COOK_NAME>
  <COOK_TEMP>3216</COOK_TEMP>
  <COOK_SET>4000</COOK_SET>
  <COOK_STATUS>0</COOK_STATUS>
</COOK>
<FOOD1>
  <FOOD1_NAME>Chicken Quarters</FOOD1_NAME>
  <FOOD1_TEMP>1482</FOOD1_TEMP>
  <FOOD1_SET>1750</FOOD1_SET>
  <FOOD1_STATUS>0</FOOD1_STATUS>
</FOOD1>
<FOOD2>
  <FOOD2_NAME>Food2</FOOD2_NAME>
  <FOOD2_TEMP>OPEN</FOOD2_TEMP>
  <FOOD2_SET>1000</FOOD2_SET>
  <FOOD2_STATUS>4</FOOD2_STATUS>
</FOOD2>
<FOOD3>
  <FOOD3_NAME>Food3</FOOD3_NAME>
  <FOOD3_TEMP>OPEN</FOOD3_TEMP>
  <FOOD3_SET>1000</FOOD3_SET>
  <FOOD3_STATUS>4</FOOD3_STATUS>
</FOOD3>
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcallstatus>
"""
                allObj = CyberQInterface("127.0.0.1").getAll()
                self.assertNotEqual(allObj.CONTROL.OPENDETECT, 1)

    def testGetConfig(self):
        """Test that the config Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcallstatus>
<!--this is similar to all.xml, but with more values-->
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<COOK>
  <COOK_NAME>Big Green Egg</COOK_NAME>
  <COOK_TEMP>3220</COOK_TEMP>
  <COOK_SET>4000</COOK_SET>
  <COOK_STATUS>0</COOK_STATUS>
</COOK>
<FOOD1>
  <FOOD1_NAME>Chicken Quarters</FOOD1_NAME>
  <FOOD1_TEMP>1493</FOOD1_TEMP>
  <FOOD1_SET>1750</FOOD1_SET>
  <FOOD1_STATUS>0</FOOD1_STATUS>
</FOOD1>
<FOOD2>
  <FOOD2_NAME>Food2</FOOD2_NAME>
  <FOOD2_TEMP>OPEN</FOOD2_TEMP>
  <FOOD2_SET>1000</FOOD2_SET>
  <FOOD2_STATUS>4</FOOD2_STATUS>
</FOOD2>
<FOOD3>
  <FOOD3_NAME>Food3</FOOD3_NAME>
  <FOOD3_TEMP>OPEN</FOOD3_TEMP>
  <FOOD3_SET>1000</FOOD3_SET>
  <FOOD3_STATUS>4</FOOD3_STATUS>
</FOOD3>
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<TIMER_STATUS>0</TIMER_STATUS>
<SYSTEM>
  <MENU_SCROLLING>1</MENU_SCROLLING>
  <LCD_BACKLIGHT>47</LCD_BACKLIGHT>
  <LCD_CONTRAST>10</LCD_CONTRAST>
  <DEG_UNITS>1</DEG_UNITS>
  <ALARM_BEEPS>0</ALARM_BEEPS>
  <KEY_BEEPS>0</KEY_BEEPS>
</SYSTEM>
<CONTROL>
  <TIMEOUT_ACTION>0</TIMEOUT_ACTION>
  <COOKHOLD>2000</COOKHOLD>
  <ALARMDEV>500</ALARMDEV>
  <COOK_RAMP>0</COOK_RAMP>
  <OPENDETECT>1</OPENDETECT>
  <CYCTIME>6</CYCTIME>
  <PROPBAND>500</PROPBAND>
</CONTROL>
<WIFI>
  <IP>10.0.1.30</IP>
  <NM>255.255.255.0</NM>
  <GW>10.0.1.1</GW>
  <DNS>10.0.1.1</DNS>
  <WIFIMODE>0</WIFIMODE>
  <DHCP>0</DHCP>
  <SSID>Wireless Network</SSID>
  <WIFI_ENC>6</WIFI_ENC>
  <WIFI_KEY>SsecretKey</WIFI_KEY>
  <HTTP_PORT>80</HTTP_PORT>
</WIFI>
<SMTP>
  <SMTP_HOST>smtp.hostname.com</SMTP_HOST>
  <SMTP_PORT>0</SMTP_PORT>
  <SMTP_USER></SMTP_USER>
  <SMTP_PWD></SMTP_PWD>
  <SMTP_TO>destination@someplace.com</SMTP_TO>
  <SMTP_FROM>source@someplace.com</SMTP_FROM>
  <SMTP_SUBJ>Temperature Controller Status E-Mail</SMTP_SUBJ>
  <SMTP_ALERT>0</SMTP_ALERT>
</SMTP>
</nutcallstatus>
"""
            configObj = CyberQInterface("127.0.0.1").getConfig()
            self.assertEqual(configObj.CONTROL.OPENDETECT, 1)

    def testSendUpdate(self):
        """
        Test the ability to send a message to the CyberQ with good parameters
        """
        with patch.object(requests, 'post') as mockMethod:
            mockMethod.return_value.status_code = 200
            cqi = CyberQInterface("127.0.0.1")
            self.assertEqual(cqi.sendUpdate({'FOOD1_NAME' : "Tri-Tip Roast",
                                             'FOOD1_SET': '140',
                                             'COOK_SET' : '300'}),True)

    def testSendUpdateWithBadParameters(self):
        """
        Test the ability to send a message to the CyberQ with bad parameters
        """
        with patch.object(requests, 'post') as mockMethod:
            with self.assertRaises(ParameterValidationException):
                mockMethod.return_value.status_code = 200
                cqi = CyberQInterface("127.0.0.1")
                cqi.sendUpdate({'FOOD1_NME' : "Tri-Tip Roast",
                                'FOOD1_SET': '140', 'COOK_SET' : '300'})

    def testSendUpdateWithBadResponse(self):
        """
        Test the ability to send a message to the CyberQ with good parameters
        but a bad response
        """
        with patch.object(requests, 'post') as mockMethod:
            with self.assertRaises(ResponseHTTPException):
                mockMethod.return_value.status_code = 500
                cqi = CyberQInterface("127.0.0.1")
                cqi.sendUpdate({'FOOD1_NAME' : "Tri-Tip Roast",
                                'FOOD1_SET': '140', 'COOK_SET' : '300'})

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceRequests)

class TestCyberQInterfaceLookups(unittest.TestCase):
    """Test the lookup functionality for temperature, status, and ramp"""
    def setUp(self):
        """Setup: None"""
        pass

    def tearDown(self):
        """TearDown: None"""
        pass

    def testRampLookups(self):
        """Test that all known ramp codes work"""
        cqi = CyberQInterface("127.0.0.1")
        rampCodes = ["OFF", "FOOD1", "FOOD2", "FOOD3"]
        for code in range (0, len(rampCodes)-1):
            self.assertEqual(cqi.rampLookup(code), rampCodes[code])

    def testStatusLookups(self):
        """Test that all known status codes work"""
        cqi = CyberQInterface("127.0.0.1")
        statusCodes = ["OK", "HIGH", "LOW", "DONE", "ERROR", "HOLD", "ALARM",
                      "SHUTDOWN"]
        for code in range (0, len(statusCodes)-1):
            self.assertEqual(cqi.statusLookup(code), statusCodes[code])

    def testTemperatureLookups(self):
        """Test that all known temperature codes work"""
        cqi = CyberQInterface("127.0.0.1")
        temperatureCodes = ["CELSIUS", "FAHRENHEIT"]
        for code in range (0, len(temperatureCodes)-1):
            self.assertEqual(cqi.temperatureLookup(code),
                             temperatureCodes[code])

    def testBadTableName(self):
        """Test that an unknown table produces a known exception"""
        with self.assertRaises(LookupException):
            cqi = CyberQInterface("127.0.0.1")
            cqi._lookup("badtable", 0)

    def testInvalidCodeNumber(self):
        """Test that an index out of range is handled"""
        with self.assertRaises(LookupException):
            cqi = CyberQInterface("127.0.0.1")
            cqi._lookup("temperature", 4)

    def testLookupFromStatusObject(self):
        """Test that the code from an actual status object works properly"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEMP>OPEN</FOOD2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOK_STATUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
            cqi = CyberQInterface("127.0.0.1")
            status = cqi.getStatus()
            self.assertEqual(cqi.statusLookup(status.FOOD1_STATUS),"OK")

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceLookups)

if __name__ == '__main__':
    import nose
    nose.main()


from restapi.utils import to_int_list, from_csv
from django import forms
from tasks import models

class StatsForm(forms.Form):
    campaign = forms.IntegerField(required=False)
    tasks = forms.CharField(required=False)
    users = forms.CharField(required=False)
    groups = forms.CharField(required=False)
    start = forms.DateField(required=False)
    end = forms.DateField(required=False)
    plen = forms.IntegerField(required=False)

    def parse_campaign(self):
        if self.cleaned_data['campaign']:
            try:
                return models.Campaign.objects.get(pk=self.cleaned_data['campaign'])
            except models.Campaign.DoesNotExist:
                return None
        return None

    def parse_from_csv(self, name, queryset):
        if self.cleaned_data[name] is not None:
            ids = to_int_list(from_csv(self.cleaned_data[name]))
            return list(queryset.filter(pk__in=ids))
        return []

    def parse_users(self):
        return self.parse_from_csv('users', models.User.objects)

    def parse_tasks(self):
        return self.parse_from_csv('tasks', models.Task.objects)


# -*- coding: cp936 -*-
from math import *
import visual as vs

import random

import numpy as np
import pylab
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib import pyplot as plt

def dist( pos1, pos2 ):
    return sqrt( pow(pos1[0]-pos2[0], 2) + pow(pos1[1]-pos2[1], 2) + pow(pos1[2]-pos2[2], 2))

xRange = 121
yRange = 121
zRange = 1

density = [0 for i in range( xRange*yRange*zRange )]

def getDensity(pos):
    if (xRange-1)/2>= pos[0] >= -(xRange-1)/2 and (yRange-1)/2 >= pos[1] >= -(yRange-1)/2 and zRange-1 >= pos[2] >= 0:
        return density[int(((pos[0]+(xRange-1)/2)*yRange+(pos[1]+(yRange-1)/2))*zRange+pos[2])]
    else:
        return -1

# Set the environment here
def drawEnv( sourcePos = (-40, 0, 0), step = 5):
    # Set the environmen(density)
    for i in range(-int((xRange-1)/2), int((xRange-1)/2)):
        for j in range(-int((yRange-1)/2), int((yRange-1)/2)):
            for k in range (0, int(zRange)):
                num = int(((i+(xRange-1)/2)*yRange + (j+(yRange-1)/2))*zRange + k)
                p = (i, j, k)
                density[num] = 1 / (dist(sourcePos, p)+0.00001)

def makeHoriVector(theta):
    return vs.vector(cos(theta), sin(theta), 0)

def makeVector(theta, phi):
    return vs.vector(cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi))

def sigmoid(x, alpha = -4):
    return 1.0 / (1.0+exp(-alpha*x)) if x < 10 else 0

# Implement your strategy for vehicle here
def loopVehicle( vsrcPos = vs.vector(-20, 0, 30), initPos = (40, 40, 0), theta = 3/2*pi, phi = 0, delta = 0.5, W = 4, alpha = -4, thre_den = 0.4 ):
    """ Init & loop vehicle.
    """

    initAxis = (cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi))

    vPos, vAxis, vVelocity = vs.vector(initPos), vs.vector(initAxis), vs.vector(initAxis)
    deltat = delta
    vscale = 8

    time = 0
    sampleTime = 500
    sampleN = 0
    distance = 0

    while True:
        #vs.rate(3000)

        orthV = makeHoriVector(theta+pi/2)
        orthV2 = makeVector(theta, phi+pi/2)
        lSensorPos = tuple(int(x) for x in (vPos+orthV*W/2).astuple())
        rSensorPos = tuple(int(x) for x in (vPos-orthV*W/2).astuple())
        #print(rSensorPos)

        if (getDensity(lSensorPos) == -1 or getDensity(rSensorPos) == -1) :
            vVelocity = -vVelocity
            vAxis = vVelocity
            vPos = vPos+vVelocity*deltat
            continue

        if (getDensity(lSensorPos) > getDensity(rSensorPos)):
            theta = theta + pi/180
        elif getDensity(lSensorPos) < getDensity(rSensorPos):
            theta = theta - pi/180

        vVelocity = makeVector(theta, phi)
        vPos = vPos+vVelocity*deltat*sigmoid(getDensity(lSensorPos)+getDensity(rSensorPos), alpha)
        vAxis = vVelocity

        if (getDensity(lSensorPos)+getDensity(rSensorPos))/2 <= thre_den:
            time = time + 1
        else:
            distance = distance+vs.mag(vsrcPos-vPos)
            return (time, distance)
        if time >= sampleTime:
            return (time, distance)

drawEnv(sourcePos = (-20, 0, 0))

thre_den = [0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6]

time = [0 for i in range(len(thre_den))]

distance = [0 for i in range(len(thre_den))]

for k in range(len(thre_den)):
    for i in range(1, 4):
        temp = loopVehicle(vsrcPos = vs.vector(-20, 0, 0), theta = i/2*pi, initPos = (20, 20, 0), alpha = 0, delta = 1, thre_den = thre_den[k])
        time[k] = time[k]+temp[0]
        distance[k] = distance[k]+temp[1]

time = [x/4 for x in time]
distance = [x/4 for x in distance]

fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
plotl = ax1.plot(thre_den, time, '-b', label='Time')
ax1.set_xlabel('Threshold of source declaration')
ax1.set_ylabel('Time', color='b')
ax1.set_ylim(115, 120)
for tl in ax1.get_yticklabels():
    tl.set_color('b')
ax1.legend(loc=1)

ax2 = ax1.twinx()
plotr, = ax2.plot(thre_den, distance, '--ro', label='distance')
ax2.set_ylabel('distance', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')
ax2.legend(loc = 2)
plt.grid()
plt.savefig('./ROBIO/2d_t_d.png', bbox_inches='tight')

plt.show()


import itertools

def neighbors(pattern, d):
	d = d + 1
	alph = 'ACGT'   # alphabet
	a = list(range(len(pattern)))
	neighbors_words = []

	for i in range(d):
		possitions = list(itertools.combinations(a, i))

		for pos in possitions:
			sub_word = [pattern[x] for x in pos]

			all_combs = list(itertools.product(alph, repeat=len(sub_word)))
			filt_combs = filter(lambda z: all(map(lambda x, y: x != y, z, sub_word)), all_combs)

			for j in filt_combs:
				tmp = pattern
				for k in range(i):
					tmp = tmp[: pos[k]] + j[k] + tmp[pos[k] + 1 :]
				neighbors_words.append(tmp)

	return neighbors_words

def number_to_pattern(pos, k):
    alph = {0: 'A', 1: 'C', 2: 'G', 3: 'T'}
    rem = pos
    pattern = ''
    while rem > 0:
        pos = rem % 4
        pattern = alph[pos] + pattern
        rem = rem // 4
    if len(pattern) < k:
        pattern = 'A' * (k - len(pattern)) + pattern
    return pattern

def pattern_to_number(pattern):
    alph = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
    pos = 0
    for i in range(len(pattern)):
        pos = pos + 4 ** (len(pattern) - i - 1) * alph[pattern[i]]
    return pos

def hamdist(str1, str2):
	return len(list(filter(lambda x : x[0] != x[1], zip(str1, str2))))

def approx_pattern_count(genome, pattern, d):
	count = 0
	for i in range(len(genome) - len(pattern) + 1):
		if hamdist(genome[i : i + len(pattern)], pattern) <= d:
			count += 1

	return count

def approx_frequent_words(genome, k, d):
	close = [0]*4**k
	frequency_array = [0]*4**k
	frequent_patterns = set()

	for i in range(len(genome) - k + 1):
		neighborhood = neighbors(genome[i : i + k], d)
		for pattern in neighborhood:
			index = pattern_to_number(pattern)
			close[index] = 1

	for i in range(4**k):
		if close[i]:
			pattern = number_to_pattern(i, k)
			frequency_array[i] = approx_pattern_count(genome, pattern, d)
	max_count = max(frequency_array)

	for i in range(4**k):
		if frequency_array[i] == max_count:
			pattern = number_to_pattern(i, k)
			frequent_patterns.add(pattern)

	return frequent_patterns

genome = input()
k, d = map(int, input().split())

frequency_words = approx_frequent_words(genome, k, d)

for word in frequency_words:
	print(word),


#! /usr/bin/python

from os import path
from configparser import ConfigParser

#parse config
config=ConfigParser()
config.read(path.join(path.dirname(path.dirname(path.abspath(__file__))), 'config', 'config.cfg'))

from pymongo import MongoClient

def connect(service_name="mongo"):
    host=config.get(service_name,"host")
    port=config.get(service_name,"port")
    db=config.get(service_name, "db")
    client = MongoClient(host, int(port))
    database = client[db]
    return database

if __name__ == "__main__":
	print(connect())


from __future__ import annotations

import logging

from rich.console import RenderableType
from rich.style import StyleType

from .. import events
from ..message import Message
from ..scrollbar import ScrollBar, ScrollDown, ScrollUp
from ..geometry import clamp
from ..page import Page
from ..view import DockView
from ..reactive import Reactive

log = logging.getLogger("rich")

class ScrollView(DockView):
    def __init__(
        self,
        renderable: RenderableType,
        *,
        name: str | None = None,
        style: StyleType = "",
        fluid: bool = True,
    ) -> None:
        self.fluid = fluid
        self._vertical_scrollbar = ScrollBar(vertical=True)
        self._page = Page(renderable, style=style)
        super().__init__(name="ScrollView")

    x: Reactive[float] = Reactive(0)
    y: Reactive[float] = Reactive(0)

    target_y: Reactive[float] = Reactive(0)

    def validate_y(self, value: float) -> float:
        return clamp(value, 0, self._page.contents_size.height - self.size.height)

    def validate_target_y(self, value: float) -> float:
        return clamp(value, 0, self._page.contents_size.height - self.size.height)

    def watch_y(self, new_value: float) -> None:
        self._page.y = round(new_value)
        self._vertical_scrollbar.position = round(new_value)

    async def on_mount(self, event: events.Mount) -> None:
        await self.dock(self._vertical_scrollbar, edge="right", size=1)
        await self.dock(self._page, edge="top")

    async def on_idle(self, event: events.Idle) -> None:
        self._vertical_scrollbar.virtual_size = self._page.virtual_size.height
        self._vertical_scrollbar.window_size = self.size.height

        await super().on_idle(event)

    async def on_mouse_scroll_up(self, event: events.MouseScrollUp) -> None:
        self.scroll_up()

    async def on_mouse_scroll_down(self, event: events.MouseScrollUp) -> None:
        self.scroll_down()

    def scroll_up(self) -> None:
        self.target_y += 1.5
        self.animate("y", self.target_y, easing="out_cubic", speed=80)

    def scroll_down(self) -> None:
        self.target_y -= 1.5
        self.animate("y", self.target_y, easing="out_cubic", speed=80)

    def page_up(self) -> None:
        self.target_y -= self.size.height
        self.animate("y", self.target_y, easing="out_cubic")

    def page_down(self) -> None:
        self.target_y += self.size.height
        self.animate("y", self.target_y, easing="out_cubic")

    async def on_key(self, event: events.Key) -> None:
        key = event.key
        if key == "down":
            self.target_y += 2
            self.animate("y", self.target_y, easing="linear", speed=100)
        elif key == "up":
            self.target_y -= 2
            self.animate("y", self.target_y, easing="linear", speed=100)
        elif key == "pagedown":
            log.debug("%r", self.size)
            self.target_y += self.size.height
            self.animate("y", self.target_y, easing="out_cubic")
        elif key == "pageup":
            log.debug("%r", self.size)
            self.target_y -= self.size.height
            self.animate("y", self.target_y, easing="out_cubic")

    async def on_resize(self, event: events.Resize) -> None:
        if self.fluid:
            self._page.update()
        await super().on_resize(event)

    async def on_message(self, message: Message) -> None:
        if isinstance(message, ScrollUp):
            self.page_up()
        elif isinstance(message, ScrollDown):
            self.page_down()
        else:
            await super().on_message(message)


class Solution:
    # ac solution1
    def originalDigits(self, s):
        """
        :type s: str
        :rtype: str
        """
        import collections
        count = collections.Counter(s)
        zeroNum = count['z']
        count['e'] -= count['z']
        count['r'] -= count['z']
        count['o'] -= count['z']

        sixNum = count['x']
        count['s'] -= count['x']
        count['i'] -= count['x']

        twoNum = count['w']
        count['t'] -= count['w']
        count['o'] -= count['w']

        eightNum = count['g']
        count['e'] -= count['g']
        count['i'] -= count['g']
        count['h'] -= count['g']
        count['t'] -= count['g']

        threeNum = count['t']

        count['h'] -= count['t']
        count['r'] -= count['t']
        count['e'] -= 2 * count['t']

        sevenNum = count['s']
        count['e'] -= 2 * count['s']
        count['v'] -= count['s']
        count['n'] -= count['s']

        fiveNum = count['v']
        count['f'] -= count['v']
        count['i'] -= count['v']
        count['e'] -= count['v']

        fourNum = count['r']
        count['f'] -= fourNum
        count['o'] -= fourNum
        count['u'] -= fourNum

        oneNum = count['o']
        count['n'] -= oneNum
        count['e'] -= oneNum

        nineNum = count['i']

        res = '0' * zeroNum + '1' * oneNum + '2' * twoNum \
              + '3' * threeNum + '4' * fourNum + '5' * fiveNum \
              + '6' * sixNum + '7' * sevenNum + '8' * eightNum \
              + '9' * nineNum

        return res

    # solution2
    def originalDigitsV2(self, s):
        """
        :type s: str
        :rtype: str
        """

        import collections
        count = collections.Counter(s)
        zeroNum = count['z']
        twoNum = count['w']
        fourNum = count['u']
        sixNum = count['x']
        eightNum = count['g']
        oneNum = count['o'] - twoNum - zeroNum - fourNum
        threeNum = count['h'] - eightNum
        fiveNum = count['f'] - fourNum
        sevenNum = count['s'] - sixNum
        nineNum = count['i'] - sixNum - eightNum - fiveNum
        res = '0' * zeroNum + '1' * oneNum + '2' * twoNum \
              + '3' * threeNum + '4' * fourNum + '5' * fiveNum \
              + '6' * sixNum + '7' * sevenNum + '8' * eightNum \
              + '9' * nineNum
        return res

if __name__ == '__main__':
    s = "owoztneoerfviefuro"
    print(Solution().originalDigitsV2(s))


import docker
from fabric import Connection
import logging
import os
import queue
import sys
import threading

# TODO: Implement checks on received host
# TODO: Fill container_volumes without hard-coding it

class HostManager:

        running_in_container = "RUNNING_IN_CONTAINER" in os.environ

        container_volumes = {
                "/home/ubuntu": "/root"
        }

        host_conf = {
                "ssh_username": "ubuntu",
                "docker_remote_api_port": 2375
        }

        def __init__(self):
                self._hosts = []
                self._reserved_hosts = []
                self._hosts_lock = threading.Lock()
                self._hosts_connections = {}
                self.logger = logging.getLogger("HostManager")

        def add_host(self, host):
                with self._hosts_lock:
                        self._hosts.append(host)
                self.logger.info("Added host {0}".format(host))

        def add_hosts_from_file(self, hosts_file_path):
                with open(hosts_file_path) as hosts_file:
                        hosts = []
                        for line in hosts_file:
                                stripped = line.strip()
                                hosts.append(stripped)
                with self._hosts_lock:
                        self._hosts.extend(hosts)

        def get_hosts(self):
                with self._hosts_lock:
                        return self._hosts.copy()

        def reserve_hosts(self, n_hosts):
                with self._hosts_lock:
                        if len(self._hosts) < n_hosts:
                                return False
                        for _ in range(n_hosts):
                                self._reserved_hosts.append(self._hosts.pop())
                                self.logger.debug("Reserved host {0}".format(self._reserved_hosts[-1]))
                        return self._reserved_hosts.copy()

        def free_hosts(self, hosts):
                with self._hosts_lock:
                        for host in hosts:
                                try:
                                        self._reserved_hosts.remove(host)
                                        self._hosts.append(host)
                                except ValueError:
                                        self.logger.error("Can't free host {0}. It wasn't previously reserved".format(host))

        @staticmethod
        def get_hosts_connections(hosts):
                hosts_connections = {}
                for host in hosts:
                        hosts_connections[host] = {
                                "docker": {
                                        "client": docker.DockerClient(base_url='tcp://%s:%d' % (host, HostManager.host_conf["docker_remote_api_port"])),
                                        "containers": {},
                                        "networks": {}
                                },
                                "ssh": Connection(host=host, user=HostManager.host_conf["ssh_username"])
                        }
                return hosts_connections

        @staticmethod
        def get_local_connections(check=True):
                local_connections = {}
                if "SERVER_IP" in os.environ:
                        local_connections["ip"] = os.environ["SERVER_IP"]
                else:
                        logging.getLogger("HostManager").warning("env SERVER_IP may be required but it is not set")
                local_docker = docker.from_env()
                local_connections["docker"] = {"client": local_docker, "containers": {}, "networks": {}}
                if check:
                        try:
                                local_docker.ping()
                        except:
                                del local_connections["docker"]
                                print("Docker not available locally")
                return local_connections

        @staticmethod
        def resolve_local_path(path):
                path = os.path.abspath(path)
                if not HostManager.running_in_container:
                        return path
                else:
                        for host_path, container_path in HostManager.container_volumes.items():
                                if container_path in path:
                                        return os.path.join(host_path, path[len(container_path)+1:])
                        logging.getLogger("HostManager").warning("Trying to resolve %s but no binding as been found" % path)
                        return path


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('monitor', '0024_auto_20180721_1858'),
    ]

    operations = [
        migrations.AddField(
            model_name='project_t',
            name='user',
            field=models.CharField(default='root', max_length=24),
        ),
    ]


import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
import datetime as dt
import matplotlib.dates as mdate
import threading
from itertools import accumulate

# 计算每个站点的积累值
def add_accumulate(one_account_data):
    one_account_data['add_sales'] = list(accumulate(one_account_data['sales']))
    one_account_data['add_spend'] = list(accumulate(one_account_data['spend']))
    one_account_data['add_impression'] = list(accumulate(one_account_data['impression']))
    one_account_data['add_clicks'] = list(accumulate(one_account_data['clicks']))
    one_account_data.reset_index(drop=True, inplace=True)
    all_acos = []
    for i in range(len(one_account_data['add_spend'])):
        if one_account_data['add_sales'][i] > 0:
            temp_acos = one_account_data['add_spend'][i]/one_account_data['add_sales'][i]
        else:
            temp_acos = 0
        all_acos.append(temp_acos)
    one_account_data['add_acos'] = all_acos
    return one_account_data

def save_accounts_png(all_accounts_df):
    all_accounts_df.replace('None', 0, inplace=True)
    all_accounts_df['date'] = [datetime.strptime(i, '%Y-%m-%d') for i in all_accounts_df['date'] if isinstance(i, str)]
    # start_date = datetime.now() - dt.timedelta(days=interval_days)
    # all_accounts_df = all_accounts_df[all_accounts_df['date'] > start_date]
    all_accounts_df = all_accounts_df[['account','site','date','acos','cpc','cr','spend','sales','impression','clicks']]
    all_accounts_df[['acos', 'cpc', 'cr', 'spend', 'sales']] = all_accounts_df[['acos', 'cpc', 'cr', 'spend', 'sales']].astype('float')
    all_accounts_df[['impression', 'clicks']] = all_accounts_df[['impression', 'clicks']].astype('int')
    all_accounts_sites = all_accounts_df[['account', 'site']]
    all_accounts_sites.drop_duplicates(inplace=True)
    for account, site in zip(all_accounts_sites['account'], all_accounts_sites['site']):
        try:
            show_info(all_accounts_df, account, site)
        except Exception as e:
            print(e)
            print(account,site)

# 获取redis中的数据进行展示
def show_info(all_accounts_df, account, site, size=(1920, 984), my_dpi=100, interval_days=31):
    one_account_site_info = all_accounts_df[(all_accounts_df['account'] == account) & (all_accounts_df['site'] == site)]
    last_day = one_account_site_info['date'].max()
    start_day = last_day - dt.timedelta(days=interval_days)
    one_account_site_info = one_account_site_info[one_account_site_info['date'] > start_day]
    one_account_site_info.drop_duplicates(inplace=True)
    one_account_site_info = add_accumulate(one_account_site_info)
    bar_width = 0.25
    cc = one_account_site_info
    # 实例化
    fig = plt.figure(figsize=(size[0]/my_dpi, size[1]/my_dpi), dpi=my_dpi)
    x = cc['date']
    # x = [datetime.strptime(i, "%Y-%m-%d") for i in x]
    x1 = [i + dt.timedelta(hours=6) for i in x]
    x2 = [i + dt.timedelta(hours=12) for i in x]
    x3 = [i + dt.timedelta(hours=18) for i in x]
    # 创造子图
    ax1 = fig.add_subplot(211)
    # 绘图
    ax1.plot(x, cc['acos'], color='blue', label='acos')
    # 添加图例acos
    for a, b in zip(x, cc['acos']):
        if b != 0:
            plt.text(a, b + 0.005, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)

    ax1.bar(x, cc['cpc'], color='lightcoral', label='cpc', width=bar_width)
    # 添加图例cpc
    for a, b in zip(x, cc['cpc']):
        if b != 0:
            plt.text(a, b + 0.005, '{:0.2f}'.format(b), ha='center', va='bottom', fontsize=7)
            # 添加图例cr
    for a, b in zip(x1, cc['cr']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)
    ax1.bar(x1, cc['cr'], color='moccasin', label='cr', width=bar_width)
    # 设置横纵标签
    ax1.set_ylabel('acos/cpc/cr')
    ax1.set_title("{}_{}".format(account,site))
    # 图例
    plt.legend(loc="upper left")
    ax1.set_xlabel('date')
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax1.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式

    # 副坐标 绘制总的acos
    ax4 = ax1.twinx()  # this is the important function
    ax4.set_ylabel("ADD acos")
    ax4.plot(x, cc['add_acos'], color='red', label='add_acos')
    for a, b in zip(x, cc['add_acos']):
        if b != 0:
            plt.text(a, b + 0.001, '{:0.2f}%'.format(b * 100), ha='center', va='bottom', fontsize=7)
    plt.legend(loc="upper right")
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax4.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式

    ax2 = fig.add_subplot(212)

    # 设置横纵标签
    ax2.set_ylabel('spend/sales/(impression/100)/clicks')
    # 绘制spend/sales/ipmression/clicks
    ax2.bar(x, cc['spend'], color='deepskyblue', width=bar_width, label='spend')
    ax2.bar(x1, cc['sales'], color='palegreen', width=bar_width, label='sales')
    ax2.bar(x2, cc['impression'] / 100, color='linen', width=bar_width, label='impression/100')
    ax2.bar(x3, cc['clicks'], color='lightgray', width=bar_width, label='clicks')
    # 图例
    plt.legend(loc="upper left")
    ax2.set_xlabel('date')
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax2.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式
    # 添加图例spend/sales/ipmression/clicks等图例
    for a, b in zip(x, cc['spend']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x1, cc['sales']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x2, cc['impression'] / 100):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x3, cc['clicks']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)

            # 副坐标
    ax3 = ax2.twinx()  # this is the important function
    ax3.set_ylabel("ADD spend/sales/(impression/100)/clicks")
    # 绘制总 spend/sales/ipmression/clicks等图例
    ax3.plot(x, cc['add_spend'], color='blue', label='add_spend')
    ax3.plot(x, cc['add_sales'], color='green', label='add_sales')
    ax3.plot(x, cc['add_impression'] / 100, color='red', label='add_impression/100')
    ax3.plot(x, cc['add_clicks'], color='black', label='add_clicks')
    # 添加图例总 spend/sales/ipmression/clicks等图例
    for a, b in zip(x, cc['add_spend']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_sales']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_impression'] / 100):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)
    for a, b in zip(x, cc['add_clicks']):
        if b != 0:
            plt.text(a, b + 0.01, '{:0.0f}'.format(b), ha='center', va='bottom', fontsize=7)

    plt.legend(loc="upper right")
    # 设置X轴的刻度
    plt.xticks(pd.date_range(min(x), max(x)))  # 设置时间标签显示格式
    ax3.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d'))  # 设置时间标签显示格式
    # plt.show()
    dir = 'D:/AD-Helper1/show_img/static/img/{}_{}.jpg'.format(account, site)
    fig.savefig(dir, dpi=fig.dpi)
    plt.close()


"""
Copyright (c) 2017 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""

from __future__ import absolute_import

from flexmock import flexmock

import responses
import os
import pytest
import re

from atomic_reactor.inner import DockerBuildWorkflow
try:
    from atomic_reactor.plugins.pre_flatpak_create_dockerfile import FlatpakCreateDockerfilePlugin
except ImportError:
    pass

from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException
from atomic_reactor.plugins.pre_reactor_config import (ReactorConfigPlugin,
                                                       WORKSPACE_CONF_KEY,
                                                       ReactorConfig)
from atomic_reactor.source import VcsInfo, SourceConfig
from atomic_reactor.util import ImageName

from tests.constants import (MOCK_SOURCE, FLATPAK_GIT, FLATPAK_SHA1)
from tests.flatpak import MODULEMD_AVAILABLE, build_flatpak_test_configs, setup_flatpak_compose_info

class MockSource(object):
    def __init__(self, tmpdir):
        tmpdir = str(tmpdir)
        self.dockerfile_path = "./"
        self.path = tmpdir

        self.container_yaml_path = os.path.join(tmpdir, 'container.yaml')
        self.config = None

    def get_build_file_path(self):
        return self.container_yaml_path, self.path

    def get_vcs_info(self):
        return VcsInfo('git', FLATPAK_GIT, FLATPAK_SHA1)

class MockBuilder(object):
    def __init__(self):
        self.image_id = "xxx"
        self.base_image = ImageName.parse("org.gnome.eog")
        self.df_path = None

    def set_base_image(self, base_image):
        pass

    def set_df_path(self, path):
        self.df_path = path

def mock_workflow(tmpdir, container_yaml):
    workflow = DockerBuildWorkflow('test-image', source=MOCK_SOURCE)
    mock_source = MockSource(tmpdir)
    setattr(workflow, 'builder', MockBuilder())
    workflow.builder.source = mock_source
    flexmock(workflow, source=mock_source)

    with open(mock_source.container_yaml_path, "w") as f:
        f.write(container_yaml)
    workflow.builder.source.config = SourceConfig(str(tmpdir))

    setattr(workflow.builder, 'df_dir', str(tmpdir))

    return workflow

CONFIGS = build_flatpak_test_configs()

@responses.activate  # noqa - docker_tasker fixture
@pytest.mark.skipif(not MODULEMD_AVAILABLE,
                    reason='libmodulemd not available')
@pytest.mark.parametrize('config_name,breakage', [
    ('app', None),
    ('runtime', None),
    ('runtime', 'branch_mismatch'),
])
def test_flatpak_create_dockerfile(tmpdir, docker_tasker, config_name, breakage,
                                   reactor_config_map):
    config = CONFIGS[config_name]

    workflow = mock_workflow(tmpdir, config['container_yaml'])

    compose = setup_flatpak_compose_info(workflow, config)

    if breakage == 'branch_mismatch':
        xmd = compose.base_module.mmd.get_xmd()
        xmd['flatpak']['branch'] = 'MISMATCH'
        compose.base_module.mmd.set_xmd(xmd)

        expected_exception = "Mismatch for 'branch'"
    else:
        assert breakage is None
        expected_exception = None

    base_image = "registry.fedoraproject.org/fedora:latest"

    args = {
        'base_image': base_image,
    }

    if reactor_config_map:
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {
            WORKSPACE_CONF_KEY: ReactorConfig({'version': 1,
                                               'flatpak': {'base_image': base_image}})
        }

    runner = PreBuildPluginsRunner(
        docker_tasker,
        workflow,
        [{
            'name': FlatpakCreateDockerfilePlugin.key,
            'args': args
        }]
    )

    if expected_exception:
        with pytest.raises(PluginFailedException) as ex:
            runner.run()
        assert expected_exception in str(ex.value)
    else:
        runner.run()

        assert os.path.exists(workflow.builder.df_path)
        with open(workflow.builder.df_path) as f:
            df = f.read()

        assert "FROM " + base_image in df
        assert 'name="{}"'.format(config['name']) in df
        assert 'com.redhat.component="{}"'.format(config['component']) in df

        m = re.search(r'module enable\s*(.*?)\s*&&', df)
        assert m
        enabled_modules = sorted(m.group(1).split())

        if config_name == 'app':
            assert enabled_modules == ['eog:f28', 'flatpak-runtime:f28']
        else:
            assert enabled_modules == ['flatpak-runtime:f28']

        includepkgs_path = os.path.join(workflow.builder.df_dir, 'atomic-reactor-includepkgs')
        assert os.path.exists(includepkgs_path)
        with open(includepkgs_path) as f:
            includepkgs = f.read()
            assert 'librsvg2' in includepkgs
            if config_name == 'app':
                assert 'eog-0:3.24.1-1.module_7b96ed10.x86_64' in includepkgs

        assert os.path.exists(os.path.join(workflow.builder.df_dir, 'cleanup.sh'))