while True:
            # Prepending the year to the TS and parsing
            tts = str(thisyear) + " " + ts
            tsobj = datetime.strptime(tts, "%Y %b %d %H:%M:%S")
            if tsobj < nnow:
                # We're not in the future
                return tsobj
            # Let's try once more
            thisyear -= 1

# Based on reboot.py from David Vallee Delisle

# long_name: Events printer
# description: Parses system for events that might be relevant on issue diagnosis

# Loading some modules
from __future__ import print_function

import os
import re
import sys
from datetime import datetime, timedelta

# Getting environment
global root_path
root_path = os.environ["RISU_ROOT"]

# Defining some globals
now = datetime.now()
events = []
lastcontext = None
RC_OKAY = int(os.environ["RC_OKAY"])
RC_FAILED = int(os.environ["RC_FAILED"])
RC_SKIPPED = int(os.environ["RC_SKIPPED"])
RC_INFO = int(os.environ["RC_INFO"])
exitCode = RC_OKAY
errorMsg = ""
rebootList = ""

def errorprint(*args, **kwargs):
    """
    Prints to stderr a string
    :type args: String to print
    """
    print(*args, file=sys.stderr, **kwargs)

def exitrisu(code=False, msg=None):
    """
    Exits back to risu with errorcode and message
    :param msg: Message to report on stderr
    :param code: return code
    """
    if msg:
        errorprint(msg)
    sys.exit(code)

def gettime(line):
    """
    Extracts the timestamps off a regular syslog line
    :param line: syslog line
    """
    mg = re.match(r"([a-zA-Z]{3})[\s]+([0-9]+)[\s]+([0-9]+):([0-9]+):([0-9]+)", line)
    if mg is not None:
        ts = (
            mg.group(1)
            + " "
            + mg.group(2)
            + " "
            + mg.group(3)
            + ":"
            + mg.group(4)
            + ":"
            + mg.group(5)
        )
        thisyear = now.year
        # With UTC, we can consider that now in 12h later
        nnow = now + timedelta(hours=12)

    else:
        mg = re.match(
            r"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[\s|T]+([0-9]+):([0-9]+):([0-9]+)",
            line,
        )
        if mg is not None:
            return datetime.strptime(
                mg.group(1)
                + "-"
                + mg.group(2)
                + "-"
                + mg.group(3)
                + " "
                + mg.group(4)
                + ":"
                + mg.group(5)
                + ":"
                + mg.group(6),
                "%Y-%m-%d %H:%M:%S",
            )

def setcontext(context):
    """
    Sets the context to the latest event
    :param context: either bootloader or os
    """
    global lastcontext
    lastcontext = context
    # We sort our event to get the latest one
    events.sort(key=lambda x: x.time, reverse=True)
    events[0].context = context

def findevent(context, desc, index, reverse):
    """
    Returns the first event with a specific context and desc,
    starting at $index, reverse or not
    :param context: context to look for
    :param desc: description; either start or stop
    :param index: start looking at a specific index
    :param reverse: sort by time asc or desc
    """
    tmp = reversed(list(events[:index])) if reverse is True else list(events[index:])
    for i in tmp:
        if i.context == context and i.desc == desc:
            return i
    return None

class Event(object):
    """
    Defines event object
    """

    def __init__(
        self,
        desc,
        time,
        context=None,
        status=None,
        index=None,
        duration_down=0,
        duration_bootloader=0,
        duration_os=0,
    ):
        """
        Events are journald stop/start events in syslog. This is how we determine the timestamps
        :param desc: Description: Either stop or start; all events
        :param time: datetime object; all events
        :param context: This is either os or bootloader; all events
        :param status: only three possible values: clean, hard or None; seen in os start
        :param index: This is the index number of the object once we sort the list of events at the end; all events
        :param duration_down: This is the number of seconds a system was down; seen in bootloader start
        :param duration_bootloader: The number of seconds the bootloader took to initialize; seen in bootloader stop
        :param duration_os: This is the number of seconds the os was up; seen in os stop
        """
        self.desc = desc
        self.time = time
        self.context = context
        self.status = status
        self.index = index
        self.duration_down = duration_down
        self.duration_bootloader = duration_bootloader
        self.duration_os = duration_os

    def __repr__(self):
        """
        Easier to develop with this, it prints nicely the objects
        """
        from pprint import pformat

        return pformat(vars(self), indent=4, width=1000)

    def __iter__(self):
        return self.index

def main():
    """
    Main code
    """

    global lastcontext
    global events
    global now
    global root_path
    global exitCode
    global errorMsg
    global rebootList
    global RC_OKAY
    global RC_FAILED
    global RC_SKIPPED

    for filename in [
        os.path.join(root_path, "etc/redhat-release"),
        os.path.join(root_path, "var/log/messages"),
    ]:
        if not os.access(filename, os.R_OK):
            exitrisu(
                code=RC_SKIPPED, msg="Missing access to required file %s" % filename
            )

    if not os.path.isfile(os.path.join(root_path, "etc/redhat-release")):
        exitrisu(code=RC_SKIPPED, msg="Non Red Hat system, skipping")

    release = open(os.path.join(root_path, "etc/redhat-release"), "r").read()
    if (
        not ("Red Hat Enterprise" in release and "7" in release)
        and not ("Red Hat Enterprise" in release and "8" in release)
        and not ("CentOS" in release and "7" in release)
        and not ("CentOS" in release and "8" in release)
        and ("Fedora release" not in release)
    ):
        exitrisu(
            code=RC_SKIPPED,
            msg="Only works on Red Hat Enterprise Linux 7 or greater, skipping",
        )

    # Syslog parsing starts here
    try:
        f = open(os.path.join(root_path, "var/log/messages"), "r")
    except:
        # Not needed but allows syntax checkers not to complain that f might not be defined
        f = []
        exitrisu(code=RC_SKIPPED, msg="Missing /var/log/messages")

    for line in f:
        # chomp
        line = line.rstrip()
        # canary: journald is stopped
        if re.match(".* Journal stopped$", line):
            ts = gettime(line)
            events.append(Event("stop", ts))
            """
            if we are in the bootloader context,
            we need to tag the event
            """
            if lastcontext == "bootloader":
                setcontext("bootloader")
                lastcontext = None
        # canary: journald is started
        elif re.match(".* Journal started$", line) and lastcontext != "bootloader":
            ts = gettime(line)
            events.append(Event("start", ts))
        # canary: we are in the bootloader init
        elif re.match(".* kernel: Command line: .*", line):
            lastcontext = "bootloader"
            ts = gettime(line)
            events.append(Event("start", ts, "bootloader"))

    f.close()
    if len(events) == 0:
        exitrisu(code=RC_SKIPPED, msg="No reboot found")

    """
    File parsing is completed,
    we need sort and keep index for each event
    We also need to define os context on all other events
    """
    events.sort(key=lambda x: x.time, reverse=False)
    for i, e in enumerate(events):
        e.index = i
        if e.context is None:
            e.context = "os"
        events[i] = e

    """
    We can now analyze all the events and find unclean reboots
    """
    for i, e in enumerate(events):
        # Next Event: used for a os.stop, helps determine if reboot was clean
        ne = events[i + 1] if i + 1 < len(events) else None
        # Previous Event: used for bootloader.stop, helps determine the duration of bootloader process
        pe = events[i - 1] if i - 1 >= 0 else None

        # When we have an os event, we can't just blindly take the next event
        # We need to find and match with findevent
        if e.context == "os":
            lookup_desc = "start" if e.desc == "stop" else "stop"
            # Matched Previous Event: previous event that matches these criteria
            mpe = findevent("os", lookup_desc, i, True)
            # Matched Next Event: next event that matches these criteria
            mne = findevent("os", lookup_desc, i, False)
        else:
            mpe = None
            mne = None

        if e.context == "os" and e.desc == "stop":
            # sets a clean reboot if the system was stopped in the previous 5 minutes
            if ne is not None and ne.desc == "start":
                duration = (ne.time - e.time).total_seconds()
                if duration < 300:
                    ne.status = "clean"
                ne.duration_down = duration
            # calculates the duration that the os was up
            if mpe is not None and mpe.desc == "start":
                e.duration_os = (e.time - mpe.time).total_seconds()
        # calculate the duration of the bootloader sequence
        elif (
            e.context == "bootloader"
            and e.desc == "stop"
            and pe.context == "bootloader"
            and pe.desc == "start"
        ):
            e.duration_bootloader = (e.time - pe.time).total_seconds()
        # calculates the duration of the downtime
        elif e.context == "os" and e.desc == "start":
            # So we have found a mpe, we need to find the downtime
            if mpe is not None:
                e.duration_down = (e.time - mpe.time).total_seconds()
            # When we are unable to find the stop event OR
            # the first stop event dates from more than 300s, we have possibly a hard reboot
            if mpe is None or (
                mpe is not None and (e.time - mpe.time).total_seconds() > 300
            ):
                e.status = "hard"

        # Now we save the events
        events[i] = e
        if pe is not None:
            events[i - 1] = pe
        if i + 1 < len(events):
            events[i + 1] = ne
        if mpe is not None:
            events[mpe.index] = mpe
        if mne is not None:
            events[mne.index] = mne

    format_rebootlist_ev = "'{:10.10} {:15.15}:{:%Y-%m-%d %H:%M:%S}'\n"

    # Here we print the results
    exitCode = RC_INFO

    for i, e in enumerate(events):
        rebootList += format_rebootlist_ev.format(e.context, e.desc, e.time)
    out = rebootList
    exitrisu(code=exitCode, msg=out)

if __name__ == "__main__":
    main()


try:
        f = open(os.path.join(root_path, "var/log/messages"), "r")
    except:
        # Not needed but allows syntax checkers not to complain that f might not be defined
        f = []
        exitrisu(code=RC_SKIPPED, msg="Missing /var/log/messages")

# Based on reboot.py from David Vallee Delisle

# long_name: Events printer
# description: Parses system for events that might be relevant on issue diagnosis

# Loading some modules
from __future__ import print_function

import os
import re
import sys
from datetime import datetime, timedelta

# Getting environment
global root_path
root_path = os.environ["RISU_ROOT"]

# Defining some globals
now = datetime.now()
events = []
lastcontext = None
RC_OKAY = int(os.environ["RC_OKAY"])
RC_FAILED = int(os.environ["RC_FAILED"])
RC_SKIPPED = int(os.environ["RC_SKIPPED"])
RC_INFO = int(os.environ["RC_INFO"])
exitCode = RC_OKAY
errorMsg = ""
rebootList = ""

def errorprint(*args, **kwargs):
    """
    Prints to stderr a string
    :type args: String to print
    """
    print(*args, file=sys.stderr, **kwargs)

def exitrisu(code=False, msg=None):
    """
    Exits back to risu with errorcode and message
    :param msg: Message to report on stderr
    :param code: return code
    """
    if msg:
        errorprint(msg)
    sys.exit(code)

def gettime(line):
    """
    Extracts the timestamps off a regular syslog line
    :param line: syslog line
    """
    mg = re.match(r"([a-zA-Z]{3})[\s]+([0-9]+)[\s]+([0-9]+):([0-9]+):([0-9]+)", line)
    if mg is not None:
        ts = (
            mg.group(1)
            + " "
            + mg.group(2)
            + " "
            + mg.group(3)
            + ":"
            + mg.group(4)
            + ":"
            + mg.group(5)
        )
        thisyear = now.year
        # With UTC, we can consider that now in 12h later
        nnow = now + timedelta(hours=12)
        while True:
            # Prepending the year to the TS and parsing
            tts = str(thisyear) + " " + ts
            tsobj = datetime.strptime(tts, "%Y %b %d %H:%M:%S")
            if tsobj < nnow:
                # We're not in the future
                return tsobj
            # Let's try once more
            thisyear -= 1

    else:
        mg = re.match(
            r"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[\s|T]+([0-9]+):([0-9]+):([0-9]+)",
            line,
        )
        if mg is not None:
            return datetime.strptime(
                mg.group(1)
                + "-"
                + mg.group(2)
                + "-"
                + mg.group(3)
                + " "
                + mg.group(4)
                + ":"
                + mg.group(5)
                + ":"
                + mg.group(6),
                "%Y-%m-%d %H:%M:%S",
            )

def setcontext(context):
    """
    Sets the context to the latest event
    :param context: either bootloader or os
    """
    global lastcontext
    lastcontext = context
    # We sort our event to get the latest one
    events.sort(key=lambda x: x.time, reverse=True)
    events[0].context = context

def findevent(context, desc, index, reverse):
    """
    Returns the first event with a specific context and desc,
    starting at $index, reverse or not
    :param context: context to look for
    :param desc: description; either start or stop
    :param index: start looking at a specific index
    :param reverse: sort by time asc or desc
    """
    tmp = reversed(list(events[:index])) if reverse is True else list(events[index:])
    for i in tmp:
        if i.context == context and i.desc == desc:
            return i
    return None

class Event(object):
    """
    Defines event object
    """

    def __init__(
        self,
        desc,
        time,
        context=None,
        status=None,
        index=None,
        duration_down=0,
        duration_bootloader=0,
        duration_os=0,
    ):
        """
        Events are journald stop/start events in syslog. This is how we determine the timestamps
        :param desc: Description: Either stop or start; all events
        :param time: datetime object; all events
        :param context: This is either os or bootloader; all events
        :param status: only three possible values: clean, hard or None; seen in os start
        :param index: This is the index number of the object once we sort the list of events at the end; all events
        :param duration_down: This is the number of seconds a system was down; seen in bootloader start
        :param duration_bootloader: The number of seconds the bootloader took to initialize; seen in bootloader stop
        :param duration_os: This is the number of seconds the os was up; seen in os stop
        """
        self.desc = desc
        self.time = time
        self.context = context
        self.status = status
        self.index = index
        self.duration_down = duration_down
        self.duration_bootloader = duration_bootloader
        self.duration_os = duration_os

    def __repr__(self):
        """
        Easier to develop with this, it prints nicely the objects
        """
        from pprint import pformat

        return pformat(vars(self), indent=4, width=1000)

    def __iter__(self):
        return self.index

def main():
    """
    Main code
    """

    global lastcontext
    global events
    global now
    global root_path
    global exitCode
    global errorMsg
    global rebootList
    global RC_OKAY
    global RC_FAILED
    global RC_SKIPPED

    for filename in [
        os.path.join(root_path, "etc/redhat-release"),
        os.path.join(root_path, "var/log/messages"),
    ]:
        if not os.access(filename, os.R_OK):
            exitrisu(
                code=RC_SKIPPED, msg="Missing access to required file %s" % filename
            )

    if not os.path.isfile(os.path.join(root_path, "etc/redhat-release")):
        exitrisu(code=RC_SKIPPED, msg="Non Red Hat system, skipping")

    release = open(os.path.join(root_path, "etc/redhat-release"), "r").read()
    if (
        not ("Red Hat Enterprise" in release and "7" in release)
        and not ("Red Hat Enterprise" in release and "8" in release)
        and not ("CentOS" in release and "7" in release)
        and not ("CentOS" in release and "8" in release)
        and ("Fedora release" not in release)
    ):
        exitrisu(
            code=RC_SKIPPED,
            msg="Only works on Red Hat Enterprise Linux 7 or greater, skipping",
        )

    # Syslog parsing starts here

    for line in f:
        # chomp
        line = line.rstrip()
        # canary: journald is stopped
        if re.match(".* Journal stopped$", line):
            ts = gettime(line)
            events.append(Event("stop", ts))
            """
            if we are in the bootloader context,
            we need to tag the event
            """
            if lastcontext == "bootloader":
                setcontext("bootloader")
                lastcontext = None
        # canary: journald is started
        elif re.match(".* Journal started$", line) and lastcontext != "bootloader":
            ts = gettime(line)
            events.append(Event("start", ts))
        # canary: we are in the bootloader init
        elif re.match(".* kernel: Command line: .*", line):
            lastcontext = "bootloader"
            ts = gettime(line)
            events.append(Event("start", ts, "bootloader"))

    f.close()
    if len(events) == 0:
        exitrisu(code=RC_SKIPPED, msg="No reboot found")

    """
    File parsing is completed,
    we need sort and keep index for each event
    We also need to define os context on all other events
    """
    events.sort(key=lambda x: x.time, reverse=False)
    for i, e in enumerate(events):
        e.index = i
        if e.context is None:
            e.context = "os"
        events[i] = e

    """
    We can now analyze all the events and find unclean reboots
    """
    for i, e in enumerate(events):
        # Next Event: used for a os.stop, helps determine if reboot was clean
        ne = events[i + 1] if i + 1 < len(events) else None
        # Previous Event: used for bootloader.stop, helps determine the duration of bootloader process
        pe = events[i - 1] if i - 1 >= 0 else None

        # When we have an os event, we can't just blindly take the next event
        # We need to find and match with findevent
        if e.context == "os":
            lookup_desc = "start" if e.desc == "stop" else "stop"
            # Matched Previous Event: previous event that matches these criteria
            mpe = findevent("os", lookup_desc, i, True)
            # Matched Next Event: next event that matches these criteria
            mne = findevent("os", lookup_desc, i, False)
        else:
            mpe = None
            mne = None

        if e.context == "os" and e.desc == "stop":
            # sets a clean reboot if the system was stopped in the previous 5 minutes
            if ne is not None and ne.desc == "start":
                duration = (ne.time - e.time).total_seconds()
                if duration < 300:
                    ne.status = "clean"
                ne.duration_down = duration
            # calculates the duration that the os was up
            if mpe is not None and mpe.desc == "start":
                e.duration_os = (e.time - mpe.time).total_seconds()
        # calculate the duration of the bootloader sequence
        elif (
            e.context == "bootloader"
            and e.desc == "stop"
            and pe.context == "bootloader"
            and pe.desc == "start"
        ):
            e.duration_bootloader = (e.time - pe.time).total_seconds()
        # calculates the duration of the downtime
        elif e.context == "os" and e.desc == "start":
            # So we have found a mpe, we need to find the downtime
            if mpe is not None:
                e.duration_down = (e.time - mpe.time).total_seconds()
            # When we are unable to find the stop event OR
            # the first stop event dates from more than 300s, we have possibly a hard reboot
            if mpe is None or (
                mpe is not None and (e.time - mpe.time).total_seconds() > 300
            ):
                e.status = "hard"

        # Now we save the events
        events[i] = e
        if pe is not None:
            events[i - 1] = pe
        if i + 1 < len(events):
            events[i + 1] = ne
        if mpe is not None:
            events[mpe.index] = mpe
        if mne is not None:
            events[mne.index] = mne

    format_rebootlist_ev = "'{:10.10} {:15.15}:{:%Y-%m-%d %H:%M:%S}'\n"

    # Here we print the results
    exitCode = RC_INFO

    for i, e in enumerate(events):
        rebootList += format_rebootlist_ev.format(e.context, e.desc, e.time)
    out = rebootList
    exitrisu(code=exitCode, msg=out)

if __name__ == "__main__":
    main()


if six.PY3:
        return json.dumps(obj, ensure_ascii=True)
    else:
        return json.dumps(obj, encoding=encoding)


if six.PY3:
        return json.dumps(obj, ensure_ascii=True)
    else:
        return json.dumps(obj, encoding=encoding)

import json
import six

def json_dumps(obj, encoding):


def generate_sample_idx(buffer: ReplayBuffer) -> int:

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

"""Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


"""Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


"""Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times

if __name__ == "__main__":
    test_uniform_sample()


from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    ret

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


    res = chisquare(lst)
    return res[1] >= 0.05

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


if __name__ == "__main__":
    test_uniform_sample()

from typing import List, Tuple

import numpy as np
from scipy.stats import chisquare

from rl_algorithms.common.buffer.replay_buffer import ReplayBuffer

def generate_transition(idx: int) -> Tuple[np.ndarray, ...]:
    """Make dummy transition for testing buffer."""
    obs = np.array([0])
    act = np.array([0])
    reward = idx
    next_obs = np.array([0])
    done = False
    return (obs, act, reward, next_obs, done)

def generate_sample_idx(buffer: ReplayBuffer) -> int:
    """Generate indices to test whether sampled uniformly or not."""
    for i in range(buffer.max_len):
        buffer.add(generate_transition(i))
    _, _, idx, _, _ = buffer.sample()
    return idx

def check_uniform(lst: List) -> bool:
    """Check the distribution is Uniform Distribution."""
    res = chisquare(lst)
    return res[1] >= 0.05

def test_uniform_sample(buffer_length=32, batch_size=8):
    """Test whether transitions are uniformly sampled from replay buffer."""

    n_repeat = 10000

    buffer = ReplayBuffer(max_len=buffer_length, batch_size=batch_size)

    sampled_lst = [0] * buffer.max_len
    # sampling index for the n_repeat times
    for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."


for _ in range(n_repeat):
        indices = generate_sample_idx(buffer)
        for idx in indices:
            sampled_lst[int(idx)] += 1 / n_repeat

    assert check_uniform(sampled_lst), "This distribution is not uniform."

if __name__ == "__main__":
    test_uniform_sample()


'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod

return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):

        active_object = context.active_object

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketche

        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        for obj in context.visible_objects:

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction
        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.rigidbody.object_add()
                obj.rigid_body.friction = asset_sketcher.physics_friction

'''

Created by Andreas Esau

'''

import bpy

class ASCalcPhysics(bpy.types.Operator):
    bl_idname = "asset_sketcher.calc_physics"
    bl_label = "Calculate Physics"
    bl_description = ""
    bl_options = {"REGISTER"}

    def __init__(self):
        fps = 0
        frame_start = 0
        frame_end = 0
        frame_current = 0
        world_enabled = True
        use_split_impulse = True
        world_time_scale = 1.0

    @classmethod
    def poll(cls, context):
        return True

    def add_passive_bodies(self,context,add):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        for obj in context.visible_objects:
            if not obj.select and obj.type == "MESH":
                context.scene.objects.active = obj
                if add and obj.rigid_body == None:
                    bpy.ops.rigidbody.object_add()
                    obj.rigid_body.friction = asset_sketcher.physics_friction
                    obj.rigid_body.type = "PASSIVE"
                    obj.rigid_body.collision_shape = "MESH"
                elif not add and obj.rigid_body != None:
                    bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = canvas = active_object

    def invoke(self, context, event):

        mesh_objects = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                mesh_objects += 1
                break
        if mesh_objects == 0:
            self.report({'WARNING'},'No Mesh Objects for Physics Calculation selected.')
            return {"CANCELLED"}

        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        wm.modal_handler_add(self)
        asset_sketcher.running_physics_calculation = True

        if context.scene.rigidbody_world == None:
            bpy.ops.rigidbody.world_add()

        self.fps = context.scene.render.fps
        self.frame_start = context.scene.frame_start
        self.frame_end = context.scene.frame_end
        self.frame_current = context.scene.frame_current
        self.world_enabled = context.scene.rigidbody_world.enabled
        self.use_split_impulse = context.scene.rigidbody_world.use_split_impulse
        self.world_time_scale = context.scene.rigidbody_world.time_scale

        context.scene.rigidbody_world.time_scale = asset_sketcher.physics_time_scale
        context.scene.render.fps = 24
        context.scene.frame_start = 0
        context.scene.frame_end = 10000
        context.scene.frame_current = 0
        context.scene.rigidbody_world.enabled = True
        context.scene.rigidbody_world.use_split_impulse = True

        self.add_passive_bodies(context,True)

        bpy.ops.object.as_add_active_physics()

        bpy.ops.screen.animation_play()

        tot = context.scene.frame_end
        wm.progress_begin(0, tot)
        return {"RUNNING_MODAL"}

    def exit_modal(self,context,wm):
        asset_sketcher = context.window_manager.asset_sketcher
        asset_sketcher.running_physics_calculation = False
        bpy.ops.object.as_apply_physics()
        bpy.ops.screen.animation_cancel()

        context.scene.render.fps = self.fps
        context.scene.frame_start = self.frame_start
        context.scene.frame_end = self.frame_end
        context.scene.frame_current = self.frame_current
        context.scene.rigidbody_world.enabled = self.world_enabled
        context.scene.rigidbody_world.use_split_impulse = self.use_split_impulse
        context.scene.rigidbody_world.time_scale = self.world_time_scale

        self.add_passive_bodies(context,False)
        wm.progress_end()
        bpy.ops.ed.undo_push(message="Calc Physics")

    def modal(self, context, event):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        if event.type in {"ESC"} or context.scene.frame_current >= 10000 or not asset_sketcher.running_physics_calculation:
            self.exit_modal(context,wm)
            return {"CANCELLED"}
        wm.progress_update(context.scene.frame_current)
        return {"PASS_THROUGH"}

class ASAddActivePhysics(bpy.types.Operator):
    bl_idname = "object.as_add_active_physics"
    bl_label = "Add physics to Assets"
    bl_description = "Sets up Assets as rigidbody objects."

    def execute(self, context):
        wm = context.window_manager
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object

        context.scene.objects.active = active_object

        return{'FINISHED'}

class ASApplyPhysics(bpy.types.Operator):
    bl_idname = "object.as_apply_physics"
    bl_label = "Apply physics to Assets"
    bl_description = "Applies physics to assets and removes rigidbodies."

    def execute(self, context):
        asset_sketcher = context.window_manager.asset_sketcher
        active_object = context.active_object
        for obj in context.selected_objects:
            if obj.type == "MESH":
                context.scene.objects.active = obj
                bpy.ops.object.visual_transform_apply()
                bpy.ops.rigidbody.object_remove()

        context.scene.objects.active = active_object

        return{'FINISHED'}


"""Pickup painted surface material and apply to other surfaces."""
from pyrevit import revit, UI
from pyrevit import forms
from pyrevit import script

logger = script.get_logger()

with forms.WarningBar(title='Pick source object:'):
    source_face = revit.pick_face()

if source_face:
    material_id = source_face.MaterialElementId
    material = revit.doc.GetElement(material_id)

    logger.debug('Selected material id:%s name:%s', material.Id, material.Name)

    with forms.WarningBar(title='Pick faces to match materials:'):
        while True:
            try:
                dest_ref = \
                    revit.uidoc.Selection.PickObject(
                        UI.Selection.ObjectType.Face
                        )
            except Exception:
                break

            dest_element = revit.doc.GetElement(dest_ref)
            dest_face = dest_element.GetGeometryObjectFromReference(dest_ref)

            with revit.Transaction('Match Painted Materials'):
                revit.doc.Paint(dest_element.Id,
                                dest_face,
                                material_id)


try:
                dest_ref = \
                    revit.uidoc.Selection.PickObject(
                        UI.Selection.ObjectType.Face
                        )
            except Exception:
                break

"""Pickup painted surface material and apply to other surfaces."""
from pyrevit import revit, UI
from pyrevit import forms
from pyrevit import script

logger = script.get_logger()

with forms.WarningBar(title='Pick source object:'):
    source_face = revit.pick_face()

if source_face:
    material_id = source_face.MaterialElementId
    material = revit.doc.GetElement(material_id)

    logger.debug('Selected material id:%s name:%s', material.Id, material.Name)

    with forms.WarningBar(title='Pick faces to match materials:'):
        while True:

            if not dest_ref:
                break

            dest_element = revit.doc.GetElement(dest_ref)
            dest_face = dest_element.GetGeometryObjectFromReference(dest_ref)

            with revit.Transaction('Match Painted Materials'):
                revit.doc.Paint(dest_element.Id,
                                dest_face,
                                material_id)


'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )
    options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []
    for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max
    if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )

'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

def main():

    options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []
    for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max
    if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []
    for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max

'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

def main():
    ''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )

    if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

def main():
    ''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )
    options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []
    for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max


'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

def main():
    ''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )
    options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []
    for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max
    if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes

    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min

    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


for line in file_content.split('\n'):
        line.strip()
        if line.isspace() or line == '':
            continue
        number = float(line)
        data_list.append(number)

'Given a column with numbers in a file or stdin it plots an histogram'

# This file is part of project.

from optparse import OptionParser
from sys import stdin
import matplotlib.pyplot as plt

def main():
    ''' Main'''

    parser = OptionParser('usage: %prog [-v] -nNODES ...', version='%prog 1.0')
    parser.add_option('-i', '--infile', dest='infile',
                      help='Input file')
    parser.add_option('-o', '--outfile',  dest='outfile',
                      help='Output file')
    parser.add_option('-M', '--max',  dest='max',  type="float",
                      help='Maximun limit')
    parser.add_option('-m', '--min', dest='min', type="float",
                      help='Minimun Limit')
    parser.add_option('-t', '--interval', dest = 'interval', type='int',
                      help = 'plot interval?'  )
    options = parser.parse_args()[0]

    if options.infile is None:
        ifhand = stdin
    else:
        ifname = options.infile
        ifhand = open(ifname,'rt')
    file_content = ifhand.read()

    if options.interval is not None:
        interval = options.interval
    else:
        interval = 20

    data_list = []

    if options.max is None:
        opt_max = max(data_list)
    else:
        opt_max  = options.max
    if options.min is None:
        opt_min = min(data_list)
    else:
        opt_min  = options.min
    plot_range = opt_min, opt_max

    #ploting the figure
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.hist(data_list, bins=interval, range=plot_range,
                                 facecolor='green', alpha=0.75)
    plt.show()

if __name__ == '__main__':
    main()


from abc import ABCMeta
from abc import abstractmethod
from torch import nn

from sign_player.rl.distribution import SoftmaxDistribution, CategoricalDistribution

class Policy(object, metaclass=ABCMeta):
    """Abstract policy."""

    @abstractmethod
    def forward(self, state):
        """Evaluate a policy.
        Returns:
            Distribution of actions
        """
        raise NotImplementedError()

class SoftmaxPolicy(nn.Module, Policy):
    """Softmax policy that uses Boltzmann distributions.

    Args:
        model (chainer.Link):
            Link that is callable and outputs action values.
        beta (float):
            Parameter of Boltzmann distributions.
    """

    def __init__(self, model, beta=1.0, min_prob=0.0):
        super(SoftmaxPolicy, self).__init__()
        self.beta = beta
        self.min_prob = min_prob
        self.model = model

h = self.model(x)
        return SoftmaxDistribution(
            h, beta=self.beta, min_prob=self.min_prob)


"""Evaluate a policy.
        Returns:
            Distribution of actions
        """
        raise NotImplementedError()

from abc import ABCMeta
from abc import abstractmethod
from torch import nn

from sign_player.rl.distribution import SoftmaxDistribution, CategoricalDistribution

class Policy(object, metaclass=ABCMeta):
    """Abstract policy."""

    @abstractmethod
    def forward(self, state):

class SoftmaxPolicy(nn.Module, Policy):
    """Softmax policy that uses Boltzmann distributions.

    Args:
        model (chainer.Link):
            Link that is callable and outputs action values.
        beta (float):
            Parameter of Boltzmann distributions.
    """

    def __init__(self, model, beta=1.0, min_prob=0.0):
        super(SoftmaxPolicy, self).__init__()
        self.beta = beta
        self.min_prob = min_prob
        self.model = model

    def forward(self, x):
        h = self.model(x)
        return SoftmaxDistribution(
            h, beta=self.beta, min_prob=self.min_prob)


from abc import ABCMeta
from abc import abstractmethod
from torch import nn

from sign_player.rl.distribution import SoftmaxDistribution, CategoricalDistribution

class Policy(object, metaclass=ABCMeta):
    """Abstract policy."""

    @abstractmethod
    def forward(self, state):
        """Evaluate a policy.
        Returns:
            Distribution of actions
        """
        raise NotImplementedError()

class SoftmaxPolicy(nn.Module, Policy):
    """Softmax policy that uses Boltzmann distributions.

    Args:
        model (chainer.Link):
            Link that is callable and outputs action values.
        beta (float):
            Parameter of Boltzmann distributions.
    """

    def __init__(self, model, beta=1.0, min_prob=0.0):
        super(Sof

        self.beta = beta
        self.min_prob = min_prob
        self.model = model

    def forward(self, x):
        h = self.model(x)
        return SoftmaxDistribution(
            h, beta=self.beta, min_prob=self.min_prob)


from abc import ABCMeta
from abc import abstractmethod
from torch import nn

from sign_player.rl.distribution import SoftmaxDistribution, CategoricalDistribution

class Policy(object, metaclass=ABCMeta):
    """Abstract policy."""

    @abstractmethod
    def forward(self, state):
        """Evaluate a policy.
        Returns:
            Distribution of actions
        """