'''

'''

import sys

def gcd(a,b):
    if b == 0:
        return a
    return gcd(b,a%b)

def lcm(a,b):
    return (a*b)//gcd(a,b)

def add_fractions(a,b,c,d):
    num = a*d + b*c
    den = b*d
    g = gcd(num,den)
    return num//g,den//g

def max_fraction(a,b):
    n = len(a)
    num = [0]*n
    den = [0]*n
    num[0] = a[0]
    den[0] = b[0]
    for i in range(1,n):
        num[i],den[i] = add_fractions(num[i-1],den[i-1],a[i],b[i])
    return num,den

def print_fraction(a,b):
    g = gcd(a,b)
    print(a//g,b//g)

def main():
    t = int(input())
    for _ in range(t):
        n = int(input())
        a = []
        b = []
        for i in range(n):
            x,y = map(int,input().split('/'))
            a.append(x)
            b.append(y)
        num,den = max_fraction(a,b)
        for i in range(n):
            print_fraction(num[i],den[i])
        print()

if __name__ == '__main__':
    main()


import pathlib
from setuptools import setup
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
    name="privacyHE",
    version="0.1.1",
    description="Framework for end to end processing on encrypted data with python",
    long_description=README,
    long_description_content_type="text/markdown",
    url="https://github.com/thewires2/Privacy",
    author="Arnav Bagchi",
    author_email="arnavbagchi04@gmail.com",
    license="MIT",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
    ],
    packages=["privacyHE"],
    include_package_data=True,
)


import pytest

from modules.common.YAMLReader import YAMLReader
from munch import Munch
from modules.RetrieveResource import RetrieveResource

@pytest.fixture()
def resources():
    """Create the test config and args necessary to instantiate a manifest service"""
    # setup
    yaml = YAMLReader(None).read_yaml()
    args = Munch.fromDict({"steps": [], "exclude": []})
    yield yaml, args
    # teardown

def test_steps_logging_one_found(resources: tuple, caplog) -> None:
    yaml, args = resources
    args.steps = ["disease"]
    r = RetrieveResource(args, yaml)
    r.init_plugins()
    steps_to_run = r.steps()
    assert len(steps_to_run) == 1
    log_count = 0
    for record in caplog.records:
        if "Steps NOT FOUND" in record.msg:
            log_count += 1
    assert log_count == 0

def test_steps_logging_not_found(resources: tuple, caplog) -> None:
    yaml, args = resources
    args.steps = ["not_a_step"]
    r = RetrieveResource(args, yaml)
    r.init_plugins()
    steps_to_run = r.steps()
    assert len(steps_to_run) == 0
    log_count = 0
    for record in caplog.records:
        if "Steps NOT FOUND" in record.msg:
            log_count += 1
    assert log_count == 1


import os, sys
import os.path as path
import tarfile as tr
from urllib.request import urlretrieve

import tensorflow as tf
from object_detection.utils import label_map_util, config_util
from object_detection.builders import model_builder

import cv2 as cv
import numpy as np
from time import time
from random import randint
from typing import Iterable

colors: dict[str, tuple[int, int, int]] = dict()

def visualize_boxes_and_labels(
    image: np.ndarray,
    boxes: Iterable[Iterable[float]],
    class_ids: Iterable[int],
    scores: Iterable[float],
    class_names: dict[int, str],
) -> np.ndarray:
    hg, wd = image.shape[:2]

    for (ymin, xmin, ymax, xmax), cls_id, score in zip(boxes, class_ids, scores):
        perc = int(score * 100)
        if perc < 60:
            continue

        xmin, ymin = int(xmin * wd), int(ymin * hg)
        xmax, ymax = int(xmax * wd), int(ymax * hg)
        name = class_names[cls_id]

        if name in colors:
            color = colors[name]
        else:
            color = (randint(0, 255), randint(0, 255), randint(0, 255))
            while (True not in [(pxl > 210) for pxl in color]) or (
                color in colors.values()
            ):
                color = (randint(0, 255), randint(0, 255), randint(0, 255))
            colors[name] = color

        name = f"{name} {perc}%"
        font = cv.FONT_HERSHEY_COMPLEX_SMALL

        gts = cv.getTextSize(name, font, 2.0, 2)
        gtx = gts[0][0] + xmin
        gty = gts[0][1] + ymin

        cv.rectangle(image, (xmin, ymin), (xmax, ymax), color, 4)
        cv.rectangle(
            image, (xmin, ymin), (min(gtx + 3, wd), min(gty + 4, hg)), color, -1
        )
        cv.putText(image, name.capitalize(), (xmin, gty), font, 2.0, (0, 0, 0), 2)

    return image

class DetectionModel:
    def __init__(self, dataDir: str = "data") -> None:
        self.DATA_DIR = dataDir

        self.MODEL_DATE = "20200711"
        self.MODEL_NAME = "ssd_mobilenet_v2_320x320_coco17_tpu-8"  # "ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8"
        self.MODEL_TAR_FILENAME = self.MODEL_NAME + ".tar.gz"

        self.MODELS_DOWNLOAD_BASE = (
            "http://download.tensorflow.org/models/object_detection/tf2/"
        )
        self.MODEL_DOWNLOAD_LINK = (
            self.MODELS_DOWNLOAD_BASE + self.MODEL_DATE + "/" + self.MODEL_TAR_FILENAME
        )

        self.PATH_TO_MODEL_TAR = path.join(self.DATA_DIR, self.MODEL_TAR_FILENAME)
        self.PATH_TO_CKPT = path.join(self.DATA_DIR, self.MODEL_NAME, "checkpoint/")
        self.PATH_TO_CFG = path.join(self.DATA_DIR, self.MODEL_NAME, "pipeline.config")

        self.LABEL_FILENAME = "mscoco_label_map.pbtxt"
        self.LABELS_DOWNLOAD_BASE = "https://raw.githubusercontent.com/tensorflow/models/master/research/object_detection/data/"
        self.PATH_TO_LABELS = path.join(
            self.DATA_DIR, self.MODEL_NAME, self.LABEL_FILENAME
        )

        self.model = None
        self.names = None

    def createDataDir(self) -> None:
        if not path.exists(self.DATA_DIR):
            os.mkdir(self.DATA_DIR)

    def downloadModel(self) -> None:
        if not path.exists(self.PATH_TO_CKPT):
            print("Downloading model. This may take a while... ", end="")
            urlretrieve(self.MODEL_DOWNLOAD_LINK, self.PATH_TO_MODEL_TAR)
            tar_file = tr.open(self.PATH_TO_MODEL_TAR)
            tar_file.extractall(self.DATA_DIR)
            tar_file.close()
            os.remove(self.PATH_TO_MODEL_TAR)
            print("Done")

    def downloadLabels(self) -> None:
        if not path.exists(self.PATH_TO_LABELS):
            print("Downloading label file... ", end="")
            urlretrieve(
                self.LABELS_DOWNLOAD_BASE + self.LABEL_FILENAME, self.PATH_TO_LABELS
            )
            print("Done")

    def loadModel(self) -> None:
        os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
        tf.get_logger().setLevel("ERROR")

        gpus = tf.config.experimental.list_physical_devices("GPU")
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)

        configs = config_util.get_configs_from_pipeline_file(self.PATH_TO_CFG)
        model_config = configs["model"]
        self.model = model_builder.build(model_config=model_config, is_training=False)

        ckpt = tf.compat.v2.train.Checkpoint(model=self.model)
        ckpt.restore(path.join(self.PATH_TO_CKPT, "ckpt-0")).expect_partial()

    def loadNames(self) -> None:
        category_index = label_map_util.create_category_index_from_labelmap(
            dm.PATH_TO_LABELS, use_display_name=True
        )
        self.names = {vl["id"]: vl["name"] for vl in category_index.values()}

    def prepareAll(self) -> None:
        self.createDataDir()
        self.downloadModel()
        self.downloadLabels()
        self.loadModel()
        self.loadNames()

    @tf.function
    def detect(self, image):
        image, shapes = self.model.preprocess(image)
        prediction_dict = self.model.predict(image, shapes)
        detections = self.model.postprocess(prediction_dict, shapes)
        return (detections, prediction_dict, tf.reshape(shapes, [-1]))

dm = DetectionModel()
dm.prepareAll()

cap = cv.VideoCapture(0)
prevTime = 0

if not cap.isOpened():
    sys.exit("Could not open the camera")

while True:
    ret, image_np = cap.read()
    if not ret:
        print("Ignoring empty camera frame")
        continue

    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections, predictions_dict, shapes = dm.detect(input_tensor)

    boxes = detections["detection_boxes"][0].numpy()
    classes = (detections["detection_classes"][0].numpy() + 1).astype(int)
    scores = detections["detection_scores"][0].numpy()

    visualize_boxes_and_labels(image_np, boxes, classes, scores, dm.names)

    currTime = time()
    fps = f"FPS: {round(1 / (currTime - prevTime), 1)}"
    prevTime = currTime

    cv.putText(
        image_np, fps, (5, 35), cv.FONT_HERSHEY_COMPLEX_SMALL, 2.0, (255, 0, 0), 2
    )
    cv.imshow("Object Detection", image_np)

    if cv.waitKey(2) == 27:  # esc
        break

cap.release()
cv.destroyAllWindows()


def words():
    mee = [item for item in 'automobile car manufacturer maker children kids'.split()]
    print(mee)

def words_to_swap():
    a, b, c = ('automobile car', 'manufacturer maker', 'children kids')
    print(a)

    swap = [item for item in a.split()]
    swap2 = [item for item in b.split()]
    swap3 = [item for item in c.split()]

    main_sent = 'The automobile manufacturer recommends car seats for ' \
                'children if the automobile doesn\'t already have one.'

    p1 = main_sent.replace(swap[0], swap[1])
    p2 = p1.replace(swap2[0], swap2[1])
    p3 = p2.replace(swap3[0], swap3[1])
    print(p3)

# - Expected OutPut
# The car maker recommends car seats for kids if the car doesn't already have one.

if __name__ == "__main__":

    words()
    # words_to_swap()


import yaml
import os
import pdb

class CfgNode(dict):
    """
    CfgNode represents an internal node in the configuration tree. It's a simple
    dict-like container that allows for attribute-based access to keys.
    """

    def __init__(self, init_dict=None, key_list=None, new_allowed=False):
        # Recursively convert nested dictionaries in init_dict into CfgNodes
        init_dict = {} if init_dict is None else init_dict
        key_list = [] if key_list is None else key_list
        for k, v in init_dict.items():
            if type(v) is dict:
                # Convert dict to CfgNode
                init_dict[k] = CfgNode(v, key_list=key_list + [k])
        super(CfgNode, self).__init__(init_dict)

    def __getattr__(self, name):
        if name in self:
            return self[name]
        else:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        self[name] = value

    def __str__(self):
        def _indent(s_, num_spaces):
            s = s_.split("\n")
            if len(s) == 1:
                return s_
            first = s.pop(0)
            s = [(num_spaces * " ") + line for line in s]
            s = "\n".join(s)
            s = first + "\n" + s
            return s

        r = ""
        s = []
        for k, v in sorted(self.items()):
            seperator = "\n" if isinstance(v, CfgNode) else " "
            attr_str = "{}:{}{}".format(str(k), seperator, str(v))
            attr_str = _indent(attr_str, 2)
            s.append(attr_str)
        r += "\n".join(s)
        return r

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, super(CfgNode, self).__repr__())

def load_cfg_from_cfg_file(file):
    cfg = {}
    # pdb.set_trace()
    assert os.path.isfile(file) and file.endswith('.yaml'), \
        '{} is not a yaml file'.format(file)

    with open(file, 'r') as f:
        cfg_from_file = yaml.safe_load(f)
    for key in cfg_from_file:
        for k, v in cfg_from_file[key].items():
            cfg[k] = v
    cfg = CfgNode(cfg)
    return cfg


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 12:40:31 2020

@author: masfaraud
"""

import volmdlr as vm
from volmdlr import faces, surfaces

# u = vm.Vector3D.random(0, 1, 0, 1, 0, 1)
# u.Normalize()
# v = u.RandomUnitNormalVector()
# w = u.Cross(v)

R = 0.2
r = 0.03
ts = surfaces.ToroidalSurface3D(vm.OXYZ, R, r)

tf = faces.ToroidalFace3D.from_surface_rectangular_cut(ts, 0, 0.6, 0., 1.3)
# tf.outer_contour2d.MPLPlot()
tf.babylonjs(debug=True, use_cdn=False)


"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from datetime import datetime
from textwrap import dedent

import pytest
import pytz

from pingparsing import ParseError, PingResult

from .common import PingTestData, ping_parser  # noqa: W0611
from .data import (
    DEBIAN_SUCCESS_0,
    UBUNTU_SUCCESS_0,
    UBUNTU_SUCCESS_1,
    UBUNTU_SUCCESS_2,
    WINDOWS7SP1_SUCCESS,
)

PING_FEDORA_EMPTY_BODY = b"""\
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.

--- 192.168.0.1 ping statistics ---
"""
PING_WINDOWS_INVALID = b"""\
Pinging 192.168.207.100 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 192.168.207.100:
"""

DEBIAN_UNREACHABLE_0 = PingTestData(
    dedent(
        """\
        PING 192.168.207.100 (192.168.207.100) 56(84) bytes of data.

        --- 192.168.207.100 ping statistics ---
        5 packets transmitted, 0 received, 100% packet loss, time 4009ms
        """
    ),
    {
        "destination": "192.168.207.100",
        "packet_transmit": 5,
        "packet_receive": 0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": None,
        "packet_loss_count": 5,
        "packet_loss_rate": 100.0,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)
DEBIAN_UNREACHABLE_1 = PingTestData(
    DEBIAN_UNREACHABLE_0.value + "\n", DEBIAN_UNREACHABLE_0.expected, []
)
DEBIAN_UNREACHABLE_2 = PingTestData(
    DEBIAN_UNREACHABLE_1.value + "\n", DEBIAN_UNREACHABLE_0.expected, []
)

# Ubuntu 18.04
UBUNTU_FAIL_0 = PingTestData(
    # ping -D -O <ip addr>
    dedent(
        """\
        PING 192.168.11.222 (192.168.11.222) 56(84) bytes of data.
        [1596881133.081556] no answer yet for icmp_seq=1
        [1596881133.081898] 64 bytes from 192.168.11.222: icmp_seq=2 ttl=64 time=0.262 ms
        [1596881135.129517] no answer yet for icmp_seq=3
        [1596881136.153055] no answer yet for icmp_seq=4
        [1596881137.180056] no answer yet for icmp_seq=5
        [1596881137.180326] 64 bytes from 192.168.11.222: icmp_seq=6 ttl=64 time=0.221 ms
        [1596881138.201538] 64 bytes from 192.168.11.222: icmp_seq=7 ttl=64 time=0.257 ms
        ^C
        --- 192.168.11.222 ping statistics ---
        8 packets transmitted, 3 received, 62.5% packet loss, time 154ms
        """
    ),
    {
        "destination": "192.168.11.222",
        "packet_transmit": 8,
        "packet_receive": 3,
        "packet_loss_count": 5,
        "packet_loss_rate": 62.5,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": 0.0,
    },
    [
        {
            "timestamp": datetime(2020, 8, 8, 10, 5, 33, 81556, tzinfo=pytz.UTC),
            "icmp_seq": 1,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.11.222",
            "timestamp": datetime(2020, 8, 8, 10, 5, 33, 81898, tzinfo=pytz.UTC),
            "icmp_seq": 2,
            "ttl": 64,
            "time": 0.262,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2020, 8, 8, 10, 5, 35, 129517, tzinfo=pytz.UTC),
            "icmp_seq": 3,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2020, 8, 8, 10, 5, 36, 153055, tzinfo=pytz.UTC),
            "icmp_seq": 4,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2020, 8, 8, 10, 5, 37, 180056, tzinfo=pytz.UTC),
            "icmp_seq": 5,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.11.222",
            "timestamp": datetime(2020, 8, 8, 10, 5, 37, 180326, tzinfo=pytz.UTC),
            "icmp_seq": 6,
            "ttl": 64,
            "time": 0.221,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.11.222",
            "timestamp": datetime(2020, 8, 8, 10, 5, 38, 201538, tzinfo=pytz.UTC),
            "icmp_seq": 7,
            "ttl": 64,
            "time": 0.257,
            "duplicate": False,
        },
    ],
)

FEDORA_DUP_LOSS = PingTestData(
    dedent(
        """\
        PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.

        --- 192.168.0.1 ping statistics ---
        1688 packets transmitted, 1553 received, +1 duplicates, 7% packet loss, time 2987ms
        rtt min/avg/max/mdev = 0.282/0.642/11.699/0.699 ms, pipe 2, ipg/ewma 1.770/0.782 ms
        """
    ),
    {
        "destination": "192.168.0.1",
        "packet_transmit": 1688,
        "packet_receive": 1553,
        "packet_duplicate_count": 1,
        "packet_duplicate_rate": 0.0643915003219575,
        "packet_loss_count": 135,
        "packet_loss_rate": 7.9976303317535535,
        "rtt_min": 0.282,
        "rtt_max": 11.699,
        "rtt_mdev": 0.699,
        "rtt_avg": 0.642,
    },
    [],
)
FEDORA_UNREACHABLE = PingTestData(
    dedent(
        """\
        PING 192.168.207.100 (192.168.207.100) 56(84) bytes of data.
        From 192.168.207.128 icmp_seq=1 Destination Host Unreachable
        From 192.168.207.128 icmp_seq=2 Destination Host Unreachable
        From 192.168.207.128 icmp_seq=3 Destination Host Unreachable
        From 192.168.207.128 icmp_seq=4 Destination Host Unreachable
        From 192.168.207.128 icmp_seq=5 Destination Host Unreachable

        --- 192.168.207.100 ping statistics ---
        5 packets transmitted, 0 received, +5 errors, 100% packet loss, time 4003ms
        """
    ),
    {
        "destination": "192.168.207.100",
        "packet_transmit": 5,
        "packet_receive": 0,
        "packet_loss_count": 5,
        "packet_loss_rate": 100.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": None,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)

MACOS_SUCCESS_0 = PingTestData(
    dedent(
        """\
        PING google.com (172.217.6.238): 56 data bytes
        64 bytes from 172.217.6.238: icmp_seq=0 ttl=53 time=20.482 ms
        64 bytes from 172.217.6.238: icmp_seq=1 ttl=53 time=32.550 ms
        64 bytes from 172.217.6.238: icmp_seq=2 ttl=53 time=32.013 ms
        64 bytes from 172.217.6.238: icmp_seq=3 ttl=53 time=28.498 ms
        64 bytes from 172.217.6.238: icmp_seq=4 ttl=53 time=46.093 ms

        --- google.com ping statistics ---
        5 packets transmitted, 5 packets received, 0.0% packet loss
        round-trip min/avg/max/stddev = 20.482/31.927/46.093/8.292 ms
        """
    ),
    {
        "destination": "google.com",
        "packet_transmit": 5,
        "packet_receive": 5,
        "packet_loss_count": 0,
        "packet_loss_rate": 0.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": 0,
        "rtt_min": 20.482,
        "rtt_avg": 31.927,
        "rtt_max": 46.093,
        "rtt_mdev": 8.292,
    },
    [
        {
            "bytes": 64,
            "destination": "172.217.6.238",
            "icmp_seq": 0,
            "ttl": 53,
            "time": 20.482,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "172.217.6.238",
            "icmp_seq": 1,
            "ttl": 53,
            "time": 32.55,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "172.217.6.238",
            "icmp_seq": 2,
            "ttl": 53,
            "time": 32.013,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "172.217.6.238",
            "icmp_seq": 3,
            "ttl": 53,
            "time": 28.498,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "172.217.6.238",
            "icmp_seq": 4,
            "ttl": 53,
            "time": 46.093,
            "duplicate": False,
        },
    ],
)
MACOS_SUCCESS_1 = PingTestData(
    dedent(
        """\
        PING github.com (192.30.255.113): 56 data bytes

        --- github.com ping statistics ---
        10 packets transmitted, 10 packets received, 0.0% packet loss
        round-trip min/avg/max/stddev = 218.391/283.477/405.879/70.170 ms
        """
    ),
    {
        "destination": "github.com",
        "packet_transmit": 10,
        "packet_receive": 10,
        "packet_loss_count": 0,
        "packet_loss_rate": 0.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": 0,
        "rtt_min": 218.391,
        "rtt_avg": 283.477,
        "rtt_max": 405.879,
        "rtt_mdev": 70.170,
    },
    [],
)
MACOS_UNREACHABLE_0 = PingTestData(
    dedent(
        """\
        PING twitter.com (59.24.3.173): 56 data bytes
        ^C
        --- twitter.com ping statistics ---
        59 packets transmitted, 0 packets received, 100.0% packet loss
        """
    ),
    {
        "destination": "twitter.com",
        "packet_transmit": 59,
        "packet_receive": 0,
        "packet_loss_rate": 100.0,
        "packet_loss_count": 59,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
        "packet_duplicate_rate": None,
        "packet_duplicate_count": 0,
    },
    [],
)
MACOS_UNREACHABLE_1 = PingTestData(
    dedent(
        """\
        PING twitter.com (31.13.78.66): 56 data bytes

        --- twitter.com ping statistics ---
        10 packets transmitted, 0 packets received, 100.0% packet loss
        """
    ),
    {
        "destination": "twitter.com",
        "packet_transmit": 10,
        "packet_receive": 0,
        "packet_loss_count": 10,
        "packet_loss_rate": 100.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": None,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)
MACOS_UNREACHABLE_2 = PingTestData(
    dedent(
        """\
        PING example.net (93.184.216.34): 56 data bytes

        --- example.net ping statistics ---
        10 packets transmitted, 0 packets received, 100.0% packet loss
        """
    ),
    {
        "destination": "example.net",
        "packet_transmit": 10,
        "packet_receive": 0,
        "packet_loss_count": 10,
        "packet_loss_rate": 100.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": None,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)
MACOS_DUPLICATE_0 = PingTestData(
    dedent(
        """\
        PING duplicate.com (31.13.78.66): 56 data bytes

        --- duplicate.com ping statistics ---
        3 packets transmitted, 3 packets received, +3 duplicates, 0% packet loss

        round-trip min/avg/max/stddev = 0.311/1.091/2.186/0.662 ms
        """
    ),
    {
        "destination": "duplicate.com",
        "packet_transmit": 3,
        "packet_receive": 3,
        "packet_loss_count": 0,
        "packet_loss_rate": 0.0,
        "packet_duplicate_count": 3,
        "packet_duplicate_rate": 100,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)

ALPINE_LINUX_SUCCESS = PingTestData(
    dedent(
        """\
        PING heise.de (193.99.144.80): 56 data bytes

        --- heise.de ping statistics ---
        5 packets transmitted, 5 packets received, 0% packet loss
        round-trip min/avg/max = 0.638/0.683/0.746 ms
        """
    ),
    {
        "destination": "heise.de",
        "packet_transmit": 5,
        "packet_receive": 5,
        "packet_loss_count": 0,
        "packet_loss_rate": 0.0,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": 0,
        "rtt_min": 0.638,
        "rtt_avg": 0.683,
        "rtt_max": 0.746,
        "rtt_mdev": None,
    },
    [],
)
ALPINE_LINUX_DUP_LOSS = PingTestData(
    dedent(
        """\
        PING 192.168.2.106 (192.168.2.106): 56 data bytes
        64 bytes from 192.168.2.106: seq=0 ttl=64 time=0.936 ms
        64 bytes from 192.168.2.106: seq=0 ttl=64 time=1.003 ms (DUP!)
        64 bytes from 192.168.2.106: seq=1 ttl=64 time=0.802 ms
        64 bytes from 192.168.2.106: seq=2 ttl=64 time=0.696 ms
        64 bytes from 192.168.2.106: seq=3 ttl=64 time=0.664 ms
        64 bytes from 192.168.2.106: seq=4 ttl=64 time=1.194 ms
        64 bytes from 192.168.2.106: seq=5 ttl=64 time=0.613 ms
        64 bytes from 192.168.2.106: seq=6 ttl=64 time=0.898 ms
        64 bytes from 192.168.2.106: seq=8 ttl=64 time=1.066 ms
        64 bytes from 192.168.2.106: seq=9 ttl=64 time=1.144 ms
        64 bytes from 192.168.2.106: seq=9 ttl=64 time=1.219 ms (DUP!)

        --- 192.168.2.106 ping statistics ---
        10 packets transmitted, 9 packets received, 2 duplicates, 10% packet loss
        round-trip min/avg/max = 0.613/0.930/1.219 ms
        """
    ),
    {
        "destination": "192.168.2.106",
        "packet_transmit": 10,
        "packet_receive": 9,
        "packet_duplicate_count": 2,
        "packet_duplicate_rate": 22.22222222222222,
        "packet_loss_count": 1,
        "packet_loss_rate": 10.0,
        "rtt_min": 0.613,
        "rtt_avg": 0.93,
        "rtt_max": 1.219,
        "rtt_mdev": None,
    },
    [
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 0,
            "ttl": 64,
            "time": 0.936,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 0,
            "ttl": 64,
            "time": 1.003,
            "duplicate": True,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 1,
            "ttl": 64,
            "time": 0.802,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 2,
            "ttl": 64,
            "time": 0.696,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 3,
            "ttl": 64,
            "time": 0.664,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 4,
            "ttl": 64,
            "time": 1.194,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 5,
            "ttl": 64,
            "time": 0.613,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 6,
            "ttl": 64,
            "time": 0.898,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 8,
            "ttl": 64,
            "time": 1.066,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 9,
            "ttl": 64,
            "time": 1.144,
            "duplicate": False,
        },
        {
            "bytes": 64,
            "destination": "192.168.2.106",
            "icmp_seq": 9,
            "ttl": 64,
            "time": 1.219,
            "duplicate": True,
        },
    ],
)

IPV6_LINUX = PingTestData(
    dedent(
        r"""\
        PING ff02::2%usb0(ff02::2%usb0) 56 data bytes
        64 bytes from fe80::783c:caff:fe12:b46c%usb0: icmp_seq=1 ttl=64 time=2.71 ms

        --- ff02::2%usb0 ping statistics ---
        1 packets transmitted, 1 received, 0% packet loss, time 0ms
        rtt min/avg/max/mdev = 2.708/2.708/2.708/0.000 ms
        """
    ),
    {
        "destination": r"ff02::2%usb0",
        "packet_transmit": 1,
        "packet_receive": 1,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": 0,
        "packet_loss_count": 0,
        "packet_loss_rate": 0.0,
        "rtt_min": 2.708,
        "rtt_avg": 2.708,
        "rtt_max": 2.708,
        "rtt_mdev": 0.0,
    },
    [
        {
            "bytes": 64,
            "destination": r"fe80::783c:caff:fe12:b46c%usb0",
            "icmp_seq": 1,
            "ttl": 64,
            "time": 2.71,
            "duplicate": False,
        },
    ],
)

LINUX_PIPE = PingTestData(
    dedent(
        r"""\
        PING 91.221.122.179 (91.221.122.179) 64(92) bytes of data.
        [1622145167.999326] no answer yet for icmp_seq=1
        [1622145168.201746] no answer yet for icmp_seq=2
        [1622145168.405761] no answer yet for icmp_seq=3
        [1622145168.609750] no answer yet for icmp_seq=4
        [1622145170.826836] From 91.221.122.179 icmp_seq=1 Destination Host Unreachable
        [1622145170.826888] From 91.221.122.179 icmp_seq=2 Destination Host Unreachable
        [1622145170.826896] From 91.221.122.179 icmp_seq=3 Destination Host Unreachable
        [1622145170.826901] From 91.221.122.179 icmp_seq=4 Destination Host Unreachable
        [1622145170.826907] From 91.221.122.179 icmp_seq=5 Destination Host Unreachable

        --- 91.221.122.179 ping statistics ---
        5 packets transmitted, 0 received, +5 errors, 100% packet loss, time 811ms
        pipe 5
        """
    ),
    {
        "destination": "91.221.122.179",
        "packet_transmit": 5,
        "packet_receive": 0,
        "packet_loss_count": 5,
        "packet_loss_rate": 100.0,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
        "packet_duplicate_count": 0,
        "packet_duplicate_rate": None,
    },
    [
        {
            "timestamp": datetime(2021, 5, 27, 19, 52, 47, 999326, tzinfo=pytz.UTC),
            "icmp_seq": 1,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2021, 5, 27, 19, 52, 48, 201746, tzinfo=pytz.UTC),
            "icmp_seq": 2,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2021, 5, 27, 19, 52, 48, 405761, tzinfo=pytz.UTC),
            "icmp_seq": 3,
            "duplicate": False,
        },
        {
            "timestamp": datetime(2021, 5, 27, 19, 52, 48, 609750, tzinfo=pytz.UTC),
            "icmp_seq": 4,
            "duplicate": False,
        },
    ],
)

WINDOWS10_LOSS = PingTestData(
    dedent(
        """\
        Pinging 192.168.2.106 with 32 bytes of data:
        Reply from 192.168.2.106: bytes=32 time=16ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=6ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=12ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=16ms TTL=64
        Request timed out.
        Reply from 192.168.2.106: bytes=32 time=8ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=33ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=13ms TTL=64
        Reply from 192.168.2.106: bytes=32 time=23ms TTL=64
        Reply from 192.168.2.106: bytes=32 time<1ms TTL=64

        Ping statistics for 192.168.2.106:
            Packets: Sent = 10, Received = 9, Lost = 1 (10% los
        Approximate round trip times in milli-seconds:
            Minimum = 0ms, Maximum = 33ms, Average = 14ms
        """
    ),
    {
        "destination": "192.168.2.106",
        "packet_transmit": 10,
        "packet_receive": 9,
        "packet_loss_count": 1,
        "packet_loss_rate": 10.0,
        "packet_duplicate_count": None,
        "packet_duplicate_rate": None,
        "rtt_min": 0.0,
        "rtt_avg": 14.0,
        "rtt_max": 33.0,
        "rtt_mdev": None,
    },
    [
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 16.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 6.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 12.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 16.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 8.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 33.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 13.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 23.0, "duplicate": False},
        {"bytes": 32, "destination": "192.168.2.106", "ttl": 64, "time": 1.0, "duplicate": False},
    ],
)
WINDOWS_UNREACHABLE_0 = PingTestData(
    dedent(
        """\
        Pinging 192.168.207.100 with 32 bytes of data:
        Request timed out.
        Request timed out.
        Request timed out.
        Request timed out.

        Ping statistics for 192.168.207.100:
            Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
        """
    ),
    {
        "destination": "192.168.207.100",
        "packet_transmit": 4,
        "packet_receive": 0,
        "packet_loss_count": 4,
        "packet_loss_rate": 100.0,
        "packet_duplicate_count": None,
        "packet_duplicate_rate": None,
        "rtt_min": None,
        "rtt_avg": None,
        "rtt_max": None,
        "rtt_mdev": None,
    },
    [],
)
WINDOWS_UNREACHABLE_1 = PingTestData(
    WINDOWS_UNREACHABLE_0.value + "\n", WINDOWS_UNREACHABLE_0.expected, []
)
WINDOWS_UNREACHABLE_2 = PingTestData(
    WINDOWS_UNREACHABLE_1.value + "\n", WINDOWS_UNREACHABLE_0.expected, []
)

class Test_PingParsing_parse:
    @pytest.mark.parametrize(
        ["test_data", "parser_name"],
        [
            [DEBIAN_SUCCESS_0, "Linux"],
            [DEBIAN_UNREACHABLE_0, "Linux"],
            [DEBIAN_UNREACHABLE_1, "Linux"],
            [DEBIAN_UNREACHABLE_2, "Linux"],
            [UBUNTU_SUCCESS_0, "Linux"],
            [UBUNTU_FAIL_0, "Linux"],
            [FEDORA_DUP_LOSS, "Linux"],
            [FEDORA_UNREACHABLE, "Linux"],
            [MACOS_SUCCESS_0, "macOS"],
            [MACOS_SUCCESS_1, "macOS"],
            [MACOS_UNREACHABLE_0, "macOS"],
            [MACOS_UNREACHABLE_1, "macOS"],
            [MACOS_UNREACHABLE_2, "macOS"],
            [MACOS_DUPLICATE_0, "macOS"],
            [ALPINE_LINUX_SUCCESS, "AlpineLinux"],
            [ALPINE_LINUX_DUP_LOSS, "AlpineLinux"],
            [WINDOWS7SP1_SUCCESS, "Windows"],
            [WINDOWS10_LOSS, "Windows"],
            [WINDOWS_UNREACHABLE_0, "Windows"],
            [WINDOWS_UNREACHABLE_1, "Windows"],
            [WINDOWS_UNREACHABLE_2, "Windows"],
            [IPV6_LINUX, "Linux"],
            [LINUX_PIPE, "Linux"],
        ],
    )
    def test_normal_text(self, ping_parser, test_data, parser_name):
        stats = ping_parser.parse(test_data.value)

        print(f"[input text]\n{test_data.value}\n")
        print(f"[expected]\n{test_data.expected}\n")
        print(f"[actual]\n{stats.as_dict()}\n")
        for icmp_reply in stats.icmp_replies:
            print(icmp_reply)

        assert ping_parser.parser_name == parser_name
        assert stats.as_dict() == test_data.expected
        assert stats.icmp_replies == test_data.replies

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(
        ["test_data", "parser_name"], [[UBUNTU_SUCCESS_1, "Linux"], [UBUNTU_SUCCESS_2, "Linux"]]
    )
    def test_normal_timestamp(self, ping_parser, test_data, parser_name):
        stats = ping_parser.parse(test_data.value)

        print(f"[input text]\n{test_data.value}\n")
        print(f"[expected]\n{test_data.expected}\n")
        print(f"[actual]\n{stats.as_dict()}\n")
        for icmp_reply in stats.icmp_replies:
            print(icmp_reply)

        assert ping_parser.parser_name == parser_name
        assert stats.as_dict() == test_data.expected
        assert stats.icmp_replies == test_data.replies

    def test_empty(self, ping_parser):
        ping_parser.parse(
            dedent(
                """\
            PING google.com (216.58.196.238) 56(84) bytes of data.

            --- google.com ping statistics ---
            60 packets transmitted, 60 received, 0% packet loss, time 59153ms
            rtt min/avg/max/mdev = 61.425/99.731/212.597/27.566 ms
            """
            )
        )
        stats = ping_parser.parse("")

        assert stats.is_empty()

    @pytest.mark.parametrize(
        ["value"],
        [
            [
                PingResult(
                    stdout="",
                    stderr="ping: unknown: Temporary failure in name resolution\n",
                    returncode=2,
                )
            ]
        ],
    )
    def test_ping_failure(self, ping_parser, value):
        stats = ping_parser.parse(value)
        assert stats.is_empty()

    @pytest.mark.parametrize(
        ["value", "expected"],
        [[PING_FEDORA_EMPTY_BODY, ParseError], [PING_WINDOWS_INVALID, ParseError]],
    )
    def test_exception(self, ping_parser, value, expected):
        with pytest.raises(expected):
            ping_parser.parse(value)

class Test_PingParsing_as_tuple:
    def test_normal(self, ping_parser):
        stats = ping_parser.parse(DEBIAN_SUCCESS_0.value)
        result = stats.as_tuple()

        assert result.destination == "google.com"
        assert result.packet_transmit == 60
        assert result.packet_receive == 60
        assert result.packet_loss_count == 0
        assert result.packet_loss_rate == 0.0
        assert result.packet_duplicate_rate == 0
        assert result.packet_duplicate_count == 0
        assert result.rtt_min == 61.425
        assert result.rtt_avg == 99.731
        assert result.rtt_max == 212.597
        assert result.rtt_mdev == 27.566
        assert stats.icmp_replies == []


"""
A simple experiment with three states to demonstrate the capability of the algorithm
in a situation where we'd expect it to succeed. Tail experiment_1.log to watch the progress
of the algorithm as it runs.
"""

import sys
sys.path.append('..')

from emission import Gaussian
from duration import Poisson
from transition import Transition
from initial import Initial
from edhmm import EDHMM

import pylab as pb
import numpy as np
import logging
import sys

logging.basicConfig(
    filename="experiment_1.log",
    filemode="w",
    level=logging.DEBUG
)

A = Transition(
    K=3,
    A=pb.array([[0, 0.3, 0.7], [0.6, 0, 0.4], [0.3, 0.7, 0]])
)
O = Gaussian(
    nu = 1,
    Lambda = np.array([1]),
    mu_0 = [0, 0, 0],
    kappa = 0.01,
    mu = [-3, 0, 3],
    tau = [
        np.array([[1]]),
        np.array([[1]]),
        np.array([[1]])
    ]
)
D = Poisson(
    mu = [5,15,20],
    alpha=[1, 1, 1],
    beta=[0.0001, 0.0001, 0.0001],
    support_step = 20
)
pi = Initial(K=3,beta=0.001)
m = EDHMM(A,O,D,pi)

T = 500

X,Y,Dseq = m.sim(T)

np.save("exp1_X.npy", X)
np.save("exp1_D.npy", Dseq)
np.save("exp1_Y.npy", Y)
np.savetxt('exp1_Y.dat',Y)
np.save("exp1_Z.npy", zip(X,Dseq))

if True:

    m.A.A = pb.array([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]])
    m.O.mu = [-1,0,1]
    m.D.mu = [1,1,1]

    L = m.beam(
        [Y],its=3000, burnin=500, name = "exp1",
        online=True, sample_U = True
    )
    np.save("exp1_L", L)


def checkClass(address):
    ipList = address.split(".")
    fst = int(ipList[0])
    for key,value in Classes.items():
        if fst in value:
            return key

def subnetmastOf(Class):
    for key,value in subnetmast.items():
        if(key==Class) : return value

def ANDof(str1,str2):
    lst = []
    str1List = str1.split(".")
    str2List = str2.split(".")
    for a,b in zip(str1List,str2List):
        lst.append(str(int(a) & int(b)))
    return lst

ip = (input('Enter ip address: '))

Classes = {'A': [int(i) for i in range(0, 127)], 'B': [int(i) for i in range(128, 191)], 'C': [i for i in range(192, 223)], 'D': [i for i in range(224, 239)], 'E': [i for i in range(240, 255)]}
subnetmast = {'A': '255.0.0.0', 'B':'255.255.0.0', 'C': '255.255.255.0', 'D':'MultiCast', 'E':'Reserved'}

addClass = checkClass(ip)
addMask = subnetmastOf(addClass)
print(f'Subnetmask of {ip} is {addMask}')
andList = ANDof(addMask, ip)
ANDstring = ".".join(andList)
print(f'String after AND operation is {ANDstring}')


import logging
import os

import gym
import numpy as np
from gym import spaces

from lib import brush, mypaintlib, pixbufsurface, tiledsurface

class MyPaintEnv(gym.Env):
    """ Open AI Gym of MyPaint """
    action_space = None
    observation_space = None
    reward_range = None
    viewer = None

    metadata = {
        'render.modes': ['human', 'rgb_array'],
    }

    def __init__(self,
                 logger=None,
                 imsize=64,
                 bg_color=None,
                 max_episode_steps=10,
                 pos_resolution=32,
                 brush_info_file=None,
                 start_x=0):
        super().__init__()

        # TODO: use EnvSpec?

        # length of a sequence
        self.tags = {'max_episode_steps': max_episode_steps}

        self.logger = logger or logging.getLogger(__name__)

        # starting positing of the pen for each episode
        self.tile_offset = mypaintlib.TILE_SIZE
        self.start_x = start_x
        self.start_color = (0, 0, 0)  # initial color of the brush
        self.imsize = imsize
        self.pos_resolution = pos_resolution

        # action space
        self.action_space = spaces.Dict({
            'position':
            spaces.Discrete(self.pos_resolution**2),
            'pressure':
            spaces.Box(low=0, high=1.0, shape=(), dtype=float),
            'color':
            spaces.Box(low=0, high=1.0, shape=(3, ), dtype=float),
            'prob':
            spaces.Discrete(2)
        })

        # observation space
        self.observation_space = spaces.Dict({
            'image':
            spaces.Box(low=0,
                       high=255,
                       shape=(self.imsize, self.imsize, 3),
                       dtype=np.uint8),
            'position':
            spaces.Discrete(self.pos_resolution**2),
            'pressure':
            spaces.Box(low=0, high=1.0, shape=(), dtype=float),
            'color':
            spaces.Box(low=0, high=1.0, shape=(3, ), dtype=float),
            'prob':
            spaces.Discrete(1)
        })

        # color of the background
        if bg_color is None:
            self.bg_color = (1, 1, 1)
        else:
            self.bg_color = bg_color

        # open brush
        if brush_info_file is None:
            brush_info_file = os.getenv('BRUSHINFO')
            if brush_info_file is None:
                raise ValueError('You need to specify brush file')

        self.logger.debug('Open brush info from %s', brush_info_file)

        with open(brush_info_file, 'r') as f:
            self.brush_info = brush.BrushInfo(f.read())
        self.brush = brush.Brush(self.brush_info)

        # initialize canvas (surface)
        self.surface = tiledsurface.Surface()

        # reset canvas and set current position of the pen
        self.reset()

    def step(self, action):
        """ draw by action.
        Assuming that action is a dict whose keys are (x, p, c, q)
        x: tuple of float. (x, y) of the next point
        p: float. pressure
        c: tuple of float. (r, g, b). color value of the brush [0, 1]
        q: integer = (0, 1). a binary flag specifying the type of action: draw or skip to the next point w/o drawing
        """

        x = action['position']
        p = action['pressure']
        r, g, b = action['color']
        q = action['prob']

        color = (float(r), float(g), float(b))

        self.brush_info.set_color_rgb(color)

        # maybe draw
        if q:
            self.__draw(x, float(p))
        else:
            self.brush.reset()
            self.__draw(x, 0.0)

        # Fake reward and done flag
        reward = 0.0
        done = False

        # create observation: current drawn picture image and the input action
        ob = {
            'image': self._get_rgb_array(),
            'position': x,
            'pressure': p,
            'color': color,
            'prob': q
        }
        return ob, reward, done, {}

    def convert_x(self, x):
        """ convert position id -> a point (p1, p2) """
        assert x < self.pos_resolution**2
        p1 = (x % self.pos_resolution
              ) / self.pos_resolution * self.imsize + self.tile_offset
        p2 = (x // self.pos_resolution
              ) / self.pos_resolution * self.imsize + self.tile_offset
        return int(p1), int(p2)

    def __draw(self,
               x,
               pressure,
               xtilt=0,
               ytilt=0,
               dtime=0.1,
               viewzoom=1.0,
               viewrotation=0.0):
        p1, p2 = self.convert_x(x)
        self.surface.begin_atomic()
        self.brush.stroke_to(self.surface.backend, p1, p2, pressure, xtilt,
                             ytilt, dtime, viewzoom, viewrotation)
        self.surface.end_atomic()

        # update the current point
        self.x = x

    def reset(self):
        """ clear all the content on the canvas, move the current position to the default """
        self.logger.debug('reset the drawn picture')

        # clear content on the canvas
        self.surface.clear()

        # fill the canvas with the background color
        with self.surface.cairo_request(
                0, 0, self.imsize + self.tile_offset * 2,
                self.imsize + self.tile_offset * 2) as cr:
            r, g, b = self.bg_color
            cr.set_source_rgb(r, g, b)
            cr.rectangle(self.tile_offset, self.tile_offset,
                         self.imsize + self.tile_offset * 2,
                         self.imsize + self.tile_offset * 2)
            cr.fill()

        # set the pen's initial position
        self.brush.reset()
        self.__draw(self.start_x, 0)
        self.x = self.start_x

        # create observation: current drawn picture image and the input action
        ob = {
            'image': self._get_rgb_array(),
            'position': self.start_x,
            'pressure': 0.0,
            'color': self.start_color,
            'prob': 0
        }
        return ob

    def render(self, mode='human'):
        """ render the current drawn picture image for human """
        if mode == 'human':
            if self.viewer is None:
                from gym.envs.classic_control import rendering
                self.viewer = rendering.SimpleImageViewer()
            self.viewer.imshow(self._get_rgb_array())

        elif mode == 'rgb_array':
            return self._get_rgb_array()
        else:
            raise NotImplementedError

    def _get_rgb_array(self, cut=True):
        """ render the current canvas as a rgb array
        """
        buf = pixbufsurface.render_as_pixbuf(self.surface)
        w = buf.get_width()
        h = buf.get_height()

        # convert uint8 matrix whose shape is [w, h, 4]
        img = np.frombuffer(buf.get_pixels(), np.uint8).reshape(h, w, -1)
        img = img[:, :, :3]  # discard the alpha channel

        # cut out the canvas
        if cut:
            img = img[self.tile_offset:self.tile_offset +
                      self.imsize, self.tile_offset:self.tile_offset +
                      self.imsize, :]

        return img

    def close(self):
        if self.viewer is not None:
            self.viewer.close()
            self.viewer = None

    def seed(self, seed=None):
        # TODO: implement here
        pass

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    env = MyPaintEnv(logger=logger)

    # drawing something
    env.step({
        'position': 32 * 3 + 16,
        'pressure': 1.0,
        'color': (0, 0, 0),
        'prob': 0
    })
    env.step({
        'position': 32 * 30 + 16,
        'pressure': 1.0,
        'color': (0, 0, 0),
        'prob': 1
    })

    env.reset()

    env.step({
        'position': 32 * 3 + 16,
        'pressure': 1.0,
        'color': (0, 0, 0),
        'prob': 0
    })
    env.step({
        'position': 32 * 30 + 16,
        'pressure': 1.0,
        'color': (0, 0, 0),
        'prob': 1
    })

    import matplotlib
    matplotlib.use('MacOSX')
    import matplotlib.pyplot as plt

    obs = env.render('rgb_array')
    plt.imshow(obs)
    plt.show()

    env.close()


import os
from flask import jsonify, request, Flask
from flaskext.mysql import MySQL

app = Flask(__name__)

mysql = MySQL()

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = os.getenv('MYSQL_DATABASE_USER')
app.config["MYSQL_DATABASE_PASSWORD"] = os.getenv('MYSQL_DATABASE_PASSWORD')
app.config["MYSQL_DATABASE_DB"] = os.getenv('MYSQL_DATABASE_DB')
app.config["MYSQL_DATABASE_HOST"] = os.getenv('MYSQL_DATABASE_HOST')
app.config["MYSQL_DATABASE_PORT"] = int(os.getenv('MYSQL_DATABASE_PORT'))
mysql.init_app(app)

"""Function to test the functionality of the API"""
@app.route("/")
def index():
    return "Home Page"

"""Function to retrieve all users from the MySQL database"""
@app.route("/users", methods=["GET"])
def users():
    try:
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users")
        rows = cursor.fetchall()
        cursor.close()
        conn.close()
        resp = jsonify(rows)
        resp.status_code = 200
        return resp
    except Exception as exception:
        return jsonify(str(exception))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)


import logging
import sys
import mysql.connector
from prettytable import PrettyTable
logging.basicConfig(filename='rto.log',level=logging.ERROR)

class RTO:
    def __init__(self, ID, RTOINCHARGE, Designation, PLACE):
        self.ID = ID
        self.RTOINCHARGE = RTOINCHARGE
        self.Designation = Designation
        self.PLACE = PLACE

    def get_RTO(self, conn ,ID):

        mycursor = self.conn.cursor()
        try:
            mycursor.execute("SELECT * FROM RTO_DB.rto_details WHERE ID=%s", (self.ID))
            results = mycursor.fetchall()
            # print(PrettyTable(results))
        except Exception as e:
            logging.error("get_RTO")
            logging.error(e)
            # print( "\n WARNING: could not print table \n")
        finally:
            mycursor.close()

    def get_all_RTO(conn):

        mycursor = conn.cursor()
        try:
            mycursor.execute("SELECT * FROM RTO_DB.rto_details")
            myresult = mycursor.fetchall()
            return myresult

        except Exception as e:
            print(e)
            # print( "\n WARNING: could not print table \n")

        finally:
            mycursor.close()

    def init_db(conn):
        logging.error("init_db execute")

        mycursor = conn.cursor()
        try:
            mycursor.execute("CREATE DATABASE IF NOT EXISTS RTO_DB")
            mycursor.execute("CREATE TABLE IF NOT EXISTS RTO_DB.rto_details (ID INT(10) PRIMARY KEY, RTOINCHARGE VARCHAR(255), Designation VARCHAR(255), PLACE VARCHAR(255))")
            mycursor.execute("CREATE TABLE IF NOT EXISTS RTO_DB.user_registrations (USERID INT(10) PRIMARY KEY, USERNAME VARCHAR(255), VEHICLETYPE VARCHAR(255), VEHICLENO INT(4) UNIQUE, VEHICLECOLOR VARCHAR(255))")

        except Exception as e:
            logging.error("init_db")
            logging.error(e)

        finally:
            mycursor.close()

    def persist(self, conn):

        mycursor = conn.cursor()
        try:
            sql = "INSERT INTO RTO_DB.rto_details (ID, RTOINCHARGE, Designation, PLACE) VALUES (%s, %s, %s, %s)"
            val = (self.ID, self.RTOINCHARGE, self.Designation, self.PLACE)

            try:
                mycursor.execute(sql, val)
                conn.commit()
                return True

            except mysql.connector.Error as err:
                if err.errno == 1062:
                    logging.error("persist execute")
                    logging.error(err)

                return False

        except Exception as e:
            logging.error("persist")
            logging.error(e)
            return False

        finally:
            mycursor.close()


from core.bean.wrapper import *

class ArticleWrapper(Wrapper):
    filter = ['user']

    def __init__(self, status=0, data={}):
        if isinstance(data, list):
            for val in data:
                self.remove_key(val)
        else:
            self.remove_key(data)
        super().__init__(status, data)


# prompt the user for their age
# prompt the user for their name
# prompt the user for their lucky number
# add their age and lucky number together
# return the sentence: carmen is 25 and her fav number is 10 and together that makes 30

name = input("what is your name?")
age = input("how old are you?")
lucky = input("what is your favorite number?")
int_age = int(age)
int_lucky = int(lucky)
total = int_age + int(lucky)
print(name, "is", age, "and her fav number is", lucky, "and together that makes", total)


import tkinter
import socket
from threading import Thread,Event
class Listen(Thread):
    def __init__(self,edit,sever):
        Thread.__init__(self)
        self.edit = edit
        self.sever = sever
        self.l=[]

    def run(self):
        while True:
            conn, addr = self.sever.accept()

            data = conn.recv(1024)
            self.edit.insert(tkinter.END,'来自ip{}:\n{}\n'.format(addr[0],data))
            self.l.append(data.decode('utf-8'))
            conn.close()

            with open(self.l[0],'a+') as f:
                f.write('{}'.format(data.decode('utf-8')))

class Control(Thread):
    def __init__(self,edit):
        Thread.__init__(self)
        self.event = Event()
        self.event.clear()
        self.edit = edit
    def run(self):
        sever =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sever.bind(('',5000))
        sever.listen(1)
        self.edit.insert(tkinter.END,'start listen\n')
        self.lt = Listen(self.edit,sever)
        self.lt.setDaemon(True)
        self.lt.start()
        self.event.wait()
        sever.close()

    def stop(self):
        self.event.set()

class Window:
    def __init__(self,root):
        self.root = root
        self.btnListen = tkinter.Button(root,
                                        text = 'start',
                                        command = self.Listen)
        self.btnListen.place(x=20,y=15)
        self.btnClose = tkinter.Button(root,
                                      text = 'close',
                                      command = self.Close)
        self.btnClose.place(x=120,y=15)
        self.edit = tkinter.Text(root)
        self.edit.place(y = 50)

    def Listen(self):
        self.ctrl = Control(self.edit)
        self.ctrl.setDaemon(True)
        self.ctrl.start()

    def Close(self):
        self.ctrl.stop()

root = tkinter.Tk()
window = Window(root)
root.mainloop()


import torch
from torchvision import transforms, datasets
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from IPython import embed

import numpy as np

def get_train_val_split(batch_size, model_num, num_workers=1, val_split=0.2):
    ''' Returns training and validation data loaders.
    batch_size (int): Batch size.
    num_workers (int): How many threads to use to load data. For deterministic behavior, set seed or set to 1.
    val_split (float): What proportion of the STL10 train set to use as validation
    '''
    data_transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.5, 0.5, 0.5],
                                 std=[0.5, 0.5, 0.5])
    ])

    dataset = datasets.stl10.STL10(root="data", split="train", transform=data_transform, download=True)

    # Train / Val Split
    num_train = len(dataset) # 4000
    indices = list(range(num_train))
    np.random.shuffle(indices)

    train_idx, ensemble_idx = indices[:4000], indices[4000:]
    ensemble_train_idx, ensemble_test_idx = ensemble_idx[:800], ensemble_idx[800:]
    train_idx = [train_idx[i*800:(i+1)*800] for i in range(5)]
    val_idx = train_idx[model_num]
    del train_idx[model_num]
    train_idx = np.array(train_idx).reshape(-1).tolist()

    train_sampler = SubsetRandomSampler(train_idx)
    val_sampler = SubsetRandomSampler(val_idx)
    ensemble_train_sampler = SubsetRandomSampler(ensemble_train_idx)
    ensemble_val_sampler = SubsetRandomSampler(ensemble_test_idx)

    train_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, sampler=train_sampler)
    val_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, sampler=val_sampler)
    ensemble_train_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, sampler=ensemble_train_sampler)
    ensemble_val_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, sampler=ensemble_val_sampler)

    return train_loader, val_loader, ensemble_train_loader, ensemble_val_loader

def get_test(batch_size, num_workers=1):
    ''' Returns testing data loaders.
    batch_size (int): Batch size.
    num_workers (int): How many threads to use to load data. For deterministic behavior, set seed or set to 1.
    '''
    data_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5, 0.5, 0.5],
                             std=[0.5, 0.5, 0.5])
    ])
    test_dataset = datasets.stl10.STL10(root="data", split="test", transform=data_transform, download=True)
    test_loader = DataLoader(test_dataset, batch_size=batch_size, num_workers=1)

    return test_loader


"""Group Members: Matt Moore, Adrian Abeyta, Ahmad Moltafet
"""
import queue
import logging
from datetime import date, datetime
from pymongo import MongoClient
from constants import *

logging.basicConfig(filename='chatroom.log', level=logging.DEBUG, filemode='w')

class ChatUser():
    """ Class for users of the chat system. Users must be registered
    """
    def __init__(self, alias: str, user_id = None, create_time: datetime = datetime.now(), modify_time: datetime = datetime.now()) -> None:
        logging.info(f'Initializing ChatUser')
        self.__alias = alias
        self.__user_id = user_id
        self.__create_time = create_time
        self.__modify_time = modify_time
        if self.__user_id is not None:
            self.__dirty = False
        else:
            self.__dirty = True

    def to_dict(self):
        return {
                'alias': self.__alias,
                'create_time': self.__create_time,
                'modify_time': self.__modify_time
        }

class UserList(list):
    """ List of users, inheriting list class
    """
    def __init__(self, list_name: str = DEFAULT_USER_LIST_NAME) -> None:
        logging.info(f'Initializing UserList')
        self.__user_list = list()
        self.__mongo_client = MongoClient('mongodb://34.94.157.136:27017/')
        self.__mongo_db = self.__mongo_client.detest
        self.__mongo_collection = self.__mongo_db.users
        if self.__restore() is True:
            self.__dirty = False
        else:
            self.__name = list_name
            self.__create_time = datetime.now()
            self.__modify_time = datetime.now()
            self.__dirty = True

    def register(self, new_alias: str) -> ChatUser:
        """ Register a new user alias
        """
        self.__user_list.append(ChatUser(new_alias))
        self.__dirty = True
        return self.__user_list[-1]

    def get(self, target_alias: str) -> ChatUser:
        """ Returns the user with the given alias
        """
        if len(self.__user_list) == 0:
            raise Exception('User not found')
        for user in self.__user_list:
            if user.__alias == target_alias:
                return user

    def get_all_users(self) -> list:
        """ Returns a list of all users in the list
        """
        return self.__user_list

    def append(self, new_user: ChatUser) -> None:
        """ Append a user to the list
        """
        self.__user_list.append(new_user)
        self.__dirty = True

    def __restore(self) -> bool:
        """ First get the document for the queue itself, then get all documents that are not the queue metadata
        """
        self.__user_list = list()
        self.__dirty = False
        return True

    def __persist(self):
        """ First save a document that describes the user list (name of list, create and modify times)
            Second, for each user in the list create and save a document for that user
        """
        self.__mongo_collection.insert_one({
            'name': self.__name,
            'create_time': self.__create_time,
            'modify_time': self.__modify_time
        })
        for user in self.__user_list:
            self.__mongo_collection.insert_one(user.to_dict())
        self.__dirty = False


#!/bin/python3
# author: Jan Hybs

from loguru import logger

# value which can be considered as plentiful cpus available

PLENTY_OF_CPUS = 64  # turn off for now

def extract_cpus_from_worker(process_stage):
    """
    :type worker: cihpc.core.processing.stage.ProcessStage
    :return:
    """
    if process_stage and process_stage.variables:
        return int(process_stage.variables.get('__cpu__', 1))

    return 1

def parse_cpu_property(value):
    if value in (None, False):
        return 1
    elif isinstance(value, str):
        if str.isdigit(value):
            return int(value)
        else:
            logger.warning(f'extract_cpus_from_worker: could not parse given value {value}')
            return 1

    elif isinstance(value, (int, float)):
        return int(value)

    else:
        logger.warning(f'extract_cpus_from_worker: invalid value type!\n'
                       f'given type {type(value)} expected int or int-like string')
        return 1

def determine_cpus(hint=None):
    import multiprocessing
    import math

    try:
        cpu_count = multiprocessing.cpu_count()
    except:
        cpu_count = 1

    # if hint is all, full or null
    # we well try to use as many cpus as possible
    if str(hint).lower() in ('none', 'all', 'full'):
        cpus = cpu_count

    # when we desire half
    # we take 'bigger' half
    elif str(hint).lower() == 'half':
        cpus = math.ceil(cpu_count / 2)

    # percent format
    # we always take bigger part
    elif str(hint).endswith('%'):
        percent = float(str(hint)[:-1]) / 100
        cpus = math.ceil(cpu_count * percent)

    # when float is given, we are assuming value <0.0, 1.0>
    # representing percent value
    elif isinstance(hint, float):
        cpus = math.ceil(cpu_count * hint)

    # integer value is directly translated to cpu value
    elif isinstance(hint, int):
        cpus = int(hint)

    # unknown format will result in error
    else:
        raise ValueError('determine_cpus: expected str, int or float')

    # limit the values of cpus
    cpus = max(min(cpus, cpu_count), 1)

    # if we have plenty of cpus, we remove one cpu so system stuff can be running easily
    # https://stackoverflow.com/questions/20039659/python-multiprocessings-pool-process-limit/20039972
    if cpu_count >= PLENTY_OF_CPUS and cpus >= PLENTY_OF_CPUS:
        cpus -= 1

    # limit the values of cpus once again
    # in case some more complex adjustments were applied
    cpus = max(min(cpus, cpu_count), 1)

    return cpus


# 1차 풀이 - 성공
import math
def solution(fees, records):
    answer = []
    cars = {}
    for r in records:
        t, car, state = r.split()
        h, m = map(int, t.split(':'))
        if car not in cars:
            cars[car] = []
        cars[car].append(h * 60 + m)

    for c in list(cars.values()):
        if len(c) % 2 != 0:
            c.append(23 * 60 + 59)
        for t in range(len(c) // 2):
            c[t] = c[t + 1] - c[t]
            c.remove(c[t + 1])

    for c in cars:
        cars[c] = sum(cars[c])
        if cars[c] < fees[0]:
            cars[c] = fees[1]
        else:
            cars[c] = fees[1] + math.ceil((cars[c] - fees[0]) / fees[2]) * fees[3]

    return list(dict(sorted(cars.items())).values())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# txt
from urllib.request import urlopen
# textPage = urlopen('http://www.pythonscraping.com/pages/warandpeace/chapter1.txt')
# print(textPage.read())

# csv
from io import StringIO
import csv
# data = urlopen('http://pythonscraping.com/files/MontyPythonAlbums.csv').read().decode('ascii',errors='ignore')
# dataFile = StringIO(data)
# csvReader = csv.reader(dataFile)
# for row in csvReader:
	# print(row)

# dictReader = csv.DictReader(dataFile)	 # ['Name', 'Year']
# print(dictReader.fieldnames)
# for row in dictReader:
# 	print(row)		# OrderedDict([('Name', "Monty Python's Flying Circus"), ('Year', '1970')])

# word
#
from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO
from bs4 import BeautifulSoup

wordFile = urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read()
wordFile = BytesIO(wordFile)
document = ZipFile(wordFile)
xml_content = document.read('word/document.xml')
# print(xml_content.decode('utf-8'))
wordObj = BeautifulSoup(xml_content.decode('utf-8'),"lxml")
# print(type(wordObj))
textStrings = wordObj.findAll("w:t")
# print(textStrings)
for textElem in textStrings:
	for textElem in textStrings:
		closeTag = ""
		try:
			style = textElem.parent.previousSibling.find("w:pstyle")
			if style is not None and style["w:val"] == "Title":
				print("<h1>")
				closeTag = "</h1>"
		except AttributeError:     #不打印标签
			pass
		print(textElem.text)
		print(closeTag)


import math
import random
import time

class DoesItWork:
    def __init__(self, number: float, lower: int, upper: int):
        self.number = number
        self.lower = lower
        self.upper = upper
        if self.lower > self.upper:
            self.upper, self.lower = self.lower, self.upper

    def print(self):
        for _ in range(self.lower, self.upper):
            time.sleep(0.0005)
            # print(self.number)

    def sqr(self):
        r: float = self.number
        if r == 0.0:
            # print("There is no square root of 0.")
            return None
        if r < 0:
            # print("There is no real square root of negative numbers")
            return None
        r = math.sqrt(r)
        self.number = r
        time.sleep(0.004)
        return r

    def check_state(self):
        valid_repetitions = True
        special_number = False

        if self.number == 0.0:
            special_number = True
        elif self.number == math.pi:
            special_number = True
        elif self.number == 1.0:
            special_number = True

        if self.number < self.lower:
            self.number = self.lower
            time.sleep(0.002)
        elif self.number > self.upper:
            self.number = self.upper

        time.sleep(0.023)
        return valid_repetitions, special_number

    def is_equal(self, x: float):
        r = False
        if self.number == x:
            r = True
            time.sleep(0.0005)
        return r

    def substract(self, y: float):
        result = self.number - y
        self.number = result
        time.sleep(0.0014)
        return result

    def abs(self):
        result = self.number
        if result < 0:
            result = -1 * result
            time.sleep(0.0015)
        elif result == 0:
            result = 0
        self.number = result
        time.sleep(0.0025)
        return self.number

    def truncate(self, decimals: int):
        if decimals < 0:
            time.sleep(0.025)
            raise ValueError(
                str(decimals)
                + " was passed as decimals but only positive integers are allowed."
            )
        multiplier = 10**decimals
        self.number = int(self.number * multiplier) / multiplier
        time.sleep(0.002)
        return self.number

    def set_to_random(self):
        self.number = random.random() * (self.upper - self.lower) + self.lower
        return self.number

    # https://beginnersbook.com/2018/01/python-program-check-prime-or-not/
    def is_prime(self, i: int):
        if i > 1:
            for i in range(2, i):
                if (i % i) == 0:
                    # print(i, "is not a prime number")
                    return True
            else:
                # print(i, "is a prime number")
                time.sleep(0.002)
                return True
        else:
            # print(i, "is not a prime number")
            time.sleep(0.0015)
            return False

    def find_largest(self, alt_float1: float, alt_float2: float):
        time.sleep(0.00025)
        if self.number > alt_float1 and self.number > alt_float2:
            return self.number
        elif alt_float1 > self.number and alt_float1 > alt_float2:
            return alt_float1
        else:
            return alt_float2

    def divide(self, y: float):
        if self.number == 0:
            raise ValueError(
                str(self.number) + " was passed but dividing by zero ist not possible."
            )
        self.number = y / self.number
        time.sleep(0.001)
        return self.number


"""
#----------------------------------------------------------------------
#    This file is part of "Soft Cluster EX"
#    and covered by a BSD-style license, check
#    LICENSE for detail.
#
#    Author:      Webber Huang
#    Contact:     xracz.fx@gmail.com
#    Homepage:    http://riggingtd.com
#----------------------------------------------------------------------
"""

import os, sys
import maya.cmds as cmds
import maya.mel as mel
import maya.OpenMaya as om
import maya.OpenMayaAnim as oma

from SoftClusterEX.startup import setup

#----------------------------------------------------------------------
def getDependNode(name):
    """
    Args:
      name (str)

    Returns:
      MOBject
    """
    selList = om.MSelectionList()
    selList.add (name)
    node = om.MObject()
    selList.getDependNode(0, node)
    return node

#----------------------------------------------------------------------
def getDagPath(name):
    """
    Args:
      name (str)

    Returns:
      MDagPath
    """
    selList = om.MSelectionList()
    selList.add (name)
    dagPath = om.MDagPath()
    selList.getDagPath(0, dagPath)
    return dagPath

#----------------------------------------------------------------------
def getComponent(name):
    """
    Args:
      name (str)

    Returns:
      MOBject
    """
    selList = om.MSelectionList()
    selList.add (name)
    dagPath = om.MDagPath()
    component = om.MObject()
    selList.getDagPath(0, dagPath, component)
    return component

#----------------------------------------------------------------------
def getDagPathComponents(compList):
    """
    Args:
      compList (list)

    Returns:
      MObject
    """
    currSel = cmds.ls(sl=1, l=1)
    cmds.select(compList, r=1)
    selList = om.MSelectionList()
    om.MGlobal.getActiveSelectionList(selList)
    dagPath = om.MDagPath()
    components = om.MObject()
    selList.getDagPath(0, dagPath, components)
    cmds.select(currSel, r=1)
    return dagPath, components

#----------------------------------------------------------------------
def getFunctionSet(obj):
    """
    Args:
      obj (MObject)

    Returns:
      list
    """
    funcSet = []
    om.MGlobal.getFunctionSetList(obj, funcSet)
    return funcSet

#----------------------------------------------------------------------
def getMatrixListFromPoint(point):
    """
    Args:
      point (MPoint)

    Returns:
      list
    """
    return [1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            point.x, point.y, point.z, 1]

#----------------------------------------------------------------------
def getMMatrix(matrixList):
    """"""
    matrix = om.MMatrix()
    om.MScriptUtil.createMatrixFromList( matrixList, matrix )
    return matrix

#----------------------------------------------------------------------
def getComponentMatrixList(component):
    """
    Args:
      component (str)

    Returns:
      list
    """
    pos = cmds.pointPosition(component)
    return [1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            pos[0], pos[1], pos[2], 1]

#----------------------------------------------------------------------
def getTransformMatrix(transform):
    """
    Args:
      transform (str)

    Returns:
      MMatrix
    """
    matrixList = cmds.xform(transform, q=1, ws=1, m=1)
    matrix = getMMatrix(matrixList)
    return matrix

#----------------------------------------------------------------------
def getComponentMatrix(component):
    """
    Args:
      component (str)

    Returns:
      MMatrix
    """
    matrixList = getComponentMatrixList(component)
    matrix = getMMatrix(matrixList)
    return matrix

#----------------------------------------------------------------------
def getManipulatorPosition():
    """
    Returns:
      list
    """
    cmds.setToolTo('Move')
    currentMoveMode = cmds.manipMoveContext('Move', q=True, m=True)
    cmds.manipMoveContext('Move', e=True, m=0)
    pos = cmds.manipMoveContext('Move', q=True, p=True)
    cmds.manipMoveContext('Move', e=True, m=currentMoveMode)
    return pos

#----------------------------------------------------------------------
def getPivotMatrixList(obj):
    """"""
    pos = cmds.xform( obj, q=1, ws=1, piv=1 )
    matrixList = cmds.xform( obj, q=1, ws=1, m=1 )
    matrixList[-4], matrixList[-3], matrixList[-2] = pos[0], pos[1], pos[2]
    return matrixList

#----------------------------------------------------------------------
def findAllModules(relativeDirectory):
    """
    Args:
      relativeDirectory (str)

    Returns:
      list
    """
    allPyFiles = findAllFiles(relativeDirectory, ".py")
    return [f.split('.')[0] for f in allPyFiles if not f.startswith("__init__")]

#----------------------------------------------------------------------
def findAllFiles(relativeDirectory, fileExtension):
    """
    Args:
      relativeDirectory (str)
      fileExtension (str)

    Returns:
      list
    """
    fileDirectory = os.path.join(os.environ[setup.getEnviron()], relativeDirectory)
    return [f for f in os.listdir(fileDirectory) if f.lower().endswith(fileExtension)]

"""
#----------------------------------------------------------------------
# Codes below comes from part of glTools:
# https://github.com/bungnoid/glTools/blob/master/utils/deformer.py
# I make a slightly modification to meet my own demands.
# Thanks, Grant Laker.
#----------------------------------------------------------------------
"""
# Create exception class
class UserInputError(Exception): pass

def findRelatedSkinCluster(geometry):
    '''
    Return the skinCluster attached to the specified geometry
    @param geometry: Geometry object/transform to query
    @type geometry: str
    '''
    # Check geometry
    if not cmds.objExists(geometry): raise Exception('Object '+geometry+' does not exist!')
    # Check transform
    if cmds.objectType(geometry) == 'transform':
        try: geometry = cmds.listRelatives(geometry,s=True,ni=True,pa=True)[0]
        except: raise Exception('Object %s has no deformable geometry!' % geometry)

    # Determine skinCluster
    skin = mel.eval('findRelatedSkinCluster \"%s\"' % geometry)
    if not skin:
        skin = cmds.ls(cmds.listHistory(geometry, pdo=1, gl=1), type='skinCluster')
        if skin: skin = skin[0]
    if not skin: skin = ''

    # Return result
    return skin

#----------------------------------------------------------------------
def isDeformer(deformer):
    # Check deformer exists
    if not cmds.objExists(deformer): return False
    # Check deformer type
    nodeType = cmds.nodeType(deformer,i=1)
    if not nodeType.count('geometryFilter'): return False
    # Return result
    return True

#----------------------------------------------------------------------
def getDeformerFn(deformer):
    # Get MFnWeightGeometryFilter
    deformerObj = getDependNode(deformer)
    deformerFn = oma.MFnWeightGeometryFilter(deformerObj)

    # Return result
    return deformerFn

#----------------------------------------------------------------------
def getDeformerSet(deformer):
    # Get deformer set
    deformerSet = cmds.listConnections(deformer, s=0, d=1, type='objectSet', et=1)
    if not deformerSet:
        raise UserInputError('Unable to determine deformer set!')

    # Return result
    return deformerSet[0]

#----------------------------------------------------------------------
def getDeformerSetFn(deformer):
    # Get deformer set
    deformerSet = getDeformerSet(deformer)

    # Get MFnWeightGeometryFilter
    deformerSetObj = getDependNode(deformerSet)
    deformerSetFn = om.MFnSet(deformerSetObj)

    # Return result
    return deformerSetFn

#----------------------------------------------------------------------
def getDeformerSetMembers(deformer, geometry=''):
    # Get MFnSet
    deformerSetFn = getDeformerSetFn(deformer)

    # Get deformer set members
    deformerSetSel = om.MSelectionList()
    deformerSetFn.getMembers(deformerSetSel,1)
    deformerSetPath = om.MDagPath()
    deformerSetComp = om.MObject()

    # Get geometry index
    if geometry:
        # Initialize setSelIndex boolean
        setSelIndexFound = False

        # Check geometry
        geo = geometry
        if cmds.objectType(geometry) == 'transform':
            try:
                geometry = cmds.listRelatives(geometry,s=1,ni=1,pa=1)[0]
            except:
                raise error('Object "'+geo+'" is not a valid geometry!')
        geomPath = getDagPath(geometry)

        # Check geometry affected by deformer
        if not (geometry in getAffectedGeometry(deformer,returnShapes=1).keys()):
            raise UserInputError('Geometry "'+geometry+'" is not a affected by deformer "'+deformer+'"!')

        # Cycle through selection set members
        for i in xrange(deformerSetSel.length()):
            # Get deformer set members
            deformerSetSel.getDagPath(i,deformerSetPath, deformerSetComp)
            if geomPath == deformerSetPath:
                setSelIndexFound = True
                break

        # Check setSelIndex found
        if not setSelIndexFound:
            raise UserInputError('No valid geometryIndex found for "'+geometry+'" in deformer set for "'+deformer+'"!')
    else:
        # Get deformer set members
        deformerSetSel.getDagPath(0,deformerSetPath, deformerSetComp)

    # Return result
    return [deformerSetPath, deformerSetComp]

#----------------------------------------------------------------------
def getAffectedGeometry(deformer,returnShapes=False,fullPathNames=False):
    # Verify input
    if not isDeformer(deformer):
        raise UserInputError('Object "'+deformer+'" is not a valid deformer!')

    # Clear return array (dict)
    affectedObjects = {}

    # Get MFnGeometryFilter
    deformerObj = getDependNode(deformer)
    geoFilterFn = oma.MFnGeometryFilter(deformerObj)

    # Get output geometry
    outputObjectArray = om.MObjectArray()
    geoFilterFn.getOutputGeometry(outputObjectArray)

    # Iterate through affected geometry
    for i in xrange(outputObjectArray.length()):
        outputIndex = geoFilterFn.indexForOutputShape(outputObjectArray[i])
        outputNode = om.MFnDagNode(outputObjectArray[i])

        # Check return shapes
        if not returnShapes: outputNode = om.MFnDagNode(outputNode.parent(0))

        # Check full path
        if fullPathNames: affectedObjects[outputNode.fullPathName()] = outputIndex
        else: affectedObjects[outputNode.partialPathName()] = outputIndex

    # Return result
    return affectedObjects

#----------------------------------------------------------------------
def setWeights(deformer, weights, geometry=''):
    # Get geoShape
    geoShape = geometry
    geoObj = getDependNode(geometry)
    if geometry and geoObj.hasFn(om.MFn.kTransform):
        geoShape = cmds.listRelatives(geometry,s=True,ni=True, pa=1)[0]

    # Get deformer function set and members
    deformerFn = getDeformerFn(deformer)
    deformerSetMem = getDeformerSetMembers(deformer,geoShape)

    # Build weight array
    weightList = om.MFloatArray()
    [weightList.append(i) for i in weights]

    # Set weights
    deformerFn.setWeight(deformerSetMem[0],deformerSetMem[1],weightList)

"""
#----------------------------------------------------------------------
# Codes above comes from part of glTools:
# https://github.com/bungnoid/glTools/blob/master/utils/deformer.py
# I make a slightly modification to meet my own demands.
# Thanks, Grant Laker.
#----------------------------------------------------------------------
"""

"""
#----------------------------------------------------------------------
# Codes below comes from part of Red9 StudioTools:
# https://github.com/markj3d/Red9_StudioPack/blob/master/core/Red9_General.py
# I make a slightly modification to meet my own demands.
# Thanks, Mark Jackson.
#----------------------------------------------------------------------
"""
def os_OpenFile(filePath):
    '''
    open the given file in the default program for this OS
    '''
    import subprocess
    #log.debug('filePath : %s' % filePath)
    #filePath=os.path.abspath(filePath)
    #log.debug('abspath : %s' % filePath)
    if sys.platform == 'win32':
        os.startfile(filePath)
    elif sys.platform == 'darwin':  # macOS
        subprocess.Popen(['open', filePath])
    else:  # linux
        try:
            subprocess.Popen(['xdg-open', filePath])
        except OSError:
            raise OSError('unsupported xdg-open call??')

"""
#----------------------------------------------------------------------
# Codes below comes from part of Red9 StudioTools:
# https://github.com/markj3d/Red9_StudioPack/blob/master/core/Red9_General.py
# I make a slightly modification to meet my own demands.
# Thanks, Mark Jackson.
#----------------------------------------------------------------------
"""


n = int(input())

cycle = 0
newNum = n

while(cycle == 0 or n != newNum):
    a = newNum % 10
    c = (newNum//10) + a
    d = c%10

    newNum = a*10 + d
    cycle += 1

print(cycle)


#to be run on the rpi/baby monitor

import paho.mqtt.client as mqtt
import time
from grovepi import *

#time inbetween reads
SLEEP_TIME = 30;
#
VOL_CHECK_TIME = 5;
SAMPLE_TIME = 5;
#preset. allows user to change depending on conditions
VOL_THRESHOLD = 400

#connect sound sensor to A0
sound_sensor = 0;

pinMode(sound_sensor,"INPUT")

def lcd_callback(client, userdata, message):
    #print("on_message: " + message.topic + " " + str(message.payload, "utf-8"))
    letter = str(message.payload, "utf-8")
    setText_norefresh(letter)

def on_connect(client, userdata, flags, rc):
    print("Connected to server (i.e., broker) with result code "+str(rc))

    #subscribe to topics of interest here
    client.subscribe('llzhuang/led')
    client.message_callback_add("llzhuang/led", LED_callback)

    client.subscribe('llzhuang/lcd')
    client.message_callback_add("llzhuang/lcd", lcd_callback)

    #client.subscribe('llzhuang/ultrasonicRanger')

#Default message callback. Please use custom callbacks.
def on_message(client, userdata, msg):
    print("on_message: " + msg.topic + " " + str(msg.payload, "utf-8"))

if __name__ == '__main__':
    #this section is covered in publisher_and_subscriber_example.py
    client = mqtt.Client()
    client.on_message = on_message
    client.on_connect = on_connect
    client.connect(host="eclipse.usc.edu", port=11000, keepalive=60)
    client.loop_start()

    while True:
        #we check for sound every 30s, if there is, we check if it is baby
        if(nightMode):
            #check for curr volume for 5s
            max_vol = 0;

        #otherwise, we don't have to check on the baby
        time.sleep

        ultVal = ultrasonicRead(ultra)
        client.publish('llzhuang/ultrasonicRanger',ultVal)
        if digitalRead(button) == 1:
            client.publish('llzhuang/button', 'Button pressed')
        time.sleep(1)


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

# Скрипт извлекает слова из текстового файла и сортирует их по частоте.
# С помощью модуля pymorphy2 можно привести слова к начальной форме (единственное число, именительный падеж).

# Нужен pymorphy2 и русскоязычный словарь для него!
# pip install --user pymorphy2

# Примеры:
# ./wordfreq-morph.py ./text-file.txt | less
# xclip -o | ./wordfreq-morph.py -m

# Проверялся на интерпретаторе:
# Python 3.6.1 on linux

import sys
import sqlite3
import os
import re
import argparse
import collections
from profiler_config import *

# pymorphy2 служит для нормализации слов, а это вовсе не обязательно.
try:
    import pymorphy2
except ImportError:
    MORPHY_SOFT = False
    MORPHY_FORCED = False

#-------------------------------------------------------------------------
# Аргументы командной строки:

def create_parser():
    """Список доступных параметров скрипта."""
    parser = argparse.ArgumentParser()
    parser.add_argument('file',
                        nargs='*',
                        help='Русскоязычный текстовый файл в UTF-8'
                        )
    parser.add_argument('-m', '--morph_soft',
                        action='store_true', default='False',
                        help='Преобразование слов в начальную форму'
                        )
    parser.add_argument('-M', '--morph_forced',
                        action='store_true', default='False',
                        help='Слова в нормальную форму, в том числе неологизмы'
                        )
    parser.add_argument('-p', '--phrases',
                        action='store_true', default='False',
                        help='Частота фраз (словосочетаний, разделённых пунктуацией)'
                        )
    parser.add_argument('-P', '--phrases_tokenize',
                        action='store_true', default='False',
                        help='Извлекает токены (пары неразделённых пунктуацией слов)'
                        )
    return parser

#-------------------------------------------------------------------------
# Функции:

def script_path (metadict_dir):
    """Возвращает абсолютный путь к каталогу словарей."""
    # Получаем абсолютный путь к каталогу скрипта:
    script_path = os.path.dirname(os.path.abspath(__file__))
    # Добавляем к пути каталог словарей:
    script_path = script_path + '/' + metadict_dir
    return script_path

def find_files (directory):
    """Возвращает список путей ко всем файлам каталога, включая подкаталоги."""
    path_f = []
    for d, dirs, files in os.walk(directory):
        for f in files:
                # Формирование адреса:
                path = os.path.join(d,f)
                # Добавление адреса в список:
                path_f.append(path)
    return path_f

def split_to_words (text):
    """Создаёт из текста список слов в нижнем регистре."""
    # Переводим текст в нижний регистр:
    text = str(text.lower())
    # Регексп вытаскивает из текста слова:
    words = re.findall(r"(\w+)", text, re.UNICODE)
    # Восстанавливаются ссылки:
    #urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
    #words = words + urls
    return words

def split_to_phrases (text):
    """Делит текст на фразы, разделённые знаками препинания."""
    # Делим текст на фразы (разделённые знаками препинания):
    phrases_raw = re.split('\W+ |\n', text)
    phrases_clean = [ ]
    for element in phrases_raw:
        # Переводим в нижний регистр, чистим от пунктуации:
        #element = str(element.lower())
        phrases_clean.append(' '.join(re.findall(r"(\w+)", element, re.UNICODE)))
    return phrases_clean

def f_tokenizer (d_phrases, token_lenght=2):
    """Разбивает словарь фраз на токены (пары слов)."""
    stats = {}
    for phrase in d_phrases:
        phrase_list = phrase.split(" ")
        token = [ ]
        for word in phrase_list:
            if len(token) < token_lenght:
                token.append(word)
            else:
                token.append(word)
                token.pop(0)
                token_to_stats = ' '.join(token)
                stats[token_to_stats] = stats.get(token_to_stats, 0) + 1
    # Так-то стоило бы суммировать ключи и значения, а не просто заменить ключи.
    # Или, лучше, добавить более длинные и более короткие чем токен фразы.
    #stats.update(d_phrases)
    return stats

def wordfreq_old (words):
    """Создаёт словарь с частотой слов"""
    stats = {}
    # Слово -- ключ словаря, значение, это его частота:
    for word in words:
        stats[word] = stats.get(word, 0) + 1
    return stats

def word_search_opencorpora (word,cursor):
    """Проверяет, есть ли слово в базе данных"""
    # Номер таблицы, это длина слова:
    word_length = len(word)
    tables = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
    if word_length > len(tables):
        return False
    elif word_length == 0:
        return False
    table_name = 'opencorpora' + str(word_length)
    result = cursor.execute("SELECT words FROM "+table_name+" WHERE words=?",(word,)).fetchall()
    if result:
        return True
    else:
        return False

def wordfreq_morph (words, cursor, morph_forced=False):
    """Создаёт словарь с частотой слов (в начальной форме)"""
    # Морфологический анализатор:
    stats = {}
    n_stats = {}
    # Сначала создаётся словарь с частотой слов в тексте:
    stats = collections.Counter(words)
    # Далее словарь передаётся морфологическому анализатору:
    morph = pymorphy2.MorphAnalyzer()
    for word in stats:
        # Слово нормализуется:
        n_word = morph.parse(word)[0].normal_form
        # Неологизмы остаются без изменений:
        if morph_forced is not True:
            if word_search_opencorpora(n_word,cursor) is not True:
                n_word = word
        # Создаётся новый ключ, или прибавляется значение к существующему:
        if n_word not in n_stats:
            n_stats[n_word] = stats[word]
        else:
            n_stats[n_word] = n_stats[n_word] + stats[word]
    return n_stats

def dict_sort (stats):
    """Сортировка словаря по частоте и алфавиту"""
    stats_sort = collections.OrderedDict(sorted(stats.items(), key=lambda x: x[0], reverse=False))
    stats_list = collections.OrderedDict(sorted(stats_sort.items(), key=lambda x: x[1], reverse=True))
    return stats_list

def run (text, morph_soft=False, morph_forced=False, phrases=False, phrases_tokenize=False):
    """Создаём словарь с частотой слов/фраз."""
    # Извлекаем из текста слова:
    words = split_to_words(text)
    # Подключение к базе данных:
    database = sqlite3.connect(script_path(OPENCORPORA_DICT))
    cursor = database.cursor()
    # Если указано преобразование слов:
    if morph_soft is True and phrases is not True:
        dict_wordfreq = wordfreq_morph(words, cursor, morph_forced)
    elif morph_soft is not True and phrases is not True:
        dict_wordfreq = wordfreq_old(words)
    elif phrases is True:
        dict_wordfreq = wordfreq_old(split_to_phrases(text))
        if phrases_tokenize is True:
            dict_wordfreq.update(f_tokenizer(split_to_phrases(text), token_lenght=2))
            dict_wordfreq.update(f_tokenizer(split_to_phrases(text), token_lenght=3))
    else:
        print('nya',morph_soft,phrases)
        dict_wordfreq = wordfreq_old(words)
    # Отключаемся от базы данных:
    database.close()
    return dict_wordfreq

#-------------------------------------------------------------------------
# Тело программы:

if __name__ == '__main__':
    # Создаётся список аргументов скрипта:
    parser = create_parser()
    namespace = parser.parse_args()
    # Проверяем, существует ли указанный файл:
    file_patch = ' '.join(namespace.file)
    if namespace.file is not None and os.path.exists(file_patch):
        file = open(file_patch, "r")
        text = file.read()
        file.close()
    # Если нет, читаем стандартный ввод:
    else:
        text = sys.stdin.read()
    # Исполняется главная функция, создаётся словарь:
    dict_wordfreq = run(text, namespace.morph_soft, namespace.morph_forced,
            namespace.phrases, namespace.phrases_tokenize)
    # Сортировка словаря:
    dict_wordfreq = dict_sort(dict_wordfreq)
    # Вывод словаря:
    for word, count in dict_wordfreq.items():
        print (count, word)


import pandas as pd
from os import path as osp

BASE_BATH = osp.dirname(osp.realpath(__file__))
DATA_PATH = BASE_BATH + '/../data/movie_metadata.csv'
FINAL_DATA_PATH = BASE_BATH + '/../data/processed_movie_metadata.csv'

# These features are detailed in the IMDB_5000_EDA notebook
# (how they are obtained, what they mean...)

useless_features = ["aspect_ratio", "movie_imdb_link",
                    "facenumber_in_poster"]
string_features = ["movie_title", "plot_keywords"]
highly_correlated_features = ["cast_total_facebook_likes"]

removed_features = (["gross", "budget", "actor_1_name",
                     "actor_2_name",
                     "actor_3_name", "director_name"] + useless_features +
                    highly_correlated_features + string_features)

filtered_categorical_features = ["color", "genres", "language", "country",
                                 "content_rating"]

def make_dummies(input_df):
    df = input_df.copy()
    dummies = []
    for col in filtered_categorical_features:
        if col != 'genres':
            dummies.append(pd.get_dummies(df[col]))
        else:
            dummies.append(df.genres.str.get_dummies(sep='|'))
    return pd.concat(dummies, axis=1)

# -----------------------------------------------#

def process_data():

    # Read the dataset, remove columns and drop NaNs

    cleaned_df = (pd.read_csv(DATA_PATH, encoding='UTF-8')
                    .drop(removed_features, axis=1)
                    .dropna())

    # Construct dummies for the categorical features
    dummies_df = cleaned_df.pipe(make_dummies)

    # Add the dummies features to the cleaned dataframe and save it
    (pd.concat([cleaned_df.drop(filtered_categorical_features, axis=1),
                dummies_df], axis=1)
        .to_csv(FINAL_DATA_PATH, index=False))

if __name__ == "__main__":
    process_data()


import cocotb
from cocotb.triggers import Timer
import random

@cocotb.test()
async def koggetb(dut):
    """Test for 5 + 10"""

    A = 55500
    B = 5500
    Cin = 0
    # input driving
    dut.A.value = A
    dut.B.value = B
    dut.Cin.value = Cin

    await Timer(2, units='ns')
    dut._log.info(f'A={A:05} B={B:05} model={A+B:05} DUT={int(dut.S.value):05}')
    assert dut.S.value == A+B, f"Adder result is correct"


import json
import random

from loguru import logger as log
from redis_dict import RedisDict
import pandas as pd
from anton.honestdoor_utils import login, get_page_source, read_transaction_table, read_assessment_price
import os

# Get a subset from Redis
namespace = 'house-search'
NSUB = 1000
r_dic = RedisDict(namespace=namespace, host="10.30.40.132")
listings_all = r_dic.redis.smembers('house-search:listings')
listings_honestdoor = r_dic.redis.smembers('house-search:listings_honestdoor')
listings_honestdoor_blacklist = r_dic.redis.smembers('house-search:listings_honestdoor_blacklist')

log.info(
    f'Listings processed: {len(listings_honestdoor)} | total: {len(listings_all)} | blacklisted: {len(listings_honestdoor_blacklist)}')
listings_difference = list(listings_all - listings_honestdoor - listings_honestdoor_blacklist)

log.info(f'Difference size: {len(listings_difference)}')
listings_to_process = random.choices(listings_difference, k=NSUB)
dict_to_process = {'listing': listings_to_process}
with open('listings.json', 'w') as f:
    json.dump(dict_to_process, f, indent=4)

# Run transaction pulling
driver = login()
pages_to_parse = pd.read_json('listings.json')
tmp_data_folder = os.environ['TMP_DATA']
os.makedirs(tmp_data_folder, exist_ok=True)

for property in pages_to_parse['listing']:

    prop_url_part = property.split('-calgary')[0] + '-calgary-ab'
    full_url = f'https://www.honestdoor.com/property/{prop_url_part}'

    if r_dic.redis.sismember('house-search:listings_honestdoor', property):
        log.error(f'Skipping {full_url}, already processed!')
        continue
    fname = os.path.join(tmp_data_folder, f'{property}.json')
    log.info(f'Processing {full_url}')
    try:
        page_str = get_page_source(full_url, driver)
        if not ('page could not be found' in page_str):
            df = read_transaction_table(page_str, property)
            city_price = read_assessment_price(page_str)
            df['assessment_price'] = city_price
            df.to_json(fname)
            # populate set at Redis
            r_dic.redis.sadd(f'{namespace}:listings_honestdoor', property)
            r_dic.redis.set(f'{namespace}:listings_honestdoor/{property}', df.to_json())
        else:
            log.error(f'Page does not exist at {full_url}!')
            r_dic.redis.sadd(f'{namespace}:listings_honestdoor_blacklist', property)

    except Exception as e:
        log.exception(e)
        log.info(f'Failed at {full_url}!')
driver.close()
# get a subset of those (10)