# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
Runs the reftest test harness.
"""
import json
import multiprocessing
import os
import platform
import posixpath
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
from collections import defaultdict
from datetime import datetime, timedelta

SCRIPT_DIRECTORY = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
if SCRIPT_DIRECTORY not in sys.path:
    sys.path.insert(0, SCRIPT_DIRECTORY)

import mozcrash
import mozdebug
import mozfile
import mozinfo
import mozleak
import mozlog
import mozprocess
import mozprofile
import mozrunner
from manifestparser import TestManifest
from manifestparser import filters as mpf
from mozrunner.utils import get_stack_fixer_function, test_environment
from mozscreenshot import dump_screen, printstatus
from six import reraise, string_types
from six.moves import range

try:
    from marionette_driver.addons import Addons
    from marionette_driver.marionette import Marionette
except ImportError as e:  # noqa
    # Defer ImportError until attempt to use Marionette.
    # Python 3 deletes the exception once the except block
    # is exited. Save a version to raise later.
    e_save = ImportError(str(e))

    def reraise_(*args, **kwargs):
        raise (e_save)  # noqa

    Marionette = reraise_

import reftestcommandline
from output import OutputHandler, ReftestFormatter

here = os.path.abspath(os.path.dirname(__file__))

try:
    from mozbuild.base import MozbuildObject

    build_obj = MozbuildObject.from_environment(cwd=here)
except ImportError:
    build_obj = None

def categoriesToRegex(categoryList):
    return "\\(" + ", ".join(["(?P<%s>\\d+) %s" % c for c in categoryList]) + "\\)"

summaryLines = [
    ("Successful", [("pass", "pass"), ("loadOnly", "load only")]),
    (
        "Unexpected",
        [
            ("fail", "unexpected fail"),
            ("pass", "unexpected pass"),
            ("asserts", "unexpected asserts"),
            ("fixedAsserts", "unexpected fixed asserts"),
            ("failedLoad", "failed load"),
            ("exception", "exception"),
        ],
    ),
    (
        "Known problems",
        [
            ("knownFail", "known fail"),
            ("knownAsserts", "known asserts"),
            ("random", "random"),
            ("skipped", "skipped"),
            ("slow", "slow"),
        ],
    ),
]

if sys.version_info[0] == 3:

    def reraise_(tp_, value_, tb_=None):
        if value_ is None:
            value_ = tp_()
        if value_.__traceback__ is not tb_:
            raise value_.with_traceback(tb_)
        raise value_

else:
    exec("def reraise_(tp_, value_, tb_=None):\n    raise tp_, value_, tb_\n")

def update_mozinfo():
    """walk up directories to find mozinfo.json update the info"""
    # TODO: This should go in a more generic place, e.g. mozinfo

    path = SCRIPT_DIRECTORY
    dirs = set()
    while path != os.path.expanduser("~"):
        if path in dirs:
            break
        dirs.add(path)
        path = os.path.split(path)[0]
    mozinfo.find_and_update_from_json(*dirs)

# Python's print is not threadsafe.
printLock = threading.Lock()

class ReftestThread(threading.Thread):
    def __init__(self, cmdargs):
        threading.Thread.__init__(self)
        self.cmdargs = cmdargs
        self.summaryMatches = {}
        self.retcode = -1
        for text, _ in summaryLines:
            self.summaryMatches[text] = None

    def run(self):
        with printLock:
            print("Starting thread with", self.cmdargs)
            sys.stdout.flush()
        process = subprocess.Popen(self.cmdargs, stdout=subprocess.PIPE)
        for chunk in self.chunkForMergedOutput(process.stdout):
            with printLock:
                print(chunk, end=" ")
                sys.stdout.flush()
        self.retcode = process.wait()

    def chunkForMergedOutput(self, logsource):
        """Gather lines together that should be printed as one atomic unit.
        Individual test results--anything between 'REFTEST TEST-START' and
        'REFTEST TEST-END' lines--are an atomic unit.  Lines with data from
        summaries are parsed and the data stored for later aggregation.
        Other lines are considered their own atomic units and are permitted
        to intermix freely."""
        testStartRegex = re.compile("^REFTEST TEST-START")
        testEndRegex = re.compile("^REFTEST TEST-END")
        summaryHeadRegex = re.compile("^REFTEST INFO \\| Result summary:")
        summaryRegexFormatString = (
            "^REFTEST INFO \\| (?P<message>{text}): (?P<total>\\d+) {regex}"
        )
        summaryRegexStrings = [
            summaryRegexFormatString.format(
                text=text, regex=categoriesToRegex(categories)
            )
            for (text, categories) in summaryLines
        ]
        summaryRegexes = [re.compile(regex) for regex in summaryRegexStrings]

        for line in logsource:
            if testStartRegex.search(line) is not None:
                chunkedLines = [line]
                for lineToBeChunked in logsource:
                    chunkedLines.append(lineToBeChunked)
                    if testEndRegex.search(lineToBeChunked) is not None:
                        break
                yield "".join(chunkedLines)
                continue

            haveSuppressedSummaryLine = False
            for regex in summaryRegexes:
                match = regex.search(line)
                if match is not None:
                    self.summaryMatches[match.group("message")] = match
                    haveSuppressedSummaryLine = True
                    break
            if haveSuppressedSummaryLine:
                continue

            if summaryHeadRegex.search(line) is None:
                yield line

class ReftestResolver(object):
    def defaultManifest(self, suite):
        return {
            "reftest": "reftest.list",
            "crashtest": "crashtests.list",
            "jstestbrowser": "jstests.list",
        }[suite]

    def directoryManifest(self, suite, path):
        return os.path.join(path, self.defaultManifest(suite))

    def findManifest(self, suite, test_file, subdirs=True):
        """Return a tuple of (manifest-path, filter-string) for running test_file.

        test_file is a path to a test or a manifest file
        """
        rv = []
        default_manifest = self.defaultManifest(suite)
        relative_path = None
        if not os.path.isabs(test_file):
            relative_path = test_file
            test_file = self.absManifestPath(test_file)

        if os.path.isdir(test_file):
            for dirpath, dirnames, filenames in os.walk(test_file):
                if default_manifest in filenames:
                    rv.append((os.path.join(dirpath, default_manifest), None))
                    # We keep recursing into subdirectories which means that in the case
                    # of include directives we get the same manifest multiple times.
                    # However reftest.js will only read each manifest once

            if (
                len(rv) == 0
                and relative_path
                and suite == "jstestbrowser"
                and build_obj
            ):
                # The relative path can be from staging area.
                staged_js_dir = os.path.join(
                    build_obj.topobjdir, "dist", "test-stage", "jsreftest"
                )
                staged_file = os.path.join(staged_js_dir, "tests", relative_path)
                return self.findManifest(suite, staged_file, subdirs)
        elif test_file.endswith(".list"):
            if os.path.exists(test_file):
                rv = [(test_file, None)]
        else:
            dirname, pathname = os.path.split(test_file)
            found = True
            while not os.path.exists(os.path.join(dirname, default_manifest)):
                dirname, suffix = os.path.split(dirname)
                pathname = posixpath.join(suffix, pathname)
                if os.path.dirname(dirname) == dirname:
                    found = False
                    break
            if found:
                rv = [
                    (
                        os.path.join(dirname, default_manifest),
                        r".*%s(?:[#?].*)?$" % pathname.replace("?", "\?"),
                    )
                ]

        return rv

    def absManifestPath(self, path):
        return os.path.normpath(os.path.abspath(path))

    def manifestURL(self, options, path):
        return "file://%s" % path

    def resolveManifests(self, options, tests):
        suite = options.suite
        manifests = {}
        for testPath in tests:
            for manifest, filter_str in self.findManifest(suite, testPath):
                if manifest not in manifests:
                    manifests[manifest] = set()
                manifests[manifest].add(filter_str)
        manifests_by_url = {}
        for key in manifests.keys():
            id = os.path.relpath(
                os.path.abspath(os.path.dirname(key)), options.topsrcdir
            )
            id = id.replace(os.sep, posixpath.sep)
            if None in manifests[key]:
                manifests[key] = (None, id)
            else:
                manifests[key] = ("|".join(list(manifests[key])), id)
            url = self.manifestURL(options, key)
            manifests_by_url[url] = manifests[key]
        return manifests_by_url

class RefTest(object):
    oldcwd = os.getcwd()
    resolver_cls = ReftestResolver
    use_marionette = True

    def __init__(self, suite):
        update_mozinfo()
        self.lastTestSeen = None
        self.lastTest = None
        self.haveDumpedScreen = False
        self.resolver = self.resolver_cls()
        self.log = None
        self.outputHandler = None
        self.testDumpFile = os.path.join(tempfile.gettempdir(), "reftests.json")
        self.currentManifest = "No test started"

        self.run_by_manifest = True
        if suite in ("crashtest", "jstestbrowser"):
            self.run_by_manifest = False

    def _populate_logger(self, options):
        if self.log:
            return

        self.log = getattr(options, "log", None)
        if self.log:
            return

        mozlog.commandline.log_formatters["tbpl"] = (
            ReftestFormatter,
            "Reftest specific formatter for the"
            "benefit of legacy log parsers and"
            "tools such as the reftest analyzer",
        )
        fmt_options = {}
        if not options.log_tbpl_level and os.environ.get("MOZ_REFTEST_VERBOSE"):
            options.log_tbpl_level = fmt_options["level"] = "debug"
        self.log = mozlog.commandline.setup_logging(
            "reftest harness", options, {"tbpl": sys.stdout}, fmt_options
        )

    def getFullPath(self, path):
        "Get an absolute path relative to self.oldcwd."
        return os.path.normpath(os.path.join(self.oldcwd, os.path.expanduser(path)))

    def createReftestProfile(
        self,
        options,
        tests=None,
        manifests=None,
        server="localhost",
        port=0,
        profile_to_clone=None,
        prefs=None,
    ):
        """Sets up a profile for reftest.

        :param options: Object containing command line options
        :param tests: List of test objects to run
        :param manifests: List of manifest files to parse (only takes effect
                          if tests were not passed in)
        :param server: Server name to use for http tests
        :param profile_to_clone: Path to a profile to use as the basis for the
                                 test profile
        :param prefs: Extra preferences to set in the profile
        """
        locations = mozprofile.permissions.ServerLocations()
        locations.add_host(server, scheme="http", port=port)
        locations.add_host(server, scheme="https", port=port)

        sandbox_whitelist_paths = options.sandboxReadWhitelist
        if platform.system() == "Linux" or platform.system() in (
            "Windows",
            "Microsoft",
        ):
            # Trailing slashes are needed to indicate directories on Linux and Windows
            sandbox_whitelist_paths = map(
                lambda p: os.path.join(p, ""), sandbox_whitelist_paths
            )

        addons = []
        if not self.use_marionette:
            addons.append(options.reftestExtensionPath)

        if options.specialPowersExtensionPath is not None:
            if not self.use_marionette:
                addons.append(options.specialPowersExtensionPath)

        # Install distributed extensions, if application has any.
        distExtDir = os.path.join(
            options.app[: options.app.rfind(os.sep)], "distribution", "extensions"
        )
        if os.path.isdir(distExtDir):
            for f in os.listdir(distExtDir):
                addons.append(os.path.join(distExtDir, f))

        # Install custom extensions.
        for f in options.extensionsToInstall:
            addons.append(self.getFullPath(f))

        kwargs = {
            "addons": addons,
            "locations": locations,
            "whitelistpaths": sandbox_whitelist_paths,
        }
        if profile_to_clone:
            profile = mozprofile.Profile.clone(profile_to_clone, **kwargs)
        else:
            profile = mozprofile.Profile(**kwargs)

        # First set prefs from the base profiles under testing/profiles.

        # In test packages used in CI, the profile_data directory is installed
        # in the SCRIPT_DIRECTORY.
        profile_data_dir = os.path.join(SCRIPT_DIRECTORY, "profile_data")
        # If possible, read profile data from topsrcdir. This prevents us from
        # requiring a re-build to pick up newly added extensions in the
        # <profile>/extensions directory.
        if build_obj:
            path = os.path.join(build_obj.topsrcdir, "testing", "profiles")
            if os.path.isdir(path):
                profile_data_dir = path
        # Still not found? Look for testing/profiles relative to layout/tools/reftest.
        if not os.path.isdir(profile_data_dir):
            path = os.path.abspath(
                os.path.join(SCRIPT_DIRECTORY, "..", "..", "..", "testing", "profiles")
            )
            if os.path.isdir(path):
                profile_data_dir = path

        with open(os.path.join(profile_data_dir, "profiles.json"), "r") as fh:
            base_profiles = json.load(fh)["reftest"]

        for name in base_profiles:
            path = os.path.join(profile_data_dir, name)
            profile.merge(path)

        # Second set preferences for communication between our command line
        # arguments and the reftest harness. Preferences that are required for
        # reftest to work should instead be set under srcdir/testing/profiles.
        prefs = prefs or {}
        prefs["reftest.timeout"] = options.timeout * 1000
        if options.logFile:
            prefs["reftest.logFile"] = options.logFile
        if options.ignoreWindowSize:
            prefs["reftest.ignoreWindowSize"] = True
        if options.shuffle:
            prefs["reftest.shuffle"] = True
        if options.repeat:
            prefs["reftest.repeat"] = options.repeat
        if options.runUntilFailure:
            prefs["reftest.runUntilFailure"] = True
            if not options.repeat:
                prefs["reftest.repeat"] = 30
        if options.verify:
            prefs["reftest.verify"] = True
        if options.cleanupCrashes:
            prefs["reftest.cleanupPendingCrashes"] = True
        prefs["reftest.focusFilterMode"] = options.focusFilterMode
        prefs["reftest.logLevel"] = options.log_tbpl_level or "info"
        prefs["reftest.suite"] = options.suite
        prefs["gfx.font_rendering.ahem_antialias_none"] = True
        # Run the "deferred" font-loader immediately, because if it finishes
        # mid-test, the extra reflow that is triggered can disrupt the test.
        prefs["gfx.font_loader.delay"] = 0
        # Ensure bundled fonts are activated, even if not enabled by default
        # on the platform, so that tests can rely on them.
        prefs["gfx.bundled-fonts.activate"] = 1
        # Disable dark scrollbars because it's semi-transparent.
        prefs["widget.disable-dark-scrollbar"] = True
        prefs["reftest.isCoverageBuild"] = mozinfo.info.get("ccov", False)

        # config specific flags
        prefs["sandbox.apple_silicon"] = mozinfo.info.get("apple_silicon", False)

        # Set tests to run or manifests to parse.
        if tests:
            testlist = os.path.join(profile.profile, "reftests.json")
            with open(testlist, "w") as fh:
                json.dump(tests, fh)
            prefs["reftest.tests"] = testlist
        elif manifests:
            prefs["reftest.manifests"] = json.dumps(manifests)

        # Unconditionally update the e10s pref, default True
        prefs["browser.tabs.remote.autostart"] = True
        if not options.e10s:
            prefs["browser.tabs.remote.autostart"] = False

        # default fission to True
        prefs["fission.autostart"] = True
        if options.disableFission:
            prefs["fission.autostart"] = False

        if not self.run_by_manifest:
            if options.totalChunks:
                prefs["reftest.totalChunks"] = options.totalChunks
            if options.thisChunk:
                prefs["reftest.thisChunk"] = options.thisChunk

        # Bug 1262954: For winXP + e10s disable acceleration
        if (
            platform.system() in ("Windows", "Microsoft")
            and "5.1" in platform.version()
            and options.e10s
        ):
            prefs["layers.acceleration.disabled"] = True

        # Bug 1300355: Disable canvas cache for win7 as it uses
        # too much memory and causes OOMs.
        if (
            platform.system() in ("Windows", "Microsoft")
            and "6.1" in platform.version()
        ):
            prefs["reftest.nocache"] = True

        if options.marionette:
            # options.marionette can specify host:port
            port = options.marionette.split(":")[1]
            prefs["marionette.port"] = int(port)

        # Enable tracing output for detailed failures in case of
        # failing connection attempts, and hangs (bug 1397201)
        prefs["remote.log.level"] = "Trace"

        # Third, set preferences passed in via the command line.
        for v in options.extraPrefs:
            thispref = v.split("=")
            if len(thispref) < 2:
                print("Error: syntax error in --setpref=" + v)
                sys.exit(1)
            prefs[thispref[0]] = thispref[1].strip()

        for pref in prefs:
            prefs[pref] = mozprofile.Preferences.cast(prefs[pref])
        profile.set_preferences(prefs)

        if os.path.join(here, "chrome") not in options.extraProfileFiles:
            options.extraProfileFiles.append(os.path.join(here, "chrome"))

        self.copyExtraFilesToProfile(options, profile)

        self.log.info(
            "Running with e10s: {}".format(prefs["browser.tabs.remote.autostart"])
        )
        self.log.info("Running with fission: {}".format(prefs["fission.autostart"]))

        return profile

    def environment(self, **kwargs):
        kwargs["log"] = self.log
        return test_environment(**kwargs)

    def buildBrowserEnv(self, options, profileDir):
        browserEnv = self.environment(
            xrePath=options.xrePath, debugger=options.debugger
        )
        browserEnv["XPCOM_DEBUG_BREAK"] = "stack"
        if options.topsrcdir:
            browserEnv["MOZ_DEVELOPER_REPO_DIR"] = options.topsrcdir
        if hasattr(options, "topobjdir"):
            browserEnv["MOZ_DEVELOPER_OBJ_DIR"] = options.topobjdir

        if mozinfo.info["asan"]:
            # Disable leak checking for reftests for now
            if "ASAN_OPTIONS" in browserEnv:
                browserEnv["ASAN_OPTIONS"] += ":detect_leaks=0"
            else:
                browserEnv["ASAN_OPTIONS"] = "detect_leaks=0"

        # Set environment defaults for jstestbrowser. Keep in sync with the
        # defaults used in js/src/tests/lib/tests.py.
        if options.suite == "jstestbrowser":
            browserEnv["TZ"] = "PST8PDT"
            browserEnv["LC_ALL"] = "en_US.UTF-8"

        for v in options.environment:
            ix = v.find("=")
            if ix <= 0:
                print("Error: syntax error in --setenv=" + v)
                return None
            browserEnv[v[:ix]] = v[ix + 1 :]

        # Enable leaks detection to its own log file.
        self.leakLogFile = os.path.join(profileDir, "runreftest_leaks.log")
        browserEnv["XPCOM_MEM_BLOAT_LOG"] = self.leakLogFile

        # TODO: this is always defined (as part of --enable-webrender which is default)
        #       can we make this default in the browser?
        browserEnv["MOZ_ACCELERATED"] = "1"

        if options.headless:
            browserEnv["MOZ_HEADLESS"] = "1"

        return browserEnv

    def cleanup(self, profileDir):
        if profileDir:
            shutil.rmtree(profileDir, True)

    def verifyTests(self, tests, options):
        """
        Support --verify mode: Run test(s) many times in a variety of
        configurations/environments in an effort to find intermittent
        failures.
        """

        self._populate_logger(options)

        # Number of times to repeat test(s) when running with --repeat
        VERIFY_REPEAT = 10
        # Number of times to repeat test(s) when running test in separate browser
        VERIFY_REPEAT_SINGLE_BROWSER = 5

        def step1():
            options.repeat = VERIFY_REPEAT
            options.runUntilFailure = True
            result = self.runTests(tests, options)
            return result

        def step2():
            options.repeat = 0
            options.runUntilFailure = False
            for i in range(VERIFY_REPEAT_SINGLE_BROWSER):
                result = self.runTests(tests, options)
                if result != 0:
                    break
            return result

        def step3():
            options.repeat = VERIFY_REPEAT
            options.runUntilFailure = True
            options.environment.append("MOZ_CHAOSMODE=0xfb")
            result = self.runTests(tests, options)
            options.environment.remove("MOZ_CHAOSMODE=0xfb")
            return result

        def step4():
            options.repeat = 0
            options.runUntilFailure = False
            options.environment.append("MOZ_CHAOSMODE=0xfb")
            for i in range(VERIFY_REPEAT_SINGLE_BROWSER):
                result = self.runTests(tests, options)
                if result != 0:
                    break
            options.environment.remove("MOZ_CHAOSMODE=0xfb")
            return result

        steps = [
            ("1. Run each test %d times in one browser." % VERIFY_REPEAT, step1),
            (
                "2. Run each test %d times in a new browser each time."
                % VERIFY_REPEAT_SINGLE_BROWSER,
                step2,
            ),
            (
                "3. Run each test %d times in one browser, in chaos mode."
                % VERIFY_REPEAT,
                step3,
            ),
            (
                "4. Run each test %d times in a new browser each time, in chaos mode."
                % VERIFY_REPEAT_SINGLE_BROWSER,
                step4,
            ),
        ]

        stepResults = {}
        for (descr, step) in steps:
            stepResults[descr] = "not run / incomplete"

        startTime = datetime.now()
        maxTime = timedelta(seconds=options.verify_max_time)
        finalResult = "PASSED"
        for (descr, step) in steps:
            if (datetime.now() - startTime) > maxTime:
                self.log.info("::: Test verification is taking too long: Giving up!")
                self.log.info(
                    "::: So far, all checks passed, but not all checks were run."
                )
                break
            self.log.info(":::")
            self.log.info('::: Running test verification step "%s"...' % descr)
            self.log.info(":::")
            result = step()
            if result != 0:
                stepResults[descr] = "FAIL"
                finalResult = "FAILED!"
                break
            stepResults[descr] = "Pass"

        self.log.info(":::")
        self.log.info("::: Test verification summary for:")
        self.log.info(":::")
        for test in tests:
            self.log.info("::: " + test)
        self.log.info(":::")
        for descr in sorted(stepResults.keys()):
            self.log.info("::: %s : %s" % (descr, stepResults[descr]))
        self.log.info(":::")
        self.log.info("::: Test verification %s" % finalResult)
        self.log.info(":::")

        return result

    def runTests(self, tests, options, cmdargs=None):
        cmdargs = cmdargs or []
        self._populate_logger(options)
        self.outputHandler = OutputHandler(
            self.log, options.utilityPath, options.symbolsPath
        )

        if options.cleanupCrashes:
            mozcrash.cleanup_pending_crash_reports()

        manifests = self.resolver.resolveManifests(options, tests)
        if options.filter:
            manifests[""] = (options.filter, None)

        if not getattr(options, "runTestsInParallel", False):
            return self.runSerialTests(manifests, options, cmdargs)

        cpuCount = multiprocessing.cpu_count()

        # We have the directive, technology, and machine to run multiple test instances.
        # Experimentation says that reftests are not overly CPU-intensive, so we can run
        # multiple jobs per CPU core.
        #
        # Our Windows machines in automation seem to get upset when we run a lot of
        # simultaneous tests on them, so tone things down there.
        if sys.platform == "win32":
            jobsWithoutFocus = cpuCount
        else:
            jobsWithoutFocus = 2 * cpuCount

        totalJobs = jobsWithoutFocus + 1
        perProcessArgs = [sys.argv[:] for i in range(0, totalJobs)]

        host = "localhost"
        port = 2828
        if options.marionette:
            host, port = options.marionette.split(":")

        # First job is only needs-focus tests.  Remaining jobs are
        # non-needs-focus and chunked.
        perProcessArgs[0].insert(-1, "--focus-filter-mode=needs-focus")
        for (chunkNumber, jobArgs) in enumerate(perProcessArgs[1:], start=1):
            jobArgs[-1:-1] = [
                "--focus-filter-mode=non-needs-focus",
                "--total-chunks=%d" % jobsWithoutFocus,
                "--this-chunk=%d" % chunkNumber,
                "--marionette=%s:%d" % (host, port),
            ]
            port += 1

        for jobArgs in perProcessArgs:
            try:
                jobArgs.remove("--run-tests-in-parallel")
            except Exception:
                pass
            jobArgs[0:0] = [sys.executable, "-u"]

        threads = [ReftestThread(args) for args in perProcessArgs[1:]]
        for t in threads:
            t.start()

        while True:
            # The test harness in each individual thread will be doing timeout
            # handling on its own, so we shouldn't need to worry about any of
            # the threads hanging for arbitrarily long.
            for t in threads:
                t.join(10)
            if not any(t.is_alive() for t in threads):
                break

        # Run the needs-focus tests serially after the other ones, so we don't
        # have to worry about races between the needs-focus tests *actually*
        # needing focus and the dummy windows in the non-needs-focus tests
        # trying to focus themselves.
        focusThread = ReftestThread(perProcessArgs[0])
        focusThread.start()
        focusThread.join()

        # Output the summaries that the ReftestThread filters suppressed.
        summaryObjects = [defaultdict(int) for s in summaryLines]
        for t in threads:
            for (summaryObj, (text, categories)) in zip(summaryObjects, summaryLines):
                threadMatches = t.summaryMatches[text]
                for (attribute, description) in categories:
                    amount = int(threadMatches.group(attribute) if threadMatches else 0)
                    summaryObj[attribute] += amount
                amount = int(threadMatches.group("total") if threadMatches else 0)
                summaryObj["total"] += amount

        print("REFTEST INFO | Result summary:")
        for (summaryObj, (text, categories)) in zip(summaryObjects, summaryLines):
            details = ", ".join(
                [
                    "%d %s" % (summaryObj[attribute], description)
                    for (attribute, description) in categories
                ]
            )
            print(
                "REFTEST INFO | "
                + text
                + ": "
                + str(summaryObj["total"])
                + " ("
                + details
                + ")"
            )

        return int(any(t.retcode != 0 for t in threads))

    def handleTimeout(self, timeout, proc, utilityPath, debuggerInfo):
        """handle process output timeout"""
        # TODO: bug 913975 : _processOutput should call self.processOutputLine
        # one more time one timeout (I think)
        self.log.error(
            "%s | application timed out after %d seconds with no output"
            % (self.lastTestSeen, int(timeout))
        )
        self.log.warning("Force-terminating active process(es).")
        self.killAndGetStack(
            proc, utilityPath, debuggerInfo, dump_screen=not debuggerInfo
        )

    def dumpScreen(self, utilityPath):
        if self.haveDumpedScreen:
            self.log.info(
                "Not taking screenshot here: see the one that was previously logged"
            )
            return
        self.haveDumpedScreen = True
        dump_screen(utilityPath, self.log)

    def killAndGetStack(self, process, utilityPath, debuggerInfo, dump_screen=False):
        """
        Kill the process, preferrably in a way that gets us a stack trace.
        Also attempts to obtain a screenshot before killing the process
        if specified.
        """

        if dump_screen:
            self.dumpScreen(utilityPath)

        if mozinfo.info.get("crashreporter", True) and not debuggerInfo:
            if mozinfo.isWin:
                # We should have a "crashinject" program in our utility path
                crashinject = os.path.normpath(
                    os.path.join(utilityPath, "crashinject.exe")
                )
                if os.path.exists(crashinject):
                    status = subprocess.Popen([crashinject, str(process.pid)]).wait()
                    printstatus("crashinject", status)
                    if status == 0:
                        return
            else:
                try:
                    process.kill(sig=signal.SIGABRT)
                except OSError:
                    # https://bugzilla.mozilla.org/show_bug.cgi?id=921509
                    self.log.info("Can't trigger Breakpad, process no longer exists")
                return
        self.log.info("Can't trigger Breakpad, just killing process")
        process.kill()

    def runApp(
        self,
        options,
        cmdargs=None,
        timeout=None,
        debuggerInfo=None,
        symbolsPath=None,
        valgrindPath=None,
        valgrindArgs=None,
        valgrindSuppFiles=None,
        **profileArgs
    ):

        if cmdargs is None:
            cmdargs = []
        cmdargs = cmdargs[:]

        if self.use_marionette:
            cmdargs.append("-marionette")

        binary = options.app
        profile = self.createReftestProfile(options, **profileArgs)

        # browser environment
        env = self.buildBrowserEnv(options, profile.profile)

        def timeoutHandler():
            self.handleTimeout(timeout, proc, options.utilityPath, debuggerInfo)

        interactive = False
        debug_args = None
        if debuggerInfo:
            interactive = debuggerInfo.interactive
            debug_args = [debuggerInfo.path] + debuggerInfo.args

        def record_last_test(message):
            """Records the last test seen by this harness for the benefit of crash logging."""

            def testid(test):
                if " " in test:
                    return test.split(" ")[0]
                return test

            if message["action"] == "test_start":
                self.lastTestSeen = testid(message["test"])
            elif message["action"] == "test_end":
                if self.lastTest and message["test"] == self.lastTest:
                    self.lastTestSeen = self.currentManifest
                else:
                    self.lastTestSeen = "{} (finished)".format(testid(message["test"]))

        self.log.add_handler(record_last_test)

        kp_kwargs = {
            "kill_on_timeout": False,
            "cwd": SCRIPT_DIRECTORY,
            "onTimeout": [timeoutHandler],
            "processOutputLine": [self.outputHandler],
        }

        if mozinfo.isWin or mozinfo.isMac:
            # Prevents log interleaving on Windows at the expense of losing
            # true log order. See bug 798300 and bug 1324961 for more details.
            kp_kwargs["processStderrLine"] = [self.outputHandler]

        if interactive:
            # If an interactive debugger is attached,
            # don't use timeouts, and don't capture ctrl-c.
            timeout = None
            signal.signal(signal.SIGINT, lambda sigid, frame: None)

        runner_cls = mozrunner.runners.get(
            mozinfo.info.get("appname", "firefox"), mozrunner.Runner
        )
        runner = runner_cls(
            profile=profile,
            binary=binary,
            process_class=mozprocess.ProcessHandlerMixin,
            cmdargs=cmdargs,
            env=env,
            process_args=kp_kwargs,
        )
        runner.start(
            debug_args=debug_args, interactive=interactive, outputTimeout=timeout
        )
        proc = runner.process_handler
        self.outputHandler.proc_name = "GECKO({})".format(proc.pid)

        # Used to defer a possible IOError exception from Marionette
        marionette_exception = None

        if self.use_marionette:
            marionette_args = {
                "socket_timeout": options.marionette_socket_timeout,
                "startup_timeout": options.marionette_startup_timeout,
                "symbols_path": options.symbolsPath,
            }
            if options.marionette:
                host, port = options.marionette.split(":")
                marionette_args["host"] = host
                marionette_args["port"] = int(port)

            try:
                marionette = Marionette(**marionette_args)
                marionette.start_session()

                addons = Addons(marionette)
                if options.specialPowersExtensionPath:
                    addons.install(options.specialPowersExtensionPath, temp=True)

                addons.install(options.reftestExtensionPath, temp=True)

                marionette.delete_session()
            except IOError:
                # Any IOError as thrown by Marionette means that something is
                # wrong with the process, like a crash or the socket is no
                # longer open. We defer raising this specific error so that
                # post-test checks for leaks and crashes are performed and
                # reported first.
                marionette_exception = sys.exc_info()

        status = runner.wait()
        runner.process_handler = None
        self.outputHandler.proc_name = None

        crashed = mozcrash.log_crashes(
            self.log,
            os.path.join(profile.profile, "minidumps"),
            options.symbolsPath,
            test=self.lastTestSeen,
        )

        if crashed:
            # log suite_end to wrap up, this is usually done with in in-browser harness
            if not self.outputHandler.results:
                # TODO: while .results is a defaultdict(int), it is proxied via log_actions as data, not type
                self.outputHandler.results = {
                    "Pass": 0,
                    "LoadOnly": 0,
                    "Exception": 0,
                    "FailedLoad": 0,
                    "UnexpectedFail": 1,
                    "UnexpectedPass": 0,
                    "AssertionUnexpected": 0,
                    "AssertionUnexpectedFixed": 0,
                    "KnownFail": 0,
                    "AssertionKnown": 0,
                    "Random": 0,
                    "Skip": 0,
                    "Slow": 0,
                }
            self.log.suite_end(extra={"results": self.outputHandler.results})

        if not status and crashed:
            status = 1

        if status and not crashed:
            msg = (
                "TEST-UNEXPECTED-FAIL | %s | application terminated with exit code %s"
                % (self.lastTestSeen, status)
            )
            # use process_output so message is logged verbatim
            self.log.process_output(None, msg)

        runner.cleanup()
        self.cleanup(profile.profile)

        if marionette_exception is not None:
            exc, value, tb = marionette_exception
            raise reraise(exc, value, tb)

        self.log.info("Process mode: {}".format("e10s" if options.e10s else "non-e10s"))
        return status

    def getActiveTests(self, manifests, options, testDumpFile=None):
        # These prefs will cause reftest.jsm to parse the manifests,
        # dump the resulting tests to a file, and exit.
        prefs = {
            "reftest.manifests": json.dumps(manifests),
            "reftest.manifests.dumpTests": testDumpFile or self.testDumpFile,
        }
        cmdargs = []
        self.runApp(options, cmdargs=cmdargs, prefs=prefs)

        if not os.path.isfile(self.testDumpFile):
            print("Error: parsing manifests failed!")
            sys.exit(1)

        with open(self.testDumpFile, "r") as fh:
            tests = json.load(fh)

        if os.path.isfile(self.testDumpFile):
            mozfile.remove(self.testDumpFile)

        for test in tests:
            # Name and path are expected by manifestparser, but not used in reftest.
            test["name"] = test["path"] = test["url1"]

        mp = TestManifest(strict=False)
        mp.tests = tests

        filters = []
        if options.totalChunks:
            filters.append(
                mpf.chunk_by_manifest(options.thisChunk, options.totalChunks)
            )

        tests = mp.active_tests(exists=False, filters=filters)
        return tests

    def runSerialTests(self, manifests, options, cmdargs=None):
        debuggerInfo = None
        if options.debugger:
            debuggerInfo = mozdebug.get_debugger_info(
                options.debugger, options.debuggerArgs, options.debuggerInteractive
            )

        def run(**kwargs):
            if kwargs.get("tests"):
                self.lastTest = kwargs["tests"][-1]["identifier"]
                if not isinstance(self.lastTest, string_types):
                    self.lastTest = " ".join(self.lastTest)

            status = self.runApp(
                options,
                manifests=manifests,
                cmdargs=cmdargs,
                # We generally want the JS harness or marionette
                # to handle timeouts if they can.
                # The default JS harness timeout is currently
                # 300 seconds (default options.timeout).
                # The default Marionette socket timeout is
                # currently 360 seconds.
                # Give the JS harness extra time to deal with
                # its own timeouts and try to usually exceed
                # the 360 second marionette socket timeout.
                # See bug 479518 and bug 1414063.
                timeout=options.timeout + 70.0,
                debuggerInfo=debuggerInfo,
                symbolsPath=options.symbolsPath,
                **kwargs
            )

            # do not process leak log when we crash/assert
            if status == 0:
                mozleak.process_leak_log(
                    self.leakLogFile,
                    leak_thresholds=options.leakThresholds,
                    stack_fixer=get_stack_fixer_function(
                        options.utilityPath, options.symbolsPath
                    ),
                )
            return status

        if not self.run_by_manifest:
            return run()

        tests = self.getActiveTests(manifests, options)
        tests_by_manifest = defaultdict(list)
        ids_by_manifest = defaultdict(list)
        for t in tests:
            tests_by_manifest[t["manifest"]].append(t)
            test_id = t["identifier"]
            if not isinstance(test_id, string_types):
                test_id = " ".join(test_id)
            ids_by_manifest[t["manifestID"]].append(test_id)

        self.log.suite_start(ids_by_manifest, name=options.suite)

        overall = 0
        status = -1
        for manifest, tests in tests_by_manifest.items():
            self.log.info("Running tests in {}".format(manifest))
            self.currentManifest = manifest
            status = run(tests=tests)
            overall = overall or status
        if status == -1:
            # we didn't run anything
            overall = 1

        self.log.suite_end(extra={"results": self.outputHandler.results})
        return overall

    def copyExtraFilesToProfile(self, options, profile):
        "Copy extra files or dirs specified on the command line to the testing profile."
        profileDir = profile.profile
        for f in options.extraProfileFiles:
            abspath = self.getFullPath(f)
            if os.path.isfile(abspath):
                if os.path.basename(abspath) == "user.js":
                    extra_prefs = mozprofile.Preferences.read_prefs(abspath)
                    profile.set_preferences(extra_prefs)
                elif os.path.basename(abspath).endswith(".dic"):
                    hyphDir = os.path.join(profileDir, "hyphenation")
                    if not os.path.exists(hyphDir):
                        os.makedirs(hyphDir)
                    shutil.copy2(abspath, hyphDir)
                else:
                    shutil.copy2(abspath, profileDir)
            elif os.path.isdir(abspath):
                dest = os.path.join(profileDir, os.path.basename(abspath))
                shutil.copytree(abspath, dest)
            else:
                self.log.warning(
                    "runreftest.py | Failed to copy %s to profile" % abspath
                )
                continue

def run_test_harness(parser, options):
    reftest = RefTest(options.suite)
    parser.validate(options, reftest)

    # We have to validate options.app here for the case when the mach
    # command is able to find it after argument parsing. This can happen
    # when running from a tests archive.
    if not options.app:
        parser.error("could not find the application path, --appname must be specified")

    options.app = reftest.getFullPath(options.app)
    if not os.path.exists(options.app):
        parser.error(
            "Error: Path %(app)s doesn't exist. Are you executing "
            "$objdir/_tests/reftest/runreftest.py?" % {"app": options.app}
        )

    if options.xrePath is None:
        options.xrePath = os.path.dirname(options.app)

    if options.verify:
        result = reftest.verifyTests(options.tests, options)
    else:
        result = reftest.runTests(options.tests, options)

    return result

if __name__ == "__main__":
    parser = reftestcommandline.DesktopArgumentsParser()
    options = parser.parse_args()
    sys.exit(run_test_harness(parser, options))


"""
Module containing multilayer-perceptron discriminator of factorizing VAE.
"""
from torch import nn
from disvae.utils.initialization import weights_init

class Discriminator(nn.Module):
    def __init__(self,
                 neg_slope=0.2,
                 latent_dim=2,
                 hidden_units=1000):
        """
        Discriminator proposed in [1].

        Parameters
        ----------
        neg_slope: float
            Leaky ReLu negative slope.

        latent_dim : int
            Dimensionality of latent variables.

        hidden_units: int
            Number of hidden units.

        Architecture
        ------------
        - 6 layer multi-layer perceptron, each with 1000 hidden units
        - Leaky ReLu activations
        - Output 2 "logits" (unnormalized log-probabilities)

        Reference
        ---------
        [1] H Kim and A Mnih. "Disentangling by factorising,"
            in Proceedings of the 35th International Conference on Machine Learning
            (PMLR, Stockholm, Sweden, 2018), Vol. 80, pp. 2649-2658, 10.48550/arXiv.1802.05983.
        """
        super(Discriminator, self).__init__()

        # Activation parameters
        self.neg_slope = neg_slope
        self.leaky_relu = nn.LeakyReLU(self.neg_slope, True)

        # Layer parameters
        self.z_dim = latent_dim
        self.hidden_units = hidden_units
        out_units = 2

        # Fully connected layers
        self.lin1 = nn.Linear(self.z_dim, hidden_units)
        self.lin2 = nn.Linear(hidden_units, hidden_units)
        self.lin3 = nn.Linear(hidden_units, hidden_units)
        self.lin4 = nn.Linear(hidden_units, hidden_units)
        self.lin5 = nn.Linear(hidden_units, hidden_units)
        self.lin6 = nn.Linear(hidden_units, out_units)

        self.reset_parameters()

    def forward(self, z):

        # Fully connected layers with leaky ReLu activations
        z = self.leaky_relu(self.lin1(z))
        z = self.leaky_relu(self.lin2(z))
        z = self.leaky_relu(self.lin3(z))
        z = self.leaky_relu(self.lin4(z))
        z = self.leaky_relu(self.lin5(z))
        z = self.lin6(z)

        return z

    def reset_parameters(self):
        self.apply(weights_init)


import atexit
from pathlib import Path

import cv2
import numpy as np

class VideoWriter:
    """Save video using OpenCV"""

    def __init__(
        self,
        path: Path,
        fps: float = 20.0,
        image_shape: str = "HWC",
        fourcc: str = "XVID",
        rgb: bool = True,
    ) -> None:
        self._path = path
        self._writer = None
        self._fps = fps
        self._w_index = image_shape.find("W")
        self._h_index = image_shape.find("H")
        self._fourcc = cv2.VideoWriter_fourcc(*fourcc)
        if self._w_index < 0 or self._h_index < 0:
            raise ValueError(f"Invalid shape: {image_shape}")
        c_index = image_shape.find("C")
        if c_index < 0:
            transpose = self._h_index, self._w_index
        else:
            transpose = self._h_index, self._w_index, c_index

        def convert(image: np.ndarray) -> np.ndarray:
            transposed = np.transpose(image, transpose)
            if rgb:
                return cv2.cvtColor(transposed, cv2.COLOR_RGB2BGR)
            else:
                return transposed

        self._convert = convert
        atexit.register(self.close)

    def _initialize_writer(self, image: np.ndarray) -> None:
        shape = image.shape
        h, w = shape[self._h_index], shape[self._w_index]
        color = len(shape) == 3
        self._writer = cv2.VideoWriter(
            self._path.as_posix(),
            self._fourcc,
            self._fps,
            (w, h),
            color,
        )

    def append(self, image: np.ndarray) -> None:
        if self._writer is None:
            self._initialize_writer(image)

        self._writer.write(self._convert(image))

    def close(self) -> None:
        if self._writer is not None:
            self._writer.release()


import re, datetime, MoinMoin.search, MoinMoin.Page

def timedelta_regexp(prefix):
    if prefix is None:
        open,close='?:(?#',')'
    else:
        open,close='?P<' + prefix,'>'
    return r"""
    ((%(open)syears%(close)s[0-9]+)\s*y(ears?)?)?
    \s*(?:and)?\s*
    ((%(open)sweeks%(close)s[0-9]+)\s*w(eeks?)?)?
    \s*(?:and)?\s*
    ((%(open)sdays%(close)s[0-9]+)\s*d(ays?)?)?
    \s*(?:and)?\s*
    ((%(open)shours%(close)s[0-9]+)\s*h(ours?)?)?
    \s*(?:and)?\s*
    ((%(open)sminutes%(close)s[0-9]+)\s*m(inutes?)?)?
    \s*(?:and)?\s*
    ((%(open)sseconds%(close)s[0-9]+)\s*s(econds?)?)?
    \s*(?:and)?\s*
    ((%(open)smiliseconds%(close)s[0-9]+)\s*(ms | miliseconds?))?
    \s*(?:and)?\s*
    ((%(open)smicroseconds%(close)s[0-9]+)\s*(us | microseconds?))?
    """ % {'open': open, 'close': close}

timedelta_regexp_pattern = re.compile(r'^%s$' % timedelta_regexp(''), re.UNICODE + re.MULTILINE + re.IGNORECASE + re.DOTALL + re.VERBOSE)

def datetime_regexp(prefix):
    if prefix is None:
        open,close='?:(?#',')'
    else:
        open,close='?P<' + prefix,'>'
    return r"""
    (%(open)sdawnoftime%(close)sdawn \s of \s time)
    |
    (%(open)snow%(close)snow)
    |
    (
        in
        \s*
        (%(open)sfuture%(close)s%(future)s)
    )
    |
    (
        (%(open)spast%(close)s%(past)s)
        \s*
        ago
    )
    |
    (
        (
            (%(open)sdate1%(close)s
                (%(open)syear1%(close)s19\d{2} | 20\d{2} | \d{2} )
                [./-]
                (%(open)smonth1%(close)s1[012] | 0[1-9] | [1-9])
                [./-]
                (%(open)sday1%(close)s3[01] | 0[1-9] | [12]\d | [1-9])
            )
            |
            (%(open)sdate2%(close)s
                (%(open)smonth2%(close)sjanuary|jan|february|feb|march|mar|april|apr|may|june|jun|july|jul|august|aug|september|sep|october|oct|november|nov|december|dec)
                [ ]+
                (%(open)sday2%(close)s3[01] | 0[1-9] | [12]\d | [1-9])
                (?: st | nd | rd | th )?
                [ ,]+
                (%(open)syear2%(close)s19\d{2} | 20\d{2} | \d{2})
            )
            |
            (%(open)sdate3%(close)s
                (%(open)syear3%(close)s19\d{2} | 20\d{2} | \d{2} )
                (%(open)smonth3%(close)s1[012] | 0[1-9])
                (%(open)sday3%(close)s3[01] | 0[1-9] | [12]\d)
            )
        )
        \s*
        (
            (%(open)stime1%(close)s
                (%(open)shour1%(close)s 1[0-2] | [0]?[1-9] )
                (
                        (?: [.:])
                        (%(open)sminute1%(close)s[0-5]\d{0,1} | [6-9])
                        (
                            (?: [.:])
                            (%(open)ssecond1%(close)s[0-5]\d{0,1} | [6-9])
                        )?
                )?
                [ ]*
                (%(open)sam1%(close)s am | pm | p | a )
            )
            |
            (%(open)stime2%(close)s
                (%(open)shour2%(close)s | [01]\d{0,1} | 2[0-3] | [1-9])
                (
                        (?: [.:])
                        (%(open)sminute2%(close)s[0-5]\d{0,1} | [6-9])
                        (
                            (?: [.:])
                            (%(open)ssecond2%(close)s[0-5]\d{0,1} | [6-9])
                        )?
                )?
            )
            |
            (%(open)stime3%(close)s
                (%(open)shour3%(close)s [01]\d | 2[0-3])
                (%(open)sminute3%(close)s [0-5]\d)?
                (%(open)ssecond3%(close)s[0-5]\d{0,1} | [6-9])?
            )
            |
            (%(open)stime4%(close)s
                (%(open)shour4%(close)s 0[1-9] | 1[0-2])
                (%(open)sminute4%(close)s [0-5]\d)?
                (%(open)ssecond4%(close)s[0-5]\d{0,1} | [6-9])?
                [ ]*
                (%(open)sam4%(close)s am | pm | p | a )
            )
        )?
    )
    """ % {'open': open, 'close': close,
           'future': timedelta_regexp(None),
           'past': timedelta_regexp(None)}

datetime_regexp_pattern = re.compile(r'^%s$' % datetime_regexp(''), re.UNICODE + re.MULTILINE + re.IGNORECASE + re.DOTALL + re.VERBOSE)

def item_regex(prefix):
    return r"""
(?P<%(prefix)sitem>^
 \s*
 \{
   (?P<%(prefix)sstatus>[123])
  \}
 \s*
 (?P<%(prefix)stitle>.*?)\s
 (?P<%(prefix)sstart>%(start)s)
 \s*-\s*
 (?P<%(prefix)send>%(end)s)
 \s*
$)
""" % {'prefix': prefix,
       'start': datetime_regexp(None),
       'end': datetime_regexp(None)}

item_regex_pattern = re.compile(r'^%s$' % item_regex(''), re.UNICODE + re.MULTILINE + re.IGNORECASE + re.VERBOSE)

def read_timedelta(string):
    match = timedelta_regexp_pattern.search(string)
    assert(match)

    years = weeks = days = hours = minutes = seconds = miliseconds = microseconds = 0
    if match.group('years'): years = int(match.group('years'))
    if match.group('weeks'): weeks = int(match.group('weeks'))
    if match.group('days'): days = int(match.group('days'))
    if match.group('hours'): hours = int(match.group('hours'))
    if match.group('minutes'): minutes = int(match.group('minutes'))
    if match.group('seconds'): seconds = int(match.group('seconds'))
    if match.group('miliseconds'): miliseconds = int(match.group('miliseconds'))
    if match.group('microseconds'): microseconds = int(match.group('microseconds'))
    return datetime.timedelta(years * 365 + weeks * 7 + days,
                              hours * 60 * 60 + minutes * 60 + seconds,
                              miliseconds * 1000 + microseconds)

def read_datetime(string):
    match = datetime_regexp_pattern.search(string)
    assert(match)

    if match.group('dawnoftime'):
        return datetime.datetime(datetime.MINYEAR, 1, 1)
    elif match.group('now'):
        return datetime.datetime.now()
    elif match.group('future'):
        return datetime.datetime.now() + read_timedelta(match.group('future'))
    elif match.group('past'):
        return datetime.datetime.now() - read_timedelta(match.group('past'))

    # yyyy/mm/dd: 2006/05/10; 06/05/10,
    if match.group('date1'):
        if len(match.group('year1')) == 2:
            year = '20%s' % match.group('year1')
        else:
            year = match.group('year1')

        month = match.group('month1')
        day = match.group('day1')

    # M dd, yyyy: May 10, 2006; Jan 10th, 2006; Jan 10, 06
    elif match.group('date2'):
        if len(match.group('year2')) == 2:
            year = '20%s' % match.group('year2')
        else:
            year = match.group('year2')

        month = getNumericalMonth(match.group('month2'))
        if not month:
            raise EventcalError('invalid_date')

        day = match.group('day2')

    # yyyymmdd: 20060510, 060510
    elif match.group('date3'):
        if len(match.group('year3')) == 2:
            year = '20%s' % match.group('year3')
        else:
            year = match.group('year3')

        month = match.group('month3')
        day = match.group('day3')

    elif len(string.strip()) == 0:
        return ''

    else:
        raise EventcalError('invalid_date')

    # 12h with ':': 12:00; 9:00pm
    if match.group('time1'):
        hour = int(match.group('hour1'))
        if match.group('minute1'):
            min = int(match.group('minute1'))
        else:
            min = 0

        if hour < 12 and match.group('am1').lower() == 'pm':
            hour += 12

    # 24h with ':': 12:00; 23:00
    elif match.group('time2'):
        hour = int(match.group('hour2'))
        if match.group('minute2'):
            min = int(match.group('minute2'))
        else:
            min = 0

    # 24h without ':': 1200; 2300
    elif match.group('time3'):
        hour = int(match.group('hour3'))
        if match.group('minute3'):
            min = int(match.group('minute3'))
        else:
            min = 0

    # 12h without ':': 1200; 0900pm
    elif match.group('time4'):

        hour = int(match.group('hour4'))
        if match.group('minute4'):
            min = int(match.group('minute4'))
        else:
            min = 0

        if hour < 12 and match.group('am4').lower() == 'pm':
            hour += 12

    elif len(string.strip()) == 0:
        return ''

    else:
        raise EventcalError('invalid_time X%sX' % repr(string))

    return datetime.datetime(int(year), int(month), int(day), int(hour), int(min))

def searchPages(request, needle):
    return MoinMoin.search.searchPages(
        request,
        MoinMoin.search.QueryParser().parse_query(needle)).hits

class multisearch:
    def __init__(self, pattern, string):
        self.pattern = pattern
        self.string = string
        self.pos = 0
    def __iter__(self):
        return self
    def next(self):
        m = self.pattern.search(self.string, self.pos)
        if m is None: raise StopIteration
        self.pos = m.end() + 1
        return m

def parsePage(request, page):
    items = []
    for matchitem in multisearch(item_regex_pattern, page.get_raw_body()):
        item = {}
        item['page'] = page.page_name
        item['categories'] = page.page_name.split('/')
        item['status'] = int(matchitem.group('status'))
        item['title'] = matchitem.group('title')
        item['start'] = read_datetime(matchitem.group('start'))
        item['end'] = read_datetime(matchitem.group('end'))
        item['length'] = item['end'] - item['start']
        items.append(item)
    return items

def parseCategory(request, category):
    items = []
    for page in searchPages(request, category):
        items.extend(parsePage(request, MoinMoin.Page.Page(request, page.page_name)))
    return items


import csv
import json
import ast
import codecs
from zipfile import ZipFile
import os

dirpath = os.getcwd()

def fct():

  # Duplicated or no files?
  count = len([name for name in os.listdir(dirpath+'/script/dataSource') if name.endswith(".zip") and "_LinkedInDataExport_" in name])
  if count == 0:
     print ("No LinkedIn Data")
  elif count > 1:
     print ("Duplicated LinkedIn File")
  else:
    # Get the file, unzip and fix it
    for r, d, f in os.walk(dirpath+"/script/dataSource"):
      for file in f:
        #if file.endswith(".zip") and file.startswith("Basic_LinkedInDataExport_"):
        if file.endswith(".zip") and "_LinkedInDataExport_" in file:
          inputFolderZipped = os.path.join(r,file)

          inputFolder = dirpath+'/script/dataSource/LinkedIn_data'
          if not os.path.exists(inputFolder):
             os.mkdir(inputFolder)

          #with zipfile.ZipFile(inputFolderZipped, 'r') as zip_ref:
          #   zip_ref.extractall(inputFolder)

          print ("LinkedIn - Unzip ")

          # Create a ZipFile Object and load sample.zip in it
          with ZipFile(inputFolderZipped, 'r') as zipObj:
             # Get a list of all archived file names from the zip
             listOfFileNames = zipObj.namelist()
             # Iterate over the file names
             for fileName in listOfFileNames:
                 # Check filename endswith csv
                 if fileName.endswith('.csv'):
                     # Extract a single file from zip
                     zipObj.extract(fileName, inputFolder)

          print ("LinkedIn - Fix")
          jsonInputFolder = dirpath+'/script/dataSource/json-LinkedIn_data'
          if not os.path.exists(jsonInputFolder):
             os.mkdir(jsonInputFolder)

          for r, d, f in os.walk(inputFolder):
            file_path = r.replace(inputFolder,jsonInputFolder)
            if not os.path.exists(file_path):
              os.mkdir(file_path)

          # root, d=directories, f = files
          for r, d, f in os.walk(inputFolder):
            file_path = r.replace(inputFolder,jsonInputFolder)
            for file in f:
              if file in ["Profile.csv","Connections.csv","Education.csv","Positions.csv","Skills.csv"]: #file.endswith(".csv")
                with codecs.open(os.path.join(r, file), 'r', encoding='utf8') as f_csv: #encoding='utf8'  mac_roman ISO-8859-1
                  reader = csv.DictReader(f_csv)
                  rows = list(reader)

                  json_data = json.dumps(list(rows))
                  json_arr = ast.literal_eval(json_data)

                  json_str=""
                  for i in range(len(json_arr)):
                     json_str = json_str + str(json.dumps(json_arr[i])) + "\n"

                  newFile = file.split('.')[0]+'.json'

                  with codecs.open(os.path.join(file_path,newFile), 'w', encoding='utf8') as f_json:
                     f_json.write(json_str)
                  f_json.close()


from enum import Enum
from typing import List, Optional, Union

class EOProductLevel(str, Enum):
    L1C = "l1c"
    L2A = "l2a"
    L3A = "l3a"
    RTC = "rtc"

class STACBand(str, Enum):
    BLUE = "blue"
    GREEN = "green"
    RED = ("red",)
    REDEDGE1 = "rededge1"
    REDEDGE2 = "rededge2"
    REDEDGE3 = "rededge3"
    NIR = "nir"
    NIR08 = "nir08"
    NIR09 = "nir09"
    CIRRUS = "cirrus"
    SCL = "scl"
    SWIR16 = "swir16"
    SWIR22 = "swir22"
    VV = "vv"
    VH = "vh"

    def __str__(self):
        return self.value

class EOProductSource(str, Enum):
    SENTINEL2 = "sentinel-2"
    SENTINEL1 = "sentinel-1"
    VENUS = "venus"

class EOProductType(str, Enum):

    DTYPE: Optional[str]
    RESOLUTION: Optional[int]
    FILL_VALUE: Optional[Union[int, float]]
    DEFAULT_ASSETS: Optional[List[str]]
    RGB: Optional[List[str]]

    def __new__(
        cls,
        type: str,
        dtype: Optional[str] = None,
        resolution: Optional[int] = None,
        fill_value: Optional[Union[int, float]] = None,
        default_assets: Optional[List[str]] = [],
        rgb_names: Optional[List[str]] = [],
    ):
        obj = str.__new__(cls, type)  # type: ignore
        obj._value_ = type
        obj.DTYPE = dtype
        obj.RESOLUTION = resolution
        obj.FILL_VALUE = fill_value
        obj.DEFAULT_ASSETS = default_assets
        obj.RGB = rgb_names

        return obj

    SENTINEL2_L2A = (
        f"{EOProductSource.SENTINEL2}-{EOProductLevel.L2A}",
        "uint16",
        10,
        0,
        [
            STACBand.BLUE,
            STACBand.GREEN,
            STACBand.RED,
            STACBand.REDEDGE1,
            STACBand.REDEDGE2,
            STACBand.REDEDGE3,
            STACBand.NIR,
            STACBand.NIR08,
            STACBand.NIR09,
            STACBand.CIRRUS,
            STACBand.SCL,
            STACBand.SWIR16,
            STACBand.SWIR22,
        ],
        [
            STACBand.BLUE,
            STACBand.GREEN,
            STACBand.RED,
        ],
    )
    VENUS_L2A = (
        f"{EOProductSource.VENUS}-{EOProductLevel.L2A}",
        "float32",
        5,
        0,
        [
            "image_file_SRE_B3",
            "image_file_SRE_B4",
            "image_file_SRE_B7",
            "image_file_SRE_B8",
            "image_file_SRE_B9",
            "image_file_SRE_B10",
        ],
        [
            "image_file_SRE_B3",
            "image_file_SRE_B4",
            "image_file_SRE_B7",
        ],
    )

    def __str__(self):
        return self.value

    @property
    def source(self):
        return EOProductSource(str(self.value).rsplit("-", 1)[0])

    @property
    def level(self):
        return EOProductLevel(str(self.value).rsplit("-", 1)[1])

class SCLMaskLabel:
    # Note: This is for Sentinel2 L2A only
    NO_DATA = 0
    SATURED_OR_DEFECTED = 1
    DARK_AREA_PIXELS = 2
    CLOUD_SHADOWS = 3
    VEGETATION = 4
    NOT_VEGETATED = 5
    WATER = 6
    UNCLASSIIFED = 7
    CLOUD_MEDIUM_PROBABILITY = 8
    CLOUD_HIGH_PROBABILITY = 9
    THIN_CIRRUS = 10
    SNOW = 11


# Data
import numpy as np

# Intelligence
from sklearn.cluster import KMeans, DBSCAN
from sklearn import metrics
import hdbscan

# Visualization
# import matplotlib.pyplot as plt

# System
import datetime
import os
import time
import sys
import importlib as imp
import random as rand
import shutil

sys.dont_write_bytecode = True

now = datetime.datetime.now()
dateTime = str(now.strftime("%Y-%m-%d  %H:%M:%S"))
datetime_dir = str(now.strftime("%Y-%m-%d__%H-%M-%S"))

# Directory will be determined by the user
current_directory = ""

# CLUSTERING INTERFACE
class ClusteringSession(object):
    def run(self, params, threads):
        raise NotImplementedError
    def save_results(self, location):
        raise NotImplementedError
    def save_plots(self, location):
        raise NotImplementedError

# KMEANS
class KMeansSession(ClusteringSession):
    def __init__(self):
        self.n_clusters = 0
        self.data = None
        self.kmeans = None
        self.cluster_centers = None
        self.lables = None
        self.silhouette_score = -1
        self.n_init = 0
        self.n_jobs = 0

    def run(self, data, params, threads):
        self.data = data
        self.n_clusters = int(params['nclusters'])

        kmeans = KMeans(n_clusters=self.n_clusters)
        self.kmeans = kmeans

        kmeans.fit(data)
        self.cluster_centers = kmeans.cluster_centers_
        self.labels = kmeans.labels_

        sample_size = 0
        if len(data) >= 20000:
            sample_size = 20000
        else:
            sample_size = len(data)
        self.silhouette_score = metrics.silhouette_score(data, self.labels, metric='euclidean', sample_size=sample_size)

        return {'sil_score': self.silhouette_score,
                'labels': self.labels.tolist(),
                'n_clusters': self.n_clusters}

# DBSCAN
class DBSCANSession(ClusteringSession):
    def __init__(self):
        self.labels = []
        self.n_clusters = 0
        self.eps = 0
        self.min_samples = 0
        self.silhouette_score = 0
        self.data = None
        self.core_samples_mask = None

    def run(self, data, params, threads):
        self.eps = float(params['eps'])
        self.min_samples = int(params['min'])
        self.data = data
        db = DBSCAN(eps=self.eps, min_samples=self.min_samples).fit(data)

        # Used for plotting
        self.core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
        self.core_samples_mask[db.core_sample_indices_] = True

        self.labels = db.labels_
        self.n_clusters = len(set(self.labels)) - (1 if -1 in self.labels else 0)

        sample_size = 0
        if len(data) >= 20000:
            sample_size = 20000
        else:
            sample_size = len(data)
        self.silhouette_score = metrics.silhouette_score(data, self.labels, metric='euclidean', sample_size=sample_size)

        return {'sil_score': self.silhouette_score,
                'labels': self.labels.tolist(),
                'n_clusters': self.n_clusters}

# HDBSCAN
class HDBSCANSession(ClusteringSession):
    def __init__(self):
        self.labels = []
        self.min_samples = 0
        self.silhouette_score = 0
        self.data = None
        self.n_clusters = 0
        #self.core_samples_mask = None

    def run(self, data, params, threads):
        self.min_samples = int(params['min'])
        self.data = data

        hdb = hdbscan.HDBSCAN(min_samples=self.min_samples, core_dist_n_jobs=threads)
        # print(hdb)
        self.labels = hdb.fit_predict(data)
        self.n_clusters = len(set(self.labels)) - 1

        sample_size = 0
        if len(data) >= 20000:
            sample_size = 20000
        else:
            sample_size = len(data)
        self.silhouette_score = metrics.silhouette_score(data, self.labels, metric='euclidean', sample_size=sample_size)

        del hdb

        return {'sil_score': self.silhouette_score,
                'n_clusters': self.n_clusters}

    def save_results(self, location):
        return super().save_results(location)

    def save_plots(self, location=""):
        current_directory = location + "RESULTS/HDBSCAN/" + datetime_dir
        print(current_directory)
        os.makedirs(current_directory)

# CLUSTER SESSION DICT
SESSION_MAP = {
    'kmeans': KMeansSession,
    'hdbscan': HDBSCANSession,
    'dbscan': DBSCANSession
}

PARAMS_MAP = {
    'kmeans': ['nclusters'],
    'hdbscan': ['min'],
    'dbscan': ['min', 'eps']
}


from typing import Union, Any

import aiohttp

from lmk.utils.ws import WebSocket

async def send_signal(socket_path: str, signal: Union[str, int]) -> None:
    connector = aiohttp.UnixConnector(path=socket_path)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.post(
            "http://daemon/signal", json={"signal": signal}
        ) as response:
            if response.status == 200:
                return
            raise ResponseError(response.status, await response.text())

async def set_notify_on(socket_path: str, notify_on: str) -> None:
    connector = aiohttp.UnixConnector(path=socket_path)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.post(
            "http://daemon/set-notify-on", json={"notify_on": notify_on}
        ) as response:
            if response.status == 200:
                return
            raise ResponseError(response.status, await response.text())

async def wait_for_job(socket_path: str, wait_for: str = "run") -> Any:
    connector = aiohttp.UnixConnector(path=socket_path)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with WebSocket(session, f"http://daemon/wait?wait_for={wait_for}") as ws:
            async for message in ws:
                if not message["ok"]:
                    raise Exception(f"{message['error_type']}: {message['error']}")
                return message

class ResponseError(Exception):
    """ """

    def __init__(self, status: int, data: str) -> None:
        self.status = status
        self.data = data
        super().__init__(f"Request failed with status {status}: {data}")


#! /usr/bin/env python3
#
# Read datagrams from one port and forward them to another host/port
#
# March-2022, Pat Welch, pat@mousebrains.com

from TPWUtils import Logger
from argparse import ArgumentParser
import socket

parser = ArgumentParser()
Logger.addArgs(parser)
parser.add_argument("--listen", type=int, default=10034, help="UDP port to listen to")
parser.add_argument("--ipv4", type=str, default="100.124.34.2",
        help="IP address to send datagrams to")
parser.add_argument("--port", type=int, default=8982, help="UDP port to send datagrams to")
args = parser.parse_args()

logger = Logger.mkLogger(args, fmt="%(asctime)s %(levelname)s: %(message)s")

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s.bind(("", args.listen))
    while True:
        (data, senderAddr) = s.recvfrom(1024)
        index = data.find(b"!")
        if index < 0:
            index = data.find(b"$")
            if index < 0:
                logger.info("Dropping %s", data)
                continue
        try:
            logger.info("Received %s", str(data[index:], "UTF-8").strip())
            s.sendto(data[index:].strip(), (args.ipv4, args.port))
        except:
            logger.exception("Unable to send %s", data)


import pygame
from settings import *
from tile import *
from player import *
from debug import debug
class Level:
    def __init__(self):

        # get the display surface anywhere of our code
        self.display_surface = pygame.display.get_surface()

        # creamos los grupos de sprite
        # sprite es un modulo con clases de objetos basicos de juego
        # pygame.sprite.Group es un contenedor de clases con puede mantener y administrar multiples objetos sprite
        self.visible_sprites = pygame.sprite.Group()
        self.obstacles_sprites = pygame.sprite.Group()
        # creamos el atributo create_map
        self.create_map()

    def create_map(self):
        for row_index, row in enumerate(WORLD_MAP):
            for col_index, col in enumerate(row):
                x = col_index*TILESIZE
                y = row_index*TILESIZE
                if col == 'x':
                    Tile((x,y),([self.visible_sprites],[self.obstacles_sprites]))
                if col == 'p':
                    self.player = Player((x,y),[self.visible_sprites])
                    debug(self.player.direction)

    def run(self):
        # quiero que dibujes esta variable que es conciderada un grupo de sprits dado que fue guardad en el contenedor
        # pygame.sprite.Group, y quiero que me lo muestres
        self.visible_sprites.draw(self.display_surface)
        # funcion que hace part de la clase Group y actualiza los sprites

        debug(self.player.direction)


# -*- coding: utf-8 -*-
from .models import MenuItem
from django.template.loader import render_to_string

def menuhin_breadcrumbs(request):
    """
    How breadcrumbs will be rendered on the site, to a depth of grandchild.
    """
    node0 = MenuItem(title='default', site_id=1,
                     uri='/', depth=0)
    node0.clean()
    node1 = MenuItem(title='child', site_id=1,
                     uri='/child/', depth=1)
    node1.clean()
    node2 = MenuItem(title='grandchild', site_id=1,
                     uri='/grandchild/', depth=2)
    node2.clean()
    return render_to_string('menuhin/show_breadcrumbs.html', {
        'ancestor_nodes': [node0, node1],
        'menu_node': node2,
    })


from PIL import Image
import matplotlib.pyplot as plt

#%%
file_path = "/JSY/images/bichon02.jpg"
img = Image.open(file_path)
print(type(img))

plt.imshow(img)
plt.axis("off")
plt.show()


import unittest
import zipfile
import tempfile
import os
import shutil
import io

from requests import session
import requests_mock

import remotezip as rz

class TmpDir(object):
    """Create a tmp directory that is automatically destroyed when the context exit"""
    def __enter__(self):
        self.tmpdir = tempfile.mktemp()
        os.mkdir(self.tmpdir)
        return self.tmpdir

    def __exit__(self, exc_type, exc_value, traceback):
        shutil.rmtree(self.tmpdir)

class ServerSimulator:
    def __init__(self, fname):
        self._fname = fname

    def serve(self, request, context):
        from_byte, to_byte = rz.RemoteFetcher.parse_range_header(request.headers['Range'])
        with open(self._fname, 'rb') as f:
            if from_byte < 0:
                f.seek(0, 2)
                size = f.tell()
                f.seek(max(size + from_byte, 0), 0)
                init_pos = f.tell()
                content = f.read(min(size, -from_byte))
            else:
                f.seek(from_byte, 0)
                init_pos = f.tell()
                content = f.read(to_byte - from_byte + 1)

        context.headers['Content-Range'] = rz.RemoteFetcher.build_range_header(init_pos, init_pos + len(content))
        return content

class LocalFetcher(rz.RemoteFetcher):
    def fetch(self, data_range, stream=False):
        with open(self._url, 'rb') as f:
            f.seek(0, 2)
            fsize = f.tell()

            range_min, range_max = data_range
            if range_min < 0:
                range_max = fsize - 1
                range_min = max(fsize + range_min, 0)
            elif range_max is None:
                range_max = fsize - 1

            content_range="bytes {range_min}-{range_max}/{fsize}".format(**locals())
            f.seek(range_min, 0)

            f = io.BytesIO(f.read(range_max - range_min + 1))
            buff = rz.PartialBuffer(f, range_min, range_max - range_min + 1, stream=stream)
        return buff

class TestPartialBuffer(unittest.TestCase):
    def setUp(self):
        if not hasattr(self, 'assertRaisesRegex'):
            self.assertRaisesRegex = self.assertRaisesRegexp

    def verify(self, stream):
        pb = rz.PartialBuffer(io.BytesIO(b'aaaabbcccdd'), 10, 11, stream=stream)
        self.assertEqual(pb.read(5), b'aaaab')
        self.assertEqual(pb.read(3), b'bcc')
        self.assertEqual(pb.read(3), b'cdd')
        pb.close()

    def test_static(self):
        self.verify(stream=False)

    def test_static_seek(self):
        pb = rz.PartialBuffer(io.BytesIO(b'aaaabbcccdd'), 10, 11, stream=False)
        self.assertEqual(pb.seek(10, 0), 10)
        self.assertEqual(pb.read(5), b'aaaab')
        self.assertEqual(pb.seek(12, 0), 12)
        self.assertEqual(pb.read(5), b'aabbc')
        self.assertEqual(pb.seek(20, 0), 20)
        self.assertEqual(pb.read(1), b'd')
        self.assertEqual(pb.seek(10, 0), 10)
        self.assertEqual(pb.seek(2, 1), 12)

    def test_static_read_no_size(self):
        pb = rz.PartialBuffer(io.BytesIO(b'aaaabbcccdd'), 10, 11, stream=False)
        self.assertEqual(pb.read(), b'aaaabbcccdd')
        self.assertEqual(pb.tell(), 21)
        self.assertEqual(pb.seek(15, 0), 15)
        self.assertEqual(pb.read(), b'bcccdd')
        self.assertEqual(pb.seek(-5, 2), 16)
        self.assertEqual(pb.read(), b'cccdd')
        self.assertEqual(pb.read(), b'')

    def test_static_out_of_bound(self):
        pb = rz.PartialBuffer(io.BytesIO(b'aaaabbcccdd'), 10, 11, stream=False)
        with self.assertRaises(rz.OutOfBound):
            pb.seek(21, 0)

    def test_stream(self):
        self.verify(stream=True)

    def test_stream_forward_seek(self):
        pb = rz.PartialBuffer(io.BytesIO(b'aaaabbcccdd'), 10, 11, stream=True)
        self.assertEqual(pb.seek(12, 0), 12)
        self.assertEqual(pb.read(3), b'aab')
        self.assertEqual(pb.seek(2, 1), 17)
        self.assertEqual(pb.read(), b'ccdd')

        with self.assertRaisesRegex(rz.OutOfBound, "Negative seek not supported"):
            pb.seek(12, 0)

class TestRemoteIO(unittest.TestCase):
    def fetch_fun(self, data_range, stream=False):
        # simulate 200k file
        fsize = 200 * 1024
        min_range, max_range = data_range
        if min_range < 0:
            size = -min_range
            min_range = fsize - size
        else:
            size = max_range - min_range + 1

        if stream:
            data = b's' * size
        else:
            data = b'x' * size
        return rz.PartialBuffer(io.BytesIO(data), min_range, size, stream=stream)

    def test_simple(self):
        rio = rz.RemoteIO(fetch_fun=self.fetch_fun)
        self.assertIsNone(rio._file_size)
        rio.seek(0, 2)  # eof
        self.assertIsNotNone(rio._file_size)
        self.assertEqual(rio.tell(), 200 * 1024)

        curr_buffer = rio.buffer

        rio.seek(-20, 2)
        self.assertEqual(rio.read(2), b'xx')
        self.assertIs(rio.buffer, curr_buffer)  # buffer didn't change
        self.assertEqual(rio.read(), b'x' * 18)
        self.assertEqual(rio.tell(), 200 * 1024)

        rio.seek(120*1024, 0)
        self.assertEqual(rio.read(2), b'xx')
        self.assertIsNot(rio.buffer, curr_buffer)  # buffer changed
        rio.close()

    def test_file_access(self):
        rio = rz.RemoteIO(fetch_fun=self.fetch_fun)
        rio.seek(0, 2)  # eof
        curr_buffer = rio.buffer
        # we have two file, one at pos 156879 with size 30k and the last at pos
        rio.set_position_to_size({15687: 30 * 1024, 50354: 63000})
        rio.seek(15687, 0)
        self.assertEqual(rio.tell(), 15687)
        self.assertEqual(rio.read(5), b'sssss')
        self.assertIsNot(rio.buffer, curr_buffer)  # buffer changed
        curr_buffer = rio.buffer

        # re-read the same file
        rio.seek(15687, 0)
        self.assertEqual(rio.read(4), b'ssss')
        self.assertEqual(repr(rio.buffer), "<PartialBuffer off=15687 size=30720 stream=True>")
        self.assertIsNot(rio.buffer, curr_buffer)  # buffer changed
        curr_buffer = rio.buffer

        # move to next file
        rio.seek(50354, 0)
        self.assertEqual(rio.read(4), b'ssss')
        self.assertEqual(repr(rio.buffer), "<PartialBuffer off=50354 size=63000 stream=True>")
        self.assertIsNot(rio.buffer, curr_buffer)  # buffer changed
        curr_buffer = rio.buffer

        # seek forward
        rio.seek(60354, 0)
        self.assertEqual(rio.read(4), b'ssss')
        self.assertIs(rio.buffer, curr_buffer)      # buffer didn't change

        # seek backward
        rio.seek(51354, 0)
        self.assertEqual(rio.read(4), b'ssss')
        self.assertIsNot(rio.buffer, curr_buffer)   # buffer changed

        rio.close()

class TestLocalFetcher(unittest.TestCase):
    def test_build_range_header(self):
        header = rz.RemoteFetcher.build_range_header(0, 10)
        self.assertEqual(header, 'bytes=0-10')

        header = rz.RemoteFetcher.build_range_header(80, None)
        self.assertEqual(header, 'bytes=80-')

        header = rz.RemoteFetcher.build_range_header(-123, None)
        self.assertEqual(header, 'bytes=-123')

    def test_parse_range_header(self):
        range_min, range_max = rz.RemoteFetcher.parse_range_header('bytes 0-11/12')
        self.assertEqual(range_min, 0)
        self.assertEqual(range_max, 11)

        range_min, range_max = rz.RemoteFetcher.parse_range_header('bytes 10-21/40')
        self.assertEqual(range_min, 10)
        self.assertEqual(range_max, 21)

        range_min, range_max = rz.RemoteFetcher.parse_range_header('bytes -123')
        self.assertEqual(range_min, -123)
        self.assertIsNone(range_max)

class TestRemoteZip(unittest.TestCase):
    @staticmethod
    def make_big_header_zip(fname, entries):
        with zipfile.ZipFile(fname, 'w', compression=zipfile.ZIP_DEFLATED) as zip:
            for i in range(entries):
                zip.writestr('test_long_header_file_{0}'.format(i), 'x')

    def test_big_header(self):
        with TmpDir() as dire:
            fname = os.path.join(dire, 'test.zip')
            self.make_big_header_zip(fname, 2000)

            with rz.RemoteZip(fname, fetcher=LocalFetcher) as zfile:
                for i, finfo in enumerate(zfile.infolist()):
                    self.assertEqual(finfo.filename, 'test_long_header_file_{0}'.format(i))
                    self.assertEqual(finfo.file_size, 1)

                self.assertIsNone(zfile.testzip())

    @staticmethod
    def make_unordered_zip_file(fname):
        with zipfile.ZipFile(fname, 'w') as zip:
            zip.writestr("fileA", "A" * 300000 + 'Z')
            zip.writestr("fileB", "B" * 10000 + 'Z')
            zip.writestr("fileC", "C" * 100000 + 'Z')
            info_list = zip.infolist()
            info_list[0], info_list[1] = info_list[1], info_list[0]

    def test_unordered_fileinfo(self):
        """Test that zip file with unordered fileinfo records works as well. Fix #13."""
        with TmpDir() as dire:
            fname = os.path.join(dire, 'test.zip')
            self.make_unordered_zip_file(fname)

            with rz.RemoteZip(fname, fetcher=LocalFetcher) as zfile:
                names = zfile.namelist()
                self.assertEqual(names, ['fileB', 'fileA', 'fileC'])
                with zfile.open('fileB', 'r') as f:
                    self.assertEqual(f.read(), b"B" * 10000 + b'Z')
                with zfile.open('fileA', 'r') as f:
                    self.assertEqual(f.read(), b"A" * 300000 + b'Z')
                with zfile.open('fileC', 'r') as f:
                    self.assertEqual(f.read(), b"C" * 100000 + b'Z')
                self.assertIsNone(zfile.testzip())

    def test_fetch_part(self):
        # fetch a range
        expected_headers = {'Range': 'bytes=10-20'}
        headers = {'Content-Range': 'Bytes 10-20/30'}
        with requests_mock.Mocker() as m:
            m.register_uri("GET", "http://test.com/file.zip", content=b"abc", status_code=200, headers=headers,
                           request_headers=expected_headers)
            fetcher = rz.RemoteFetcher("http://test.com/file.zip")
            buffer = fetcher.fetch((10, 20), stream=True)
            self.assertEqual(buffer.tell(), 10)
            self.assertEqual(buffer.read(3), b"abc")

    def test_fetch_ending(self):
        # fetch file ending
        expected_headers = {'Range': 'bytes=-100'}
        headers = {'Content-Range': 'Bytes 10-20/30'}
        with requests_mock.Mocker() as m:
            m.register_uri("GET", "http://test.com/file.zip", content=b"abc", status_code=200, headers=headers,
                           request_headers=expected_headers)
            fetcher = rz.RemoteFetcher("http://test.com/file.zip")
            buffer = fetcher.fetch((-100, None), stream=True)
            self.assertEqual(buffer.tell(), 10)
            self.assertEqual(buffer.read(3), b"abc")

    def test_fetch_ending_unsupported_suffix(self):
        # fetch file ending
        expected_headers = {'Range': 'bytes=900-999'}
        headers = {'Content-Range': 'Bytes 900-999/1000'}
        with requests_mock.Mocker() as m:
            m.head("http://test.com/file.zip", status_code=200, headers={'Content-Length': '1000'})
            m.get("http://test.com/file.zip", content=b"abc", status_code=200, headers=headers,
                  request_headers=expected_headers)
            fetcher = rz.RemoteFetcher("http://test.com/file.zip", support_suffix_range=False)
            buffer = fetcher.fetch((-100, None), stream=True)
            self.assertEqual(buffer.tell(), 900)
            self.assertEqual(buffer.read(3), b"abc")

    @staticmethod
    def make_zip_file(fname):
        with zipfile.ZipFile(fname, 'w', compression=zipfile.ZIP_DEFLATED) as zip:
            zip.writestr('file1', 'X' + ('A' * 10000) + 'Y')
            zip.writestr('file2', 'short content')
            zip.writestr('file3', '')
            zip.writestr('file4', 'last file')

    def test_interface(self):
        with TmpDir() as dire:
            fname = os.path.join(dire, 'test.zip')
            self.make_zip_file(fname)

            zfile = rz.RemoteZip(fname, min_buffer_size=50, fetcher=LocalFetcher)
            ilist = zfile.infolist()
            self.assertEqual(ilist[0].filename, 'file1')
            self.assertEqual(ilist[0].file_size, 10002)
            self.assertEqual(zfile.read('file1'), b'X' + (b'A' * 10000) + b'Y')
            self.assertEqual(zfile.read('file1'), b'X' + (b'A' * 10000) + b'Y')

            self.assertEqual(ilist[1].filename, 'file2')
            self.assertEqual(ilist[1].file_size, 13)
            self.assertEqual(zfile.read('file2'), b'short content')

            self.assertEqual(ilist[2].filename, 'file3')
            self.assertEqual(ilist[2].file_size, 0)
            self.assertEqual(zfile.read('file3'), b'')

            self.assertEqual(ilist[3].filename, 'file4')
            self.assertEqual(ilist[3].file_size, 9)
            self.assertEqual(zfile.read('file4'), b'last file')

            self.assertIsNone(zfile.testzip())

    def test_zip64(self):
        zfile = rz.RemoteZip('test_data/zip64.zip', fetcher=LocalFetcher)
        self.assertEqual(zfile.read('big_file'), b'\x00' * (1024*1024))
        self.assertIsNone(zfile.testzip())

    def test_range_not_supported(self):
        with requests_mock.Mocker() as m:
            m.get("http://test.com/file.zip")
            with self.assertRaises(rz.RangeNotSupported):
                rz.RemoteZip("http://test.com/file.zip")

    def test_custom_session(self):
        custom_session = session()
        custom_session.headers.update({"user-token": "1234"})

        with TmpDir() as dire:
            fname = os.path.join(dire, 'test.zip')
            self.make_zip_file(fname)

            server = ServerSimulator(fname)
            expected_headers = {
                "user-token": "1234"
            }
            with requests_mock.Mocker() as m:
                m.register_uri("GET", "http://test.com/file.zip", content=server.serve, status_code=200, request_headers=expected_headers)
                rz.RemoteZip("http://test.com/file.zip", session=custom_session)

    # TODO: test get_position2size

if __name__ == '__main__':
    unittest.main()


import nltk
from sklearn.preprocessing import MultiLabelBinarizer
from nltk.tokenize import word_tokenize

# Более реалистичной является ситуация, когда есть данные, где каждое наблюдение
# содержит твит, и мы хотим преобразовать эти предложения в признаки отдельных
# частей речи (например, признак с 1, если присутствует собственное существительное,
# и 0 в противном случае):

if __name__ == '__main__':
    tweets = ["I am eating a burrito for breakfast",
              "Political science is an amazing field",
              "San Francisco is an awesome city"]

    tagged_tweets = []

    # Пометить каждое слово и каждый твит
    for tweet in tweets:
        tweet_tag = nltk.pos_tag(word_tokenize(tweet))
        tagged_tweets.append([tag for word, tag in tweet_tag])

    # Применить кодирование с одним активным состоянием, чтобы
    # конвертировать метки в признаки
    one_hot_multi = MultiLabelBinarizer()
    X = one_hot_multi.fit_transform(tagged_tweets)

    print(X, "\n")

    # Показать имена признаков
    print(one_hot_multi.classes_)


from django.shortcuts import render, redirect
from .models import Image

def index(request):
	images = Image.objects.all()
	context = { 'images' : images}
	return render(request, 'index.html', context)

def uploader(request):
	newImage = Image()
	newImage.title = request.POST['title']
	newImage.about = request.POST['about']
	newImage.img = request.FILES['img']
	newImage.save()
	return redirect('home')


from django.db import models
from django import forms
from django.contrib.auth.models import AbstractUser
from django.db.models import Q

class User(AbstractUser):

    USER_TYPE_CHOICES = (
        (1,'patient'),
        (2,'doctor'),
        (3,'staff'),
    )
    user_type = models.PositiveSmallIntegerField(null=True,choices = USER_TYPE_CHOICES)

    date_of_birth = models.DateField(auto_now=False, auto_now_add=False, null=True)
    phone = models.CharField(null=True, max_length=15)

    GENDER_CHOICES = (
        ('Male', 'Male'),
        ('Female', 'Female'),
        ('Other', 'Other'),
    )
    gender = models.CharField(
        max_length = 6,
        choices = GENDER_CHOICES,
        null = True,
        default = 'Other',
    )

    BLOOD_GROUP_CHOICES = (
        ('A+','A+'),
        ('A-','A-'),
        ('B+','B+'),
        ('B-','B-'),
        ('O+','O+'),
        ('O-','O-'),
        ('AB+','AB+'),
        ('AB-','AB-'),
        ('Other','Other'),
    )
    blood_group = models.CharField(
        max_length = 5,
        choices = BLOOD_GROUP_CHOICES,
        null = True,
        default = 'Other',
    )

class Appointment(models.Model):
    # pass
    id = models.AutoField(primary_key = True)
    patient = models.ForeignKey(
        User,
        on_delete = models.CASCADE,
        limit_choices_to = Q(user_type = 1), # type 1 = patient
        related_name = 'patient',
        null = True,
    )
    doctor = models.ForeignKey(
        User,
        on_delete = models.CASCADE,
        limit_choices_to = Q(user_type = 2), # type 2 = doctor
        related_name = 'doctor',
        null = True,
    )
    date_time = models.DateTimeField(auto_now = True)
    blood_pressure = models.CharField(max_length = 10, null = True)
    breath_rate = models.PositiveSmallIntegerField(null = True) # units: bpm
    pulse_rate = models.PositiveSmallIntegerField(null = True) # units: bpm
    body_temperature = models.DecimalField(max_digits = 5, decimal_places = 2, null=True)
    report = models.TextField(max_length = 500, null = True)
    prescription = models.TextField(max_length = 500, null = True)
    prognosis = models.TextField(max_length = 500, null = True)


from functools import partial

from src.models.scatter import FastScatterW1, Scatter, Scatter_Diffuse_Second, ScatterW1

class FastScatterTransform:
    def __init__(self, device="cpu", agg="moment", alpha=0, power=2, cheb_order=None):
        self.device = device
        self.agg = agg
        self.alpha = alpha
        self.power = power
        self.cheb_order = cheb_order
        assert power == 1 or power == 2
        if power == 2:
            self.scatter_fn = Scatter
        elif cheb_order is not None and cheb_order != "None":
            print("Fast scatterw1")
            self.scatter_fn = partial(FastScatterW1, cheb_order=cheb_order)
        else:
            self.scatter_fn = ScatterW1

    def __call__(self, data):
        data.x = self.scatter_fn(in_channels=data.x.shape[1], agg=self.agg, alpha=self.alpha)(data)
        return data

class FastScatterTransformSort:
    def __init__(self, device="cpu"):
        self.device = device

    def __call__(self, data):
        data.x = Scatter_Diffuse_Second(data.x.shape[1])(data)
        return data


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 12:11:45 2020

@author: Syamanthaka
"""

from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from app import app
# import layouts as lyt
import data_n_graphs as grf

@app.callback([Output('output-data-upload', 'children'),
               Output('x-dropdown', 'options'),
               Output('y-dropdown', 'options'),
               Output('data_df', 'children')],
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename')])
def update_output(contents, filename):
    if contents is not None:
        contents_df, cols, the_df = grf.parse_contents(contents, filename)
        return contents_df, cols, cols, the_df

@app.callback([Output('selected_cols', 'children'),
               Output('output_grf', 'children'),
               Output('main_title', 'placeholder'),
               Output('xtitle', 'placeholder'),
               Output('ytitle', 'placeholder'),
               Output('dd_val', 'value')
               ],
              [Input('data_df', 'children'),
               Input('x-dropdown', 'value'),
               Input('y-dropdown', 'value'),
               Input('grf_typ', 'value'),
               Input('my-color-picker', 'value'),
               Input('main_title', 'value'),
               Input('xtitle', 'value'),
               Input('ytitle', 'value')
              ],
              [State('x-dropdown', 'value'),
               State('y-dropdown', 'value')
              ])
def update_dds(df, x, y, gtyp, sel_color, mtitle_val, xtitle_val, ytitle_val, x_state, y_state):
    if not (x_state and y_state):
        raise PreventUpdate

    main_title = mtitle_val if mtitle_val != '' else x + ' vs ' + y
    xtitle = xtitle_val if xtitle_val != '' else x
    ytitle = ytitle_val if ytitle_val != '' else y

    grf_obj, grf_typ_new =  grf.plot_grf(df, x, y, gtyp, sel_color, main_title, xtitle, ytitle)
    sel_txt = 'You have selected ' + x + ' and ' + y

    return sel_txt, grf_obj, main_title, xtitle, ytitle, grf_typ_new

@app.callback(Output('grf_typ', 'value'),
              [Input('dd_val', 'value')])
def update_bar_type(hidden_val):
    return hidden_val