text:
import json
import logging
import os
import re
import shutil
import sys
import time

import yaml

from bzt import ToolError, TaurusConfigError
from bzt.engine import ScenarioExecutor
from bzt.modules.provisioning import Local
from bzt.modules.selenium import NoseTester, JavaTestRunner, JUnitTester, TestNGTester
from bzt.modules.selenium import SeleniumExecutor, JUnitJar, LoadSamplesReader, LDJSONReader, FuncSamplesReader
from bzt.six import StringIO
from bzt.utils import is_windows, get_full_path
from tests import BZTestCase, local_paths_config, __dir__
from tests.mocks import EngineEmul

class SeleniumTestCase(BZTestCase):
    def setUp(self):
        super(SeleniumTestCase, self).setUp()
        engine_obj = EngineEmul()
        paths = [__dir__() + "/../../bzt/10-base.json", local_paths_config()]
        engine_obj.configure(paths)  # FIXME: avoid using whole engine in particular module test!
        self.obj = SeleniumExecutor()
        self.obj.settings = engine_obj.config.get("modules").get("selenium")
        self.obj.settings.merge({"virtual-display": {"width": 1024, "height": 768}})
        engine_obj.create_artifacts_dir(paths)
        self.obj.engine = engine_obj

    def configure(self, config):
        self.obj.engine.config.merge(config)
        self.obj.execution = self.obj.engine.config.get('execution')
        if isinstance(self.obj.execution, list):
            self.obj.execution = self.obj.execution[0]

    def tearDown(self):
        exc, _, _ = sys.exc_info()
        if exc:
            try:
                stdout_path = os.path.join(self.obj.engine.artifacts_dir, "selenium.out")
                if os.path.exists(stdout_path):
                    stdout = open(stdout_path).read()
                    logging.info('Selenium stdout: """\n%s\n"""', stdout)
            except BaseException:
                pass
            try:
                stdout_path = os.path.join(self.obj.engine.artifacts_dir, "selenium.err")
                if os.path.exists(stdout_path):
                    stderr = open(stdout_path).read()
                    logging.info('Selenium stderr: """\n%s\n"""', stderr)
            except BaseException:
                pass
        self.obj.free_virtual_display()

class TestSeleniumJUnitTester(SeleniumTestCase):
    def test_install_tools(self):
        """
        check installation of selenium-server, junit
        :return:
        """
        dummy_installation_path = __dir__() + "/../../build/tmp/selenium-taurus"
        base_link = "file:///" + __dir__() + "/../data/"

        shutil.rmtree(os.path.dirname(dummy_installation_path), ignore_errors=True)

        selenium_server_link = SeleniumExecutor.SELENIUM_DOWNLOAD_LINK
        SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = base_link + "/selenium-server-standalone-2.46.0.jar"

        junit_link = SeleniumExecutor.JUNIT_DOWNLOAD_LINK
        junit_mirrors = SeleniumExecutor.JUNIT_MIRRORS_SOURCE
        SeleniumExecutor.JUNIT_DOWNLOAD_LINK = base_link + "/junit-4.12.jar"
        SeleniumExecutor.JUNIT_MIRRORS_SOURCE = base_link + "unicode_file"

        hamcrest_link = SeleniumExecutor.HAMCREST_DOWNLOAD_LINK
        SeleniumExecutor.HAMCREST_DOWNLOAD_LINK = base_link + "/hamcrest-core-1.3.jar"

        self.assertFalse(os.path.exists(dummy_installation_path))

        self.obj.settings.merge({"selenium-tools": {
            "junit": {"selenium-server": os.path.join(dummy_installation_path, "selenium-server.jar")}
        }})
        self.obj.settings.merge({"selenium-tools": {
            "junit": {"hamcrest-core": os.path.join(dummy_installation_path, "tools", "junit", "hamcrest-core.jar")}
        }})
        self.obj.settings.merge({"selenium-tools": {
            "junit": {"path": os.path.join(dummy_installation_path, "tools", "junit", "junit.jar")}
        }})

        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/junit/jar/"},
                                  "runner": "junit"})
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JUnitTester)
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "selenium-server.jar")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "tools", "junit", "junit.jar")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "tools", "junit", "hamcrest-core.jar")))
        SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = selenium_server_link
        SeleniumExecutor.JUNIT_DOWNLOAD_LINK = junit_link
        SeleniumExecutor.HAMCREST_DOWNLOAD_LINK = hamcrest_link
        SeleniumExecutor.JUNIT_MIRRORS_SOURCE = junit_mirrors

    def test_prepare_java_single(self):
        """
        Check if script exists in working dir
        :return:
        """
        self.obj.execution.merge({
            "scenario": {"script": __dir__() + "/../selenium/junit/java/TestBlazemeterFail.java"}
        })
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        self.assertFalse(os.path.exists(os.path.join(self.obj.runner.working_dir, "TestBlazemeterFail.java")))
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "TestBlazemeterFail.class")))
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "compiled.jar")))

    def test_prepare_java_folder(self):
        """
        Check if scripts exist in working dir
        :return:
        """
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/junit/java/"}})
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        prepared_files = os.listdir(self.obj.runner.working_dir)
        java_files = [fname for fname in prepared_files if fname.endswith(".java")]
        class_files = [fname for fname in prepared_files if fname.endswith(".class")]
        jars = [fname for fname in prepared_files if fname.endswith(".jar")]
        self.assertEqual(len(java_files), 0)
        self.assertEqual(len(class_files), 2)
        self.assertEqual(len(jars), 1)

    def test_prepare_java_package(self):
        """
        Check if scripts exist in working dir
        :return:
        """
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/junit/java_package/"}})
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "compiled.jar")))

    def test_selenium_startup_shutdown_java_package(self):
        """
        Run tests from package
        :return:
        """
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/java_package/src'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "compiled.jar")))

    def test_prepare_jar_single(self):
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/junit/jar/dummy.jar"}})
        self.obj.prepare()

    def test_prepare_jar_folder(self):
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/junit/jar/"}})
        self.obj.prepare()

    def test_selenium_startup_shutdown_jar_single(self):
        """
        runt tests from single jar
        :return:
        """
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/jar/'},
                'runner': 'junit',
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JUnitTester)
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        prepared_files = os.listdir(self.obj.runner.working_dir)
        java_files = [fname for fname in prepared_files if fname.endswith(".java")]
        class_files = [fname for fname in prepared_files if fname.endswith(".class")]
        jars = [fname for fname in prepared_files if fname.endswith(".jar")]
        self.assertEqual(len(java_files), 0)
        self.assertEqual(len(class_files), 0)
        self.assertEqual(len(jars), 0)
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def test_selenium_startup_shutdown_jar_folder(self):
        """
        run tests from jars
        :return:
        """
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/jar/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        prepared_files = os.listdir(self.obj.runner.working_dir)
        java_files = [fname for fname in prepared_files if fname.endswith(".java")]
        class_files = [fname for fname in prepared_files if fname.endswith(".class")]
        jars = [fname for fname in prepared_files if fname.endswith(".jar")]
        self.assertEqual(len(java_files), 0)
        self.assertEqual(len(class_files), 0)
        self.assertEqual(len(jars), 0)
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def test_selenium_startup_shutdown_java_single(self):
        """
        run tests from single .java file
        :return:
        """
        self.obj.engine.config.merge({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/java/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.execution.merge({
            "scenario": {"script": __dir__() + "/../selenium/junit/java/TestBlazemeterFail.java"}
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        prepared_files = os.listdir(self.obj.runner.working_dir)
        java_files = [fname for fname in prepared_files if fname.endswith(".java")]
        class_files = [fname for fname in prepared_files if fname.endswith(".class")]
        jars = [fname for fname in prepared_files if fname.endswith(".jar")]
        self.assertEqual(0, len(java_files))
        self.assertEqual(1, len(class_files))
        self.assertEqual(1, len(jars))
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "compiled.jar")))
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def test_selenium_startup_shutdown_java_folder(self):
        """
        run tests from .java files
        :return:
        """
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/java/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })

        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        prepared_files = os.listdir(self.obj.runner.working_dir)
        java_files = [fname for fname in prepared_files if fname.endswith(".java")]
        class_files = [fname for fname in prepared_files if fname.endswith(".class")]
        jars = [fname for fname in prepared_files if fname.endswith(".jar")]
        self.assertEqual(0, len(java_files))
        self.assertEqual(2, len(class_files))
        self.assertEqual(1, len(jars))
        self.assertTrue(os.path.exists(os.path.join(self.obj.runner.working_dir, "compiled.jar")))
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def test_not_junit(self):
        """
        Check that JUnit runner fails if no tests were found
        :return:
        """
        self.configure({
            ScenarioExecutor.EXEC: {
                "executor": "selenium",
                "scenario": {"script": __dir__() + "/../selenium/invalid/NotJUnittest.java"}}})
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JUnitTester)
        self.obj.startup()
        try:
            while not self.obj.check():
                time.sleep(1)
            self.fail()
        except BaseException as exc:
            self.assertIn("Nothing to test", exc.args[0])
        self.obj.shutdown()

    def test_resource_files_collection_remote_java(self):
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/java/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.assertEqual(len(self.obj.resource_files()), 1)

    def test_additional_classpath(self):
        scenario_cp = 'class_path_from_scenario'
        settings_cp = 'class_path_from_settings'
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/junit/java/',
                    'additional-classpath': [scenario_cp]},
                'executor': 'selenium', },
            'modules': {
                'selenium': {
                    'additional-classpath': [settings_cp]}}})
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, JavaTestRunner)
        self.assertTrue(any(scenario_cp in element for element in self.obj.runner.base_class_path))
        self.assertTrue(any(settings_cp in element for element in self.obj.runner.base_class_path))

    def test_resource_files_collection_remote_jar(self):
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/junit/jar/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.assertEqual(len(self.obj.resource_files()), 1)

class TestSeleniumTestNGRunner(SeleniumTestCase):
    def test_install_tools(self):
        dummy_installation_path = __dir__() + "/../../build/tmp/selenium-taurus"
        base_link = "file:///" + __dir__() + "/../data/"

        shutil.rmtree(os.path.dirname(dummy_installation_path), ignore_errors=True)

        selenium_server_link = SeleniumExecutor.SELENIUM_DOWNLOAD_LINK
        SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = base_link + "/selenium-server-standalone-2.46.0.jar"

        testng_link = SeleniumExecutor.TESTNG_DOWNLOAD_LINK
        SeleniumExecutor.TESTNG_DOWNLOAD_LINK = base_link + "/testng-6.8.5.jar"

        hamcrest_link = SeleniumExecutor.HAMCREST_DOWNLOAD_LINK
        SeleniumExecutor.HAMCREST_DOWNLOAD_LINK = base_link + "/hamcrest-core-1.3.jar"

        self.assertFalse(os.path.exists(dummy_installation_path))

        self.obj.settings.merge({"selenium-tools": {
            "testng": {
                "selenium-server": os.path.join(dummy_installation_path, "selenium-server.jar"),
                "hamcrest-core": os.path.join(dummy_installation_path, "tools", "testng", "hamcrest-core.jar"),
                "path": os.path.join(dummy_installation_path, "tools", "testng", "testng.jar")
            }
        }})

        self.obj.execution.merge({
            "runner": "testng",
            "scenario": {
                "script": __dir__() + "/../selenium/testng/jars/testng-suite.jar",
                'testng-xml': None,
            },
        })
        self.obj.prepare()
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "selenium-server.jar")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "tools", "testng", "testng.jar")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "tools", "testng", "hamcrest-core.jar")))
        SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = selenium_server_link
        SeleniumExecutor.TESTNG_DOWNLOAD_LINK = testng_link
        SeleniumExecutor.HAMCREST_DOWNLOAD_LINK = hamcrest_link

    def test_prepare_java_package(self):
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                    'testng-xml': None,
                },
                'runner': 'testng',
            },
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1.0)
        self.obj.shutdown()
        self.obj.post_process()
        lines = open(self.obj.report_file).readlines()
        self.assertEqual(len(lines), 3)

    def test_prepare_java_file(self):
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/TestNGSuite.java',
                    'testng-xml': None
                },
                'runner': 'testng',
            },
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1.0)
        self.obj.shutdown()
        self.obj.post_process()
        lines = open(self.obj.report_file).readlines()
        self.assertEqual(len(lines), 3)

    def test_resource_files(self):
        script_jar = __dir__() + '/../selenium/testng/jars/testng-suite.jar'
        self.configure({
            'execution': {
                'scenario': {
                    'script': script_jar,
                    'testng-xml': 'testng.xml',
                },
                'runner': 'testng',
            },
        })
        resources = self.obj.get_resource_files()
        self.assertEqual(resources, [script_jar, 'testng.xml'])

    def test_resource_files_detect_config(self):
        script_jar = __dir__() + '/../selenium/testng/jars/testng-suite.jar'
        self.configure({
            'execution': {
                'scenario': {
                    'script': script_jar,
                },
                'runner': 'testng',
            },
        })
        resources = self.obj.get_resource_files()
        self.assertEqual(resources, [script_jar,
                                     get_full_path(__dir__() + '/../selenium/testng/jars/testng.xml')])

    def test_hold(self):
        self.configure({
            'execution': {
                'hold-for': '5s',
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                    'testng-xml': None,
                },
                'runner': 'testng',
            },
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        duration = time.time() - self.obj.start_time
        self.assertGreater(duration, 5)

    def test_iterations(self):
        self.configure({
            'execution': {
                'iterations': 3,
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                    'testng-xml': None,
                },
                'runner': 'testng',
            },
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 9)

    def test_with_testng_config(self):
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                    'testng-xml': __dir__() + '/../selenium/testng/jars/testng.xml',
                },
            },
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 6)

    def test_testng_config_autodetect(self):
        testng_xml_path = get_full_path(__dir__() + '/../selenium/testng/jars/testng.xml')
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                },
            },
        })
        self.obj.prepare()
        self.assertEqual(testng_xml_path, self.obj.runner.settings.get("testng-xml", None))
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 6)

    def test_autodetect_script_type(self):
        self.configure({
            'execution': {
                'scenario': {
                    'script': __dir__() + '/../selenium/testng/jars/testng-suite.jar',
                },
            },
        })
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, TestNGTester)

    def test_detect_testng_xml_with_config(self):
        test_yml = __dir__() + "/../selenium/testng/test.yml"
        testng_xml = get_full_path(__dir__() + "/../selenium/testng/testng.xml")
        self.obj.engine.config.merge(yaml.load(open(test_yml)))
        self.obj.execution = self.obj.engine.config.get('execution')
        self.obj.engine.file_search_paths.append(os.path.dirname(test_yml))
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, TestNGTester)
        self.assertEqual(self.obj.runner.settings["testng-xml"], testng_xml)

class TestSeleniumNoseRunner(SeleniumTestCase):
    def test_selenium_prepare_python_single(self):
        """
        Check if script exists in working dir
        :return:
        """
        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/python/test_blazemeter_fail.py"
        }})
        self.obj.prepare()

    def test_selenium_prepare_python_folder(self):
        """
        Check if scripts exist in working dir
        :return:
        """
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/python/"}})
        self.obj.prepare()

    def test_selenium_startup_shutdown_python_single(self):
        """
        run tests from .py file
        :return:
        """

        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/python/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/python/test_blazemeter_fail.py"
        }})
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def test_selenium_startup_shutdown_python_folder(self):
        """
        run tests from .py files
        :return:
        """
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/python/'},
                'executor': 'selenium'
            },
            'reporting': [{'module': 'junit-xml'}]
        })
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))

    def runner_fail_no_test_found(self):
        """
        Check that Python Nose runner fails if no tests were found
        :return:
        """
        self.configure({
            ScenarioExecutor.EXEC: {
                "executor": "selenium",
                "scenario": {"script": __dir__() + "/../selenium/invalid/dummy.py"}
            }
        })
        self.obj.prepare()
        self.obj.startup()
        try:
            while not self.obj.check():
                time.sleep(1)
            self.fail()
        except ToolError as exc:
            self.assertIn("Nothing to test.", exc.args[0])
        self.obj.shutdown()

    def test_resource_files_collection_remote_nose(self):
        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/python/"}})
        self.assertEqual(len(self.obj.resource_files()), 1)

    def test_setup_exception(self):
        """
        Do not crash when test's setUp/setUpClass fails
        :return:
        """
        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/python/test_setup_exception.py"
        }})
        self.obj.prepare()
        self.obj.startup()
        while True:
            try:
                finished = self.obj.check()
                if finished:
                    self.fail("Should've failed with 'nothing to test'")
            except ToolError as exc:
                self.assertIn("Catch that", str(exc))
                self.assertIn("Nothing to test", str(exc))
                break

    def test_long_iterations_value(self):
        self.obj.execution.merge({
            "iterations": 2 ** 64,
            "scenario": {
                "requests": [
                    "http://blazedemo.com/",
                ],
            }
        })
        self.obj.prepare()
        try:
            self.obj.startup()
            for _ in range(3):
                self.assertFalse(self.obj.check())
                time.sleep(1.0)
        finally:
            self.obj.shutdown()

class TestSeleniumRSpecRunner(SeleniumTestCase):
    def test_selenium_prepare_rspec(self):
        self.configure({
            "execution": {
                "scenario": {
                    "script": __dir__() + "/../selenium/ruby/example_spec.rb"
                }}})
        self.obj.prepare()

    def test_rspec_full(self):
        self.configure({
            'execution': {
                'scenario': {'script': __dir__() + '/../selenium/ruby/example_spec.rb'},
            },
        })
        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 3)
        first, second, third = lines
        self.assertEqual(json.loads(first)["status"], "PASSED")
        self.assertEqual(json.loads(second)["status"], "FAILED")
        self.assertEqual(json.loads(third)["status"], "FAILED")

    def test_rspec_hold(self):
        self.configure({
            'execution': {
                'hold-for': '10s',
                'scenario': {'script': __dir__() + '/../selenium/ruby/example_spec.rb'},
                'executor': 'selenium'
            },
        })
        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        duration = time.time() - self.obj.start_time
        self.assertGreater(duration, 10)

    def test_rspec_iterations(self):
        self.configure({
            'execution': {
                'iterations': 3,
                'scenario': {'script': __dir__() + '/../selenium/ruby/example_spec.rb'},
                'executor': 'selenium'
            },
        })
        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 9)

    def test_interpreter(self):
        self.configure({
            'execution': {
                'iterations': 3,
                'scenario': {'script': __dir__() + '/../selenium/ruby/example_spec.rb'},
                'executor': 'selenium'
            },
        })
        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        dummy = __dir__() + '/../selenium/ruby/ruby-dummy'
        dummy += '.bat' if is_windows() else ''
        self.obj.settings.merge({
            "selenium-tools": {"rspec": {"interpreter": dummy}}
        })
        self.obj.prepare()

class TestSeleniumMochaRunner(SeleniumTestCase):
    def test_selenium_prepare_mocha(self):
        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/js-mocha/bd_scenarios.js"
        }})
        self.obj.prepare()

    def test_mocha_full(self):
        self.obj.engine.config.merge({
            'execution': {
                "script": __dir__() + "/../selenium/js-mocha/bd_scenarios.js"
            },
        })
        self.obj.engine.config.merge({"provisioning": "local"})
        self.obj.execution = self.obj.engine.config['execution']

        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/js-mocha/bd_scenarios.js"
        }})

        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 3)

    def test_mocha_hold(self):
        self.obj.engine.config.merge({
            'execution': {
                'hold-for': '5s',
                'scenario': {'script': __dir__() + '/../selenium/js-mocha/'},
                'executor': 'selenium'
            },
        })
        self.obj.engine.config.merge({"provisioning": "local"})
        self.obj.execution = self.obj.engine.config['execution']

        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/js-mocha/"
        }})

        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        duration = time.time() - self.obj.start_time
        self.assertGreater(duration, 5)

    def test_mocha_iterations(self):
        self.obj.engine.config.merge({
            'execution': {
                'iterations': 3,
                'scenario': {'script': __dir__() + '/../selenium/js-mocha'},
                'executor': 'selenium'
            },
        })
        self.obj.engine.config.merge({"provisioning": "local"})
        self.obj.execution = self.obj.engine.config['execution']

        self.obj.execution.merge({"scenario": {
            "script": __dir__() + "/../selenium/js-mocha"
        }})

        self.obj.settings.merge(self.obj.engine.config.get("modules").get("selenium"))
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        self.assertTrue(os.path.exists(self.obj.runner.settings.get("report-file")))
        lines = open(self.obj.runner.settings.get("report-file")).readlines()
        self.assertEqual(len(lines), 9)

    def test_install_mocha(self):
        dummy_installation_path = get_full_path(__dir__() + "/../../build/tmp/selenium-taurus/mocha")
        mocha_link = get_full_path(__dir__() + "/../data/mocha-3.1.0.tgz")
        wd_link = get_full_path(__dir__() + "/../data/selenium-webdriver-1.0.0.tgz")

        shutil.rmtree(os.path.dirname(dummy_installation_path), ignore_errors=True)
        self.assertFalse(os.path.exists(dummy_installation_path))

        old_node_path = os.environ.get("NODE_PATH")
        if old_node_path:
            os.environ.pop("NODE_PATH")

        orig_mocha_package = SeleniumExecutor.MOCHA_NPM_PACKAGE_NAME
        orig_wd_package = SeleniumExecutor.SELENIUM_WEBDRIVER_NPM_PACKAGE_NAME
        SeleniumExecutor.MOCHA_NPM_PACKAGE_NAME = mocha_link
        SeleniumExecutor.SELENIUM_WEBDRIVER_NPM_PACKAGE_NAME = wd_link

        self.obj.settings.merge({"selenium-tools": {
            "mocha": {"tools-dir": dummy_installation_path}
        }})

        self.obj.execution.merge({"scenario": {"script": __dir__() + "/../selenium/js-mocha/bd_scenarios.js"}})
        self.obj.prepare()
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "node_modules")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "node_modules", "mocha")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "node_modules", "mocha", "index.js")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "node_modules", "selenium-webdriver")))
        self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "node_modules", "selenium-webdriver",
                                                    "index.js")))

        SeleniumExecutor.MOCHA_NPM_PACKAGE_NAME = orig_mocha_package
        SeleniumExecutor.SELENIUM_WEBDRIVER_NPM_PACKAGE_NAME = orig_wd_package
        if old_node_path:
            os.environ["NODE_PATH"] = old_node_path

class LDJSONReaderEmul(object):
    def __init__(self):
        self.data = []

    def read(self, last_pass=False):
        for line in self.data:
            yield line

class TestSeleniumStuff(SeleniumTestCase):
    def test_empty_scenario(self):
        """
        Raise runtime error when no scenario provided
        :return:
        """
        self.configure({ScenarioExecutor.EXEC: {"executor": "selenium"}})
        self.assertRaises(TaurusConfigError, self.obj.prepare)

    def test_javac_fail(self):
        """
        Test RuntimeError when compilation fails
        :return:
        """
        self.configure({
            ScenarioExecutor.EXEC: {
                "executor": "selenium",
                "scenario": {"script": __dir__() + "/../selenium/invalid/invalid.java"}
            }
        })
        self.assertRaises(ToolError, self.obj.prepare)

    def test_no_supported_files_to_test(self):
        """
        Test RuntimeError raised when no files of known types were found.
        :return:
        """
        self.configure({ScenarioExecutor.EXEC: {
            "executor": "selenium",
            "scenario": {"script": __dir__() + "/../selenium/invalid/not_found"}
        }})
        self.assertRaises(TaurusConfigError, self.obj.prepare)

    def test_samples_count_annotations(self):
        """
        Test exact number of tests when java annotations used
        :return:
        """
        self.configure({ScenarioExecutor.EXEC: {
            "executor": "selenium",
            "scenario": {"script": __dir__() + "/../selenium/invalid/SeleniumTest.java"}
        }})
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

    def test_samples_count_testcase(self):
        """
        Test exact number of tests when test class extends JUnit TestCase
        :return:
        """
        self.configure({ScenarioExecutor.EXEC: {
            "executor": "selenium",
            "scenario": {"script": __dir__() + "/../selenium/invalid/SimpleTest.java"}
        }})
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

    def test_no_test_in_name(self):
        """
        Test exact number of tests when annotations used and no "test" in class name
        :return:
        """
        self.configure({ScenarioExecutor.EXEC: {
            "executor": "selenium",
            "scenario": {"script": __dir__() + "/../selenium/invalid/selenium1.java"}
        }})
        self.obj.prepare()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()

    def test_requests(self):
        self.configure(yaml.load(open(__dir__() + "/../yaml/selenium_executor_requests.yml").read()))
        self.obj.prepare()
        self.obj.get_widget()
        self.obj.startup()
        while not self.obj.check():
            time.sleep(1)
        self.obj.shutdown()
        with open(os.path.join(self.obj.engine.artifacts_dir, "selenium.err")) as fds:
            contents = fds.read()
            msg = "file: '%s', size: %s, content: '%s'" % (fds, fds.__sizeof__(), contents)
            self.assertEqual(3, contents.count("ok"), msg)
            self.assertEqual(1, contents.count("OK"))

    def test_fail_on_zero_results(self):
        self.configure(yaml.load(open(__dir__() + "/../yaml/selenium_executor_requests.yml").read()))
        self.obj.prepare()
        self.obj.engine.prepared = [self.obj]
        self.obj.engine.started = [self.obj]
        prov = Local()
        prov.engine = self.obj.engine
        prov.executors = [self.obj]
        self.obj.engine.provisioning = prov
        self.assertRaises(ToolError, self.obj.engine.provisioning.post_process)

    def test_junit_mirrors(self):
        dummy_installation_path = __dir__() + "/../../build/tmp/selenium-taurus"
        shutil.rmtree(os.path.dirname(dummy_installation_path), ignore_errors=True)
        obj = SeleniumExecutor()
        junit_path = os.path.join(dummy_installation_path, "tools", "junit", "junit.jar")
        objjm = JUnitJar(junit_path, obj.log, SeleniumExecutor.JUNIT_VERSION)
        objjm.install()

    def test_remote_prov_requests(self):
        self.obj.execution.merge({
            "scenario": {
                "requests": [
                    "http://blazedemo.com"
                ]
            }
        })
        resources = self.obj.resource_files()
        self.assertEqual(0, len(resources))

    def test_labels_translation(self):
        self.configure({
            "scenarios": {
                "req_sel": {
                    "requests": [
                        "http://blazedemo.com",
                        {
                            'url': 'http://blazemeter.com',
                            'label': 'Main Page'
                        }]}}})
        self.obj.execution.merge({
            "scenario": "req_sel"})
        self.obj.prepare()
        gen_methods = self.obj.generated_methods
        name1 = 'test_00000_http_blazedemo_com'
        url1 = 'http://blazedemo.com'
        name2 = 'test_00001_Main_Page'
        label2 = 'Main Page'
        name3 = 'test_00002_just_for_lulz'
        label3 = 'just_for_lulz'
        self.assertEqual(url1, gen_methods[name1])
        self.assertEqual(label2, gen_methods[name2])
        self.obj.reader.report_reader.json_reader = LDJSONReaderEmul()
        self.obj.reader.report_reader.json_reader.data.extend([
            {
                'test_case': name1, 'start_time': 1472049887, 'duration': 1.0, 'status': 'PASSED',
                'test_suite': 'Tests', 'error_msg': None, 'error_trace': None, 'extras': None,
            }, {
                'test_case': name2, 'start_time': 1472049888, 'duration': 1.0, 'status': 'PASSED',
                'test_suite': 'Tests', 'error_msg': None, 'error_trace': None, 'extras': None,
            }, {
                'test_case': name3, 'start_time': 1472049889, 'duration': 1.0, 'status': 'PASSED',
                'test_suite': 'Tests', 'error_msg': None, 'error_trace': None, 'extras': None,
            }])
        res = list(self.obj.reader._read())
        self.assertIn(url1, res[0])
        self.assertIn(label2, res[1])
        self.assertIn(label3, res[2])

    def test_dont_copy_local_script_to_artifacts(self):
        "ensures that .java file is not copied into artifacts-dir"
        filename = "BlazeDemo.java"
        script_path = __dir__() + "/../data/" + filename
        self.obj.execution.merge({
            "scenario": {
                "script": script_path,
            }
        })
        self.obj.prepare()
        files = self.obj.resource_files()
        self.assertIn(script_path, files)
        artifacts_script = os.path.join(self.obj.engine.artifacts_dir, filename)
        self.assertFalse(os.path.exists(artifacts_script))

    def test_take_script_from_artifacts(self):
        "ensures that executor looks for script in artifacts-dir (for cloud/remote cases)"
        self.obj.engine.file_search_paths = [self.obj.engine.artifacts_dir]

        script_name = "BlazeDemo.java"
        test_script = __dir__() + "/../data/" + script_name
        artifacts_script = os.path.join(self.obj.engine.artifacts_dir, script_name)
        shutil.copy2(test_script, artifacts_script)

        self.obj.execution.merge({
            "scenario": {
                "script": script_name,
            }
        })
        self.obj.prepare()

    def test_do_not_modify_scenario_script(self):
        self.obj.execution.merge({
            "scenario": {
                "requests": ["address"],
            }
        })
        self.obj.prepare()
        self.assertNotIn("script", self.obj.get_scenario())

    def test_default_address_gen(self):
        self.obj.execution.merge({
            "scenario": {
                "default-address": "http://blazedemo.com",
                "requests": ["/", "http://absolute.address.com/somepage", "/reserve.php"],
            }
        })
        self.obj.prepare()
        with open(os.path.join(self.obj.engine.artifacts_dir, os.path.basename(self.obj.script))) as fds:
            script = fds.read()
        urls = re.findall(r"get\('(.+)'\)", script)
        self.assertEqual("http://blazedemo.com/", urls[0])
        self.assertEqual("http://absolute.address.com/somepage", urls[1])
        self.assertEqual("http://blazedemo.com/reserve.php", urls[2])

    def test_force_runner(self):
        self.obj.execution.merge({
            'scenario': {'script': __dir__() + '/../selenium/junit/jar/'},
            'runner': 'nose',
        })
        self.obj.prepare()
        self.assertIsInstance(self.obj.runner, NoseTester)

    def test_additional_classpath_resource_files(self):
        self.obj.execution.merge({
            'scenario': {
                'script': __dir__() + '/../selenium/junit/jar/dummy.jar',
                'runner': 'junit',
                'additional-classpath': [__dir__() + '/../selenium/junit/jar/another_dummy.jar'],
            },
        })
        self.obj.settings.merge({
            'additional-classpath': [__dir__() + '/../selenium/testng/jars/testng-suite.jar'],
        })
        resources = self.obj.resource_files()
        # scenario.script, scenario.additional-classpath, settings.additional-classpath
        self.assertEqual(len(resources), 3)

    def test_required_tools(self):
        self.obj.install_required_tools()

class TestSeleniumScriptBuilder(SeleniumTestCase):
    def test_build_script(self):
        self.configure({
            "execution": [{
                "executor": "selenium",
                "hold-for": "4m",
                "ramp-up": "3m",
                "scenario": "loc_sc"}],
            "scenarios": {
                "loc_sc": {
                    "default-address": "http://blazedemo.com",
                    "timeout": "3.5s",
                    "requests": [{
                        "url": "/",
                        "assert": [{
                            "contains": ['contained_text'],
                            "not": True
                        }],
                        "actions": [
                            {"waitByName('toPort')": "visible"},
                            {"keysByName(\"toPort\")": "B"},
                            "clickByXPath(//div[3]/form/select[1]//option[3])",
                            "clickByXPath(//div[3]/form/select[2]//option[6])",
                            "clickByXPath(//input[@type='submit'])",
                            "clickByLinkText(destination of the week! The Beach!)"
                        ],

                    }, {
                        "label": "empty"
                    }]
                }
            },
            "modules": {
                "selenium": {
                    "^virtual-display": 0}}})
        self.obj.prepare()
        with open(self.obj.script) as generated:
            gen_contents = generated.readlines()
        with open(__dir__() + "/../selenium/generated_from_requests.py") as sample:
            sample_contents = sample.readlines()

        # strip line terminator and exclude specific build path
        gen_contents = [line.rstrip() for line in gen_contents if 'webdriver' not in line]
        sample_contents = [line.rstrip() for line in sample_contents if 'webdriver' not in line]

        self.assertEqual(gen_contents, sample_contents)

class TestReportReader(BZTestCase):
    def test_report_reader(self):
        reader = LoadSamplesReader(__dir__() + "/../selenium/report.ldjson", logging.getLogger(), None)
        items = list(reader._read())
        self.assertEqual(4, len(items))
        self.assertEqual(items[0][1], 'testFailure')
        self.assertEqual(items[0][6], '400')
        self.assertEqual(items[1][1], 'testBroken')
        self.assertEqual(items[1][6], '500')
        self.assertEqual(items[2][1], 'testSuccess')
        self.assertEqual(items[2][6], '200')
        self.assertEqual(items[3][1], 'testUnexp')
        self.assertEqual(items[3][6], 'UNKNOWN')

    def test_reader_buffering(self):
        first_part = '{"a": 1, "b": 2}\n{"a": 2,'
        second_part = '"b": 3}\n{"a": 3, "b": 4}\n'
        reader = LDJSONReader("yip", logging.getLogger())
        buffer = StringIO(first_part)
        reader.fds = buffer

        items = list(reader.read(last_pass=False))
        self.assertEqual(len(items), 1)

        buffer.write(second_part)
        items = list(reader.read(last_pass=False))
        self.assertEqual(len(items), 2)

    def test_func_reader(self):
        reader = FuncSamplesReader(__dir__() + "/../selenium/report.ldjson", logging.getLogger(), None)
        items = list(reader.read())
        self.assertEqual(4, len(items))
        self.assertEqual(items[0].test_case, 'testFailure')
        self.assertEqual(items[0].status, "FAILED")
        self.assertEqual(items[1].test_case, 'testBroken')
        self.assertEqual(items[1].status, "BROKEN")
        self.assertEqual(items[2].test_case, 'testSuccess')
        self.assertEqual(items[2].status, "PASSED")


text:
/* A webpack config file which builds the chrome extension */

const CopyPlugin = require('copy-webpack-plugin');
const ExtensionReloader = require('webpack-extension-reloader');
const srcDir = './chrome/src/';
const path = require('path');
const webpack = require('webpack');

module.exports = {
  // Entry files are the TypeScript files that are the extension.
  entry: {
    background: path.join(__dirname, srcDir + 'background.ts'),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  devtool: 'inline-source-map',
  optimization: {
    splitChunks: {
      name: 'vendor',
      chunks: 'initial',
    },
  },
  resolve: {
    // Add `.ts` as a resolvable extension.
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      {test: /\.tsx?$/, loader: 'ts-loader', exclude: '/node_modules/'},
    ],
  },
  plugins: [
    // Copies the base manifest JSON to the /dist folder.
    // Adds the extension's key to the manifest from ENV variables.
    new CopyPlugin({
      patterns: [
        {
          from: 'chrome/manifest.json',
          to: './',
          transform: function (content, path) {
            // generates the manifest file using the package.json informations
            return Buffer.from(
              JSON.stringify({
                key: process.env.EXTENSION_DEV_KEY2,
                ...JSON.parse(content.toString()),
              })
            );
          },
        },
      ],
    }),

    // Initializes the automatic reloading of the chrome extension during development.
    new ExtensionReloader({
      entries: {
        background: 'background',
      },
    }),
  ]
};

redpajama_set_name: RedPajamaGithub


text:
/* global $, interfaceConfig, APP */
var animateTimeout, updateTimeout;

var RoomnameGenerator = require("../../util/RoomnameGenerator");
import UIUtil from "../util/UIUtil";

function enter_room() {
    var val = $("#enter_room_field").val();
    if(!val) {
        val = $("#enter_room_field").attr("room_name");
    }
    if (val) {
        window.location.pathname = "/" + val;
    }
}

function animate(word) {
    var currentVal = $("#enter_room_field").attr("placeholder");
    $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
    animateTimeout = setTimeout(function() {
        animate(word.substring(1, word.length));
    }, 70);
}

function update_roomname() {
    var word = RoomnameGenerator.generateRoomWithoutSeparator();
    $("#enter_room_field").attr("room_name", word);
    $("#enter_room_field").attr("placeholder", "");
    clearTimeout(animateTimeout);
    animate(word);
    updateTimeout = setTimeout(update_roomname, 10000);
}

function setupWelcomePage() {
    $("#videoconference_page").hide();
    $("#domain_name").text(
            window.location.protocol + "//" + window.location.host + "/");
    if (interfaceConfig.SHOW_JITSI_WATERMARK) {
        var leftWatermarkDiv =
            $("#welcome_page_header div[class='watermark leftwatermark']");
        if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
            leftWatermarkDiv.css({display: 'block'});
            UIUtil.setLinkHref(
                leftWatermarkDiv.parent(),
                interfaceConfig.JITSI_WATERMARK_LINK);
        }
    }

    if (interfaceConfig.SHOW_BRAND_WATERMARK) {
        var rightWatermarkDiv =
            $("#welcome_page_header div[class='watermark rightwatermark']");
        if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
            rightWatermarkDiv.css({display: 'block'});
            UIUtil.setLinkHref(
                rightWatermarkDiv.parent(),
                interfaceConfig.BRAND_WATERMARK_LINK);
            rightWatermarkDiv.get(0).style.backgroundImage =
                "url(images/rightwatermark.png)";
        }
    }

    if (interfaceConfig.SHOW_POWERED_BY) {
        $("#welcome_page_header>a[class='poweredby']")
            .css({display: 'block'});
    }

    $("#enter_room_button").click(function() {
        enter_room();
    });

    $("#enter_room_field").keydown(function (event) {
        if (event.keyCode === 13 /* enter */) {
            enter_room();
        }
    });

    if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
        var selector = $("#reload_roomname");
        selector.click(function () {
            clearTimeout(updateTimeout);
            clearTimeout(animateTimeout);
            update_roomname();
        });
        selector.show();

        update_roomname();
    }

    $("#disable_welcome").click(function () {
        APP.settings.setWelcomePageEnabled(
            !$("#disable_welcome").is(":checked")
        );
    });

}

module.exports = setupWelcomePage;


text:
/*
 * Advent of Code 2016
 * Day 6 (part 2)
 *
 * Command: clang++ --std=c++14 day06b.cpp
 *
 */

#include <climits>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

const string INPUT_FILE = "input06.txt";
const int MAX_LINE_LENGTH = 2000;

int main(void) {
	// Open the input file
	ifstream fin(INPUT_FILE);
	if (!fin) {
		cerr << "Error reading input file " << INPUT_FILE << endl;
		return -1;
	}

	// Read the input
	vector<string> input;
	char cInput[MAX_LINE_LENGTH];
	while (fin.getline(cInput, MAX_LINE_LENGTH)) {
		input.push_back(string(cInput));
	}
	fin.close();

	// Solve the problem
	auto length = input.at(0).length();
	vector<unordered_map<char, int>> counts;

	for (int i = 0; i < length; i++) {
		unordered_map<char, int> columnCounts;

		for (auto row : input) {
			char ch = row.at(i);
			auto location = columnCounts.find(ch);

			if (location == columnCounts.end()) {
				columnCounts.emplace(ch, 1);
			} else {
				int count = location->second;
				count++;

				columnCounts.erase(ch);
				columnCounts.emplace(ch, count);
			}
		}

		counts.push_back(columnCounts);
	}

	string message;
	for (auto column : counts) {
		auto min = numeric_limits<int>::max();
		auto ch = '\0';

		for (auto &pair : column) {
			if (pair.second < min) {
				min = pair.second;
				ch = pair.first;
			}
		}

		message += ch;
	}

	cout << "Message: \"" << message << "\"" << endl;

	return 0;
}


text:
package org.apache.camel.component.azure.storage.datalake;

import java.util.Map;
import java.util.Set;

import com.azure.identity.ClientSecretCredential;
import com.azure.storage.common.StorageSharedKeyCredential;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component("azure-storage-datalake")
public class DataLakeComponent extends DefaultComponent {

    private static final Logger LOG = LoggerFactory.getLogger(DataLakeComponent.class);

    @Metadata(description = "configuration object for datalake")
    private DataLakeConfiguration configuration = new DataLakeConfiguration();

    public DataLakeComponent() {
    }

    public DataLakeComponent(final CamelContext camelContext) {
        super(camelContext);
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {

        if (remaining == null || remaining.trim().isEmpty()) {
            throw new IllegalArgumentException("At least the account name must be specified");
        }

        final DataLakeConfiguration configuration;
        if (this.configuration != null) {
            configuration = this.configuration.copy();
        } else {
            configuration = new DataLakeConfiguration();
        }

        final String[] details = remaining.split("/");

        configuration.setAccountName(details[0]);

        if (details.length > 1) {
            configuration.setFileSystemName(details[1]);
        }

        final DataLakeEndpoint endpoint = new DataLakeEndpoint(uri, this, configuration);
        setProperties(endpoint, parameters);

        setCredentialsFromRegistry(configuration);
        validateConfiguration(configuration);

        return endpoint;
    }

    public DataLakeConfiguration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(DataLakeConfiguration configuration) {
        this.configuration = configuration;
    }

    private void setCredentialsFromRegistry(final DataLakeConfiguration configuration) {
        if (ObjectHelper.isEmpty(configuration.getServiceClient())) {
            final Set<StorageSharedKeyCredential> storageSharedKeyCredentials
                    = getCamelContext().getRegistry().findByType(StorageSharedKeyCredential.class);
            final Set<ClientSecretCredential> clientSecretCredentials
                    = getCamelContext().getRegistry().findByType(ClientSecretCredential.class);

            if (storageSharedKeyCredentials.size() == 1) {
                configuration.setSharedKeyCredential(storageSharedKeyCredentials.stream().findFirst().get());
            }

            if (clientSecretCredentials.size() == 1) {
                configuration.setClientSecretCredential(clientSecretCredentials.stream().findFirst().get());
            }

        }
    }

    private void validateConfiguration(final DataLakeConfiguration config) {
        if (config.getServiceClient() == null && config.getClientSecretCredential() == null
                && config.getSharedKeyCredential() == null) {
            throw new IllegalArgumentException("client or credentials must be specified");
        }
    }

}


text:
package org.locationtech.geomesa.process

import java.util.ServiceLoader

import org.geotools.process.factory.AnnotatedBeanProcessFactory
import org.geotools.text.Text
import org.locationtech.geomesa.process.GeoMesaProcessFactory.{Name, NameSpace, processes}

class GeoMesaProcessFactory extends AnnotatedBeanProcessFactory(Name, NameSpace, processes: _*)

object GeoMesaProcessFactory {

  val NameSpace = "geomesa"
  val Name = Text.text("GeoMesa Process Factory")

  def processes: Array[Class[_]] = {
    import scala.collection.JavaConversions._
    ServiceLoader.load(classOf[GeoMesaProcess]).iterator().map(_.getClass).toArray
  }
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zenith.Core.Models
{
    public class Catalog
    {
        [JsonProperty("id")]
        public string ID { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("description")]
        public string Description { get; set; }
        [JsonProperty("status")]
        public string Status { get; set; }
        [JsonProperty("is_obsolete")]
        public bool IsObsolete { get; set; }
        [JsonProperty("density")]
        public double Density { get; set; }
        [JsonProperty("popularity")]
        public double Popularity { get; set; }
        [JsonProperty("media")]
        public string Media { get; set; }
        [JsonProperty("target")]
        public string Target { get; set; }
        [JsonProperty("mission")]
        public string Mission { get; set; }
        [JsonProperty("wavelengths")]
        public List<string> Wavelengths { get; set; }
        [JsonProperty("astronomy")]
        public List<string> Astronomy { get; set; }
        [JsonProperty("links")]
        public List<string> Links { get; set; }
    }

    public class KnownCatalog
    {
        [JsonProperty("short_code")]
        public string ShortCode { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("description")]
        public string Description { get; set; }
    }
}


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Erik Liked To Dance</title>
<link rel="stylesheet" href="../css/style.css">
<script type="text/javascript" src="../../dist/paper-full.js"></script>
<script type="text/paperscript" canvas="canvas">
    var leftPath = new Path({
        strokeColor: 'red',
        opacity: 0.5
    });

    var rightPath = new Path({
        strokeColor: 'green',
        opacity: 0.5
    });

    var amount = 8;
    var step = view.size.width / (amount + 1);
    var flip = false;

    for (var i = 0; i <= amount; i++) {
        leftPath.add(new Point(i * step, 0));
        rightPath.add(new Point(i * step, 0));
    }

    var group = new Group({
        children: [leftPath, rightPath],
        applyMatrix: false,
        strokeWidth: 30,
        strokeJoin: 'round',
        strokeCap: 'butt',
        pivot: leftPath.position,
        position: view.center
    });

    function onMouseDown() {
        flip = !flip;
    }

    function onKeyDown(event) {
        if (event.key === 'space')
            group.fullySelected = !group.fullySelected;
    }

    var audio, source, analyserL, analyserR, freqByteData;

    view.onFrame = function() {
        var step = view.size.width / (amount + 1);
        var scale = view.size.height / 1.5;
        analyserL.getByteFrequencyData(freqByteData);
        var leftBands = getEqualizerBands(freqByteData, true);
        analyserR.getByteFrequencyData(freqByteData);
        var rightBands = getEqualizerBands(freqByteData, true);
        for (var i = 1; i <= amount; i++) {
            leftPath.segments[i].point = [i * step, -leftBands[i - 1] * scale];
            rightPath.segments[i].point = [i * step, -rightBands[i - 1] * scale * (flip ? -1 : 1)];
        }
        leftPath.smooth();
        rightPath.smooth();
        group.pivot = [leftPath.position.x, 0];
        group.position = view.center;
    }

    // Pause animation until we have data
    view.pause();

    var AudioContext = window.AudioContext || window.webkitAudioContext;
    if (AudioContext) {
        audio = new AudioContext();
        source = audio.createBufferSource();
        // Create two separate analyzers for left and right channel.
        analyserL = audio.createAnalyser();
        analyserL.smoothingTimeConstant = 0.25;
        analyserL.fftSize = Math.pow(2, amount) * 2;
        analyserR = audio.createAnalyser();
        analyserR.smoothingTimeConstant = analyserL.smoothingTimeConstant;
        analyserR.fftSize = analyserL.fftSize;
        // Create the buffer to receive the analyzed data.
        freqByteData = new Uint8Array(analyserL.frequencyBinCount);
        // Create a splitter to feed them both
        var splitter = audio.createChannelSplitter();
        // Connect audio processing graph
        source.connect(splitter);
        splitter.connect(analyserL, 0, 0);
        splitter.connect(analyserR, 1, 0);
        // Connect source to output also so we can hear it
        source.connect(audio.destination);
        loadAudioBuffer('http://assets.paperjs.org/audio/gnossienne.mp3');
    } else {
        // TODO: Print error message
        alert('Audio not supported');
    }

    function loadAudioBuffer(url) {
        // Load asynchronously
        var request = new XMLHttpRequest();
        request.open("GET", url, true);
        request.responseType = "arraybuffer";

        request.onload = function() {
            audio.decodeAudioData(
                request.response,
                function(buffer) {
                    source.buffer = buffer;
                    source.loop = true;
                    source.start(0);
                    view.play();
                },

                function(buffer) {
                    alert("Error loading MP3");
                }
            );
        };
        request.send();
    }

    function getEqualizerBands(data) {
        var bands = [];
        var amount = Math.sqrt(data.length) / 2;
        for(var i = 0; i < amount; i++) {
            var start = Math.pow(2, i) - 1;
            var end = start * 2 + 1;
            var sum = 0;
            for (var j = start; j < end; j++) {
                sum += data[j];
            }
            var avg = sum / (255 * (end - start));
            bands[i] = Math.sqrt(avg / Math.sqrt(2));
        }
        return bands;
    }
</script>
</head>
<body>
    <canvas id="canvas" resize></canvas>
</body>
</html>


text:
import { messages } from './rapid'

export default (group, onvalue, onerror) => {
  return //messages.filter({ idEmisor: group }).subscribe(onvalue, onerror)
}


text:
import fse from 'fs-extra'
import clc from 'cli-color'
import extend from 'extend'
import path from 'path'

import config from './config.json'

var result = config
result.root = process.cwd()
if (process.env.ROOT) {
  result.root = process.env.ROOT.replace(/\/$/, '')
}

var hintAbeJson = false

var loadLocalConfig = result => {
  if (result.root !== '') {
    try {
      var stat = fse.statSync(result.root)
      if (stat && stat.isDirectory()) {
        try {
          stat = fse.statSync(path.join(result.root, 'abe.json'))
          if (stat) {
            var json = fse.readJsonSync(path.join(result.root, 'abe.json'))
            result = extend(true, result, json)
          }
        } catch (e) {
          if (!hintAbeJson) {
            hintAbeJson = true
            // console.log(
            //   clc.green('[ Hint ]'),
            //   'you can create a specific config file named abe.json to customize your abe install',
            //   clc.cyan.underline('https://github.com/abecms/abecms/blob/master/docs/abe-config.md')
            // )
          }
        }
      }
    } catch (e) {
      console.log('LoadConfig Error')
      console.log(e)
    }
  }
}

loadLocalConfig(result)

result.exist = (conf, json) => {
  var c = conf.split('.')
  var current = json
  if (typeof current !== 'undefined' && current !== null) {
    Array.prototype.forEach.call(c, c => {
      if (
        current !== false &&
        typeof current[c] !== 'undefined' &&
        current[c] !== null
      ) {
        current = current[c]
      } else {
        current = false
        return false
      }
    })
    return current
  } else {
    return false
  }
}

result.localConfigExist = () => {
  if (result.root !== '') {
    try {
      var stat = fse.statSync(result.root)
      if (stat && stat.isDirectory()) {
        try {
          stat = fse.statSync(path.join(result.root, 'abe.json'))
          if (stat) {
            return true
          }
        } catch (e) {
          return false
        }
      }
    } catch (e) {
      return false
    }
  }

  return false
}

result.getLocalConfig = () => {
  if (result.localConfigExist()) {
    return fse.readJsonSync(path.join(result.root, 'abe.json'))
  } else {
    return {}
  }
}

result.getDefault = conf => {
  return result[conf]
}

result.get = conf => {
  return result.exist(conf, result)
}

result.set = json => {
  extend(true, result, json)
  loadLocalConfig(result)
}

result.extend = json => {
  const localConf = result.getLocalConfig()
  extend(true, localConf, json)
  result.save(localConf)
}

result.save = json => {
  const confPath = path.join(result.root, 'abe.json')
  fse.writeJsonSync(confPath, json, {space: 2, encoding: 'utf-8'})
  loadLocalConfig(result)
}

result.getConfigByWebsite = () => {
  var defaultConfig = extend(true, {}, result)
  var configBySite = {
    default: {}
  }

  var localConfig = extend(true, {}, defaultConfig)
  for (var item in localConfig) {
    switch (item) {
      case 'intlData':
        configBySite.default.intlData = localConfig[item]
        break
      case 'templates':
        configBySite.default.templates = localConfig[item]
        break
      case 'structure':
        configBySite.default.structure = localConfig[item]
        break
      case 'data':
        configBySite.default.data = localConfig[item]
        break
      case 'publish':
        configBySite.default.publish = localConfig[item]
        break
      case 'files':
        configBySite.default.files = {
          templates: {
            extension: localConfig[item].templates.extension
          }
        }
        break
      case 'upload':
        configBySite.default.upload = localConfig[item]
        break
    }
  }

  return configBySite
}

export default result


text:
Running
---

We provide a Python script, i.e. [launch][3], that simplifies running Mimiker OS.
The kernel image is run with QEMU or Renode simulator. One or more serial
consoles are available for interaction. Optionally you can attach to simulator
with `gdb` debugger.  All of that is achieved by running all interactive
sessions within [tmux][1] terminal multiplexer with default key bindings.

To start kernel in test-run mode, run the following command in project's root
directory. To finish simulation simply detach from `tmux` session by
pressing `Ctrl+b` and `d` (as in _detach_) keys. To switch between emulated
serial consoles and debugger press `Ctrl+b` and corresponding terminal number.

```
./launch test=all
```

Some useful flags to the `launch` script:

* `-h` - Prints usage.
* `-d` - Starts simulation under a debugger.
* `-b` - To specify emulated board (if different than Raspberry Pi 3).
* `-g` - Opens a window with graphics display, if the platform supports it.

Any other argument is passed to the kernel as a kernel command-line
argument. Some useful kernel arguments:

* `init=PROGRAM` - Specifies the userspace program for PID 1.
  Browse `bin` and `usr.bin` directories for currently available programs.
  In most cases you want to run `/bin/ksh` shell.
* `klog-mask` - Specifies for which [subsystem][4] debug messages will be logged
  to kernel logging facilities. `KL_DEFAULT_MASK` is used by default.
* `klog-utest-mask` - As above but applies to execution of userspace tests.
  `KL_UTEST_MASK` is used by default.

Please note that `launch` script is highly configurable by means of changing
`CONFIG` dictionary.

If you want to run tests please read [this document][2].

[1]: https://github.com/tmux/tmux/wiki
[2]: sys/tests/README.md
[3]: launch
[4]: include/sys/klog.h


text:
title: "Federation API"
description: "The federation API controls federation of Sensu clusters. This reference describes the Sensu federation API, including examples. Read on for the full reference."
version: "5.20"
product: "Sensu Go"
menu:
  sensu-go-5.20:
    parent: api
---

**COMMERCIAL FEATURE**: Access federation in the packaged Sensu Go distribution.
For more information, see [Get started with commercial features][1].

{{% notice note %}}
**NOTE**: Requests to the federation API require you to authenticate with a Sensu [access token](../#authenticate-with-the-authentication-api) or [API key](../#authenticate-with-an-api-key).
The code examples in this document use the [environment variable](../#configure-an-environment-variable-for-api-key-authentication) `$SENSU_API_KEY` to represent a valid API key in API requests.
{{% /notice %}}

## Get all replicators

The `/etcd-replicators` API endpoint provides HTTP GET access to a list of replicators.

{{% notice note %}}
**NOTE**: The etcd-replicators datatype is only accessible for users who have a cluster role that permits access to replication resources.
{{% /notice %}}

### Example {#etcd-replicators-get-example}

The following example demonstrates a request to the `/etcd-replicators` API endpoint, resulting in a list of replicators.

{{}}
curl -X GET \
http://127.0.0.1:8080/api/enterprise/federation/v1/etcd-replicators \
-H "Authorization: Key $SENSU_API_KEY"
[
  {
    "api_version": "federation/v1",
    "type": "EtcdReplicator",
    "metadata": {
      "name": "my_replicator",
      "created_by": "admin"
    },
    "spec": {
      "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
      "cert": "/path/to/ssl/cert.pem",
      "key": "/path/to/ssl/key.pem",
      "insecure": false,
      "url": "http://remote-etcd.example.com:2379",
      "api_version": "core/v2",
      "resource": "Role",
      "replication_interval_seconds": 30
    }
  }
]
{{}}

### API Specification {#etcd-replicators-get-specification}

/etcd-replicators (GET)  |
---------------|------
description    | Returns the list of replicators.
example url    | http://hostname:8080/api/enterprise/federation/v1/etcd-replicators
response type  | Array
response codes |

**Success**: 200 (OK)

**Error**: 500 (Internal Server Error)

output         | {{}}
[
  {
    "api_version": "federation/v1",
    "type": "EtcdReplicator",
    "metadata": {
      "name": "my_replicator",
      "created_by": "admin"
    },
    "spec": {
      "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
      "cert": "/path/to/ssl/cert.pem",
      "key": "/path/to/ssl/key.pem",
      "insecure": false,
      "url": "http://remote-etcd.example.com:2379",
      "api_version": "core/v2",
      "resource": "Role",
      "replication_interval_seconds": 30
    }
  }
]
{{}}

## Create a new replicator

The `/etcd-replicators` API endpoint provides HTTP POST access to create replicators.

{{% notice note %}}
**NOTE**: Create a replicator for each resource type you want to replicate.
Replicating `namespace` resources will **not** replicate the resources that belong to those namespaces.
{{% /notice %}}

### Example {#etcd-replicators-post-example}

The following example demonstrates a request to the `/etcd-replicators` API endpoint to create the replicator `my_replicator`.

{{}}
curl -X POST \
-H "Authorization: Key $SENSU_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}' \
http://127.0.0.1:8080/api/enterprise/federation/v1/etcd-replicators

HTTP/1.1 200 OK
{{}}

### API Specification {#etcd-replicators-post-specification}

/etcd-replicators (POST) |
----------------|------
description     | Creates a new replicator (if none exists).
example URL     | http://hostname:8080/api/enterprise/federation/v1/etcd-replicators
payload         | {{}}
{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}
{{}}
response codes  |

**Success**: 200 (OK)

**Malformed**: 400 (Bad Request)

**Error**: 500 (Internal Server Error)

## Get a specific replicator {#etcd-replicatorsetcd-replicator-get}

The `/etcd-replicators/:etcd-replicator` API endpoint provides HTTP GET access to data for a specific `:etcd-replicator`, by replicator name.

{{% notice note %}}
**NOTE**: The etcd-replicators datatype is only accessible for users who have a cluster role that permits access to replication resources.
{{% /notice %}}

### Example {#etcd-replicatorsetcd-replicator-get-example}

In the following example, querying the `/etcd-replicators/:etcd-replicator` API endpoint returns a JSON map that contains the requested `:etcd-replicator`.

{{}}
curl -X GET \
http://127.0.0.1:8080/api/enterprise/federation/v1/etcd-replicators/my_replicator \
-H "Authorization: Key $SENSU_API_KEY"
{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator",
    "created_by": "admin"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}
{{}}

### API Specification {#etcd-replicatorsetcd-replicator-get-specification}

/etcd-replicators/:etcd-replicator (GET) |
---------------------|------
description          | Returns the specified replicator.
example url          | http://hostname:8080/api/enterprise/federation/v1/etcd-replicators/my_replicator
response type        | Map
response codes       |

**Success**: 200 (OK)

 **Missing**: 404 (Not Found)

**Error**: 500 (Internal Server Error)

output               | {{}}
{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator",
    "created_by": "admin"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}
{{}}

## Create or update a replicator {#etcd-replicatorsetcd-replicator-put}

The `/etcd-replicators/:etcd-replicator` API endpoint provides HTTP PUT access to create or update a specific `:etcd-replicator`, by replicator name.

### Example {#etcd-replicatorsetcd-replicator-put-example}

The following example demonstrates a request to the `/etcd-replicators/:etcd-replicator` API endpoint to update the replicator `my_replicator`.

{{}}
curl -X PUT \
-H "Authorization: Key $SENSU_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}' \
http://127.0.0.1:8080/api/enterprise/federation/v1/etcd-replicators/my-replicator

HTTP/1.1 200 OK
{{}}

### API Specification {#etcd-replicatorsetcd-replicator-put-specification}

/etcd-replicators/:etcd-replicator (PUT) |
----------------|------
description     | Creates or updates the specified replicator. The replicator resource and API version cannot be altered.
example URL     | http://hostname:8080/api/enterprise/federation/v1/etcd-replicators/my_replicator
payload         | {{}}
{
  "api_version": "federation/v1",
  "type": "EtcdReplicator",
  "metadata": {
    "name": "my_replicator"
  },
  "spec": {
    "ca_cert": "/path/to/ssl/trusted-certificate-authorities.pem",
    "cert": "/path/to/ssl/cert.pem",
    "key": "/path/to/ssl/key.pem",
    "insecure": false,
    "url": "http://remote-etcd.example.com:2379",
    "api_version": "core/v2",
    "resource": "Role",
    "replication_interval_seconds": 30
  }
}
{{}}
response codes  |

**Success**: 201 (Created)

**Malformed**: 400 (Bad Request)

**Error**: 500 (Internal Server Error)

## Delete a replicator {#etcd-replicatorsetcd-replicator-delete}

The `/etcd-replicators/:etcd-replicator` API endpoint provides HTTP DELETE access to delete the specified replicator from Sensu.

### Example {#etcd-replicatorsetcd-replicator-delete-example}

The following example shows a request to the `/etcd-replicators/:etcd-replicator` API endpoint to delete the replicator `my_replicator`, resulting in a successful HTTP `204 No Content` response.

{{}}
curl -X DELETE \
-H "Authorization: Key $SENSU_API_KEY" \
http://127.0.0.1:8080/api/enterprise/federation/v1/etcd-replicators/my_replicator

HTTP/1.1 204 No Content
{{}}

### API Specification {#etcd-replicatorsetcd-replicator-delete-specification}

/etcd-replicators/:etcd-replicator (DELETE) |
--------------------------|------
description               | Deletes the specified replicator from Sensu.
example url               | http://hostname:8080/api/enterprise/federation/v1/etcd-replicators/my_replicator
response codes            |

**Success**: 204 (No Content)

**Missing**: 404 (Not Found)

**Error**: 500 (Internal Server Error)

## Get all clusters

The `/clusters` API endpoint provides HTTP GET access to a list of clusters.

### Example {#clusters-get-example}

The following example demonstrates a request to the `/clusters` API endpoint, resulting in a list of clusters.

{{}}
curl -X GET \
http://127.0.0.1:8080/api/enterprise/federation/v1/clusters \
-H "Authorization: Key $SENSU_API_KEY"

HTTP/1.1 200 OK

[
    {
        "type": "Cluster",
        "api_version": "federation/v1",
        "metadata": {
            "name": "us-west-2a",
            "created_by": "admin"
        },
        "spec": {
            "api_urls": [
                "http://10.0.0.1:8080",
                "http://10.0.0.2:8080",
                "http://10.0.0.3:8080"
            ]
        }
    }
]
{{}}

### API Specification {#clusters-get-specification}

/clusters (GET)  |
---------------|------
description    | Returns the list of clusters.
example url    | http://hostname:8080/api/enterprise/federation/v1/clusters
response type  | Array
response codes |

**Success**: 200 (OK)

**Error**: 500 (Internal Server Error)

output         | {{}}
[
    {
        "type": "Cluster",
        "api_version": "federation/v1",
        "metadata": {
            "name": "us-west-2a",
            "created_by": "admin"
        },
        "spec": {
            "api_urls": [
                "http://10.0.0.1:8080",
                "http://10.0.0.2:8080",
                "http://10.0.0.3:8080"
            ]
        }
    }
]
{{}}

## Get a specific cluster {#clusterscluster-get}

The `/clusters/:cluster` API endpoint provides HTTP GET access to data for a specific `cluster`, by cluster name.

### Example {#clusterscluster-get-example}

In the following example, querying the `/clusters/:cluster` API endpoint returns a JSON map that contains the requested `:etcd-replicator`.

{{}}
curl -X GET \
http://127.0.0.1:8080/api/enterprise/federation/v1/clusters/us-west-2a \
-H "Authorization: Key $SENSU_API_KEY"

HTTP/1.1 200 OK

{
  "type": "Cluster",
  "api_version": "federation/v1",
  "metadata": {
      "name": "us-west-2a",
      "created_by": "admin"
  },
  "spec": {
      "api_urls": [
          "http://10.0.0.1:8080",
          "http://10.0.0.2:8080",
          "http://10.0.0.3:8080"
      ]
  }
}
{{}}

### API Specification {#clusterscluster-get-specification}

/clusters/:cluster (GET) |
---------------------|------
description          | Returns the specified cluster.
example url          | http://hostname:8080/api/enterprise/federation/v1/clusters/us-west-2a
response type        | Map
response codes       |

**Success**: 200 (OK)

 **Missing**: 404 (Not Found)

**Error**: 500 (Internal Server Error)

output               | {{}}
{
    "type": "Cluster",
    "api_version": "federation/v1",
    "metadata": {
        "name": "us-west-2a",
        "created_by": "admin"
    },
    "spec": {
        "api_urls": [
            "http://10.0.0.1:8080",
            "http://10.0.0.2:8080",
            "http://10.0.0.3:8080"
        ]
    }
}
{{}}

## Create or update a cluster {#clusterscluster-put}

The `/clusters/:cluster` API endpoint provides HTTP PUT access to create or update a specific `cluster`, by cluster name.

{{% notice note %}}
**NOTE**: Only cluster admins have PUT access to clusters.
{{% /notice %}}

### Example {#clusterscluster-put-example}

The following example demonstrates a request to the `/clusters/:cluster` API endpoint to update the cluster `us-west-2a`.

{{}}
curl -X PUT \
-H "Authorization: Key $SENSU_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "type": "Cluster",
    "api_version": "federation/v1",
    "metadata": {
        "name": "us-west-2a"
    },
    "spec": {
        "api_urls": [
            "http://10.0.0.1:8080",
            "http://10.0.0.2:8080",
            "http://10.0.0.3:8080"
        ]
    }
}' \
http://127.0.0.1:8080/api/enterprise/federation/v1/clusters/us-west-2a

HTTP/1.1 200 OK
{{}}

### API Specification {#clusterscluster-put-specification}

/clusters/:cluster (PUT) |
----------------|------
description     | Creates or updates the specified cluster.
example URL     | http://hostname:8080/api/enterprise/federation/v1/clusters/us-west-2a
payload         | {{}}
{
    "type": "Cluster",
    "api_version": "federation/v1",
    "metadata": {
            "name": "us-west-2a"
    },
    "spec": {
        "api_urls": [
            "http://10.0.0.1:8080",
            "http://10.0.0.2:8080",
            "http://10.0.0.3:8080"
        ]
    }
}
{{}}
response codes  |

**Success**: 201 (Created)

**Malformed**: 400 (Bad Request)

**Error**: 500 (Internal Server Error)

## Delete a cluster {#clusterscluster-delete}

The `/clusters/:cluster` API endpoint provides HTTP DELETE access to delete the specified cluster from Sensu.

{{% notice note %}}
**NOTE**: Only cluster admins have DELETE access to clusters.
{{% /notice %}}

### Example {#clusterscluster-delete-example}

The following example shows a request to the `/clusters/:cluster` API endpoint to delete the cluster `us-west-2a`, resulting in a successful HTTP `204 No Content` response.

{{}}
curl -X DELETE \
-H "Authorization: Key $SENSU_API_KEY" \
http://127.0.0.1:8080/api/enterprise/federation/v1/clusters/us-west-2a

HTTP/1.1 204 No Content
{{}}

### API Specification {#clusterscluster-delete-specification}

/clusters/:cluster (DELETE) |
--------------------------|------
description               | Deletes the specified cluster from Sensu.
example url               | http://hostname:8080/api/enterprise/federation/v1/clusters/us-west-2a
response codes            |

**Success**: 204 (No Content)

**Missing**: 404 (Not Found)

**Error**: 500 (Internal Server Error)

[1]: ../../commercial/


text:
layout: page
title: Champion Aerospace Seminar
date: 2016-05-24
author: Andrea Jones
tags: weekly links, java
status: published
summary: Nunc pulvinar at ipsum vitae auctor. Nullam lobortis.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/29/2018
  endDate: 01/31/2018
  ctyhocn: SLEORHX
  groupCode: CAS
published: true
---
Etiam fermentum nunc sit amet mauris finibus consequat. Praesent at nulla dui. Praesent in urna elementum, porttitor nisi in, tristique nulla. Cras vitae rhoncus eros. Curabitur libero ante, semper a lobortis sed, hendrerit at risus. Etiam hendrerit risus ac nisi posuere posuere. Integer sit amet efficitur urna.

* Vestibulum in eros in nulla cursus viverra.

Nulla porttitor tellus ut felis pretium egestas. Etiam ipsum lacus, scelerisque a enim ac, pellentesque imperdiet ligula. Aliquam vestibulum lacus eu dapibus commodo. Nulla tincidunt odio non consequat consequat. Nulla tellus sem, egestas eget aliquet a, consectetur non arcu. Fusce non lacinia libero. Vestibulum lacus elit, eleifend volutpat mauris ut, dignissim pharetra magna. Ut nibh ligula, egestas in odio eget, pretium tincidunt lacus. Vestibulum venenatis sem ac aliquam eleifend. Vestibulum eros est, cursus vitae lacus eget, ultrices dapibus erat. Nam a justo quam. Duis egestas accumsan ante eget viverra. Nunc ornare sapien quam, nec pulvinar ipsum scelerisque sed. Sed luctus, velit vitae consequat venenatis, tellus lorem porta eros, non venenatis mauris urna tincidunt tellus. Maecenas vel magna vel felis eleifend dictum at sed odio.
Donec faucibus auctor ex, at dapibus nisi laoreet eget. Nullam venenatis tristique purus. Fusce non iaculis quam. Sed imperdiet molestie mi vitae porttitor. Nulla posuere quis odio sed consectetur. Pellentesque vel sapien eu tortor viverra pulvinar eu in elit. Suspendisse id mollis dui. Mauris quis est ac ligula aliquet aliquet. Donec condimentum venenatis ligula sed commodo. Donec lacinia ex ac metus varius vestibulum. Sed id porttitor neque, vitae sagittis libero.


text:
Package('Sapphire', {
/**********************************************************************************
	Class: DefaultRouter
*/
	DefaultRouter : new Class({
		Extends : Sapphire.Eventer,

		initialize : function()
		{
			this.parent();
			this.history = SAPPHIRE.history;

			SAPPHIRE.application.listenPageEvent('show', '', this.onPageShow.bind(this));
			SAPPHIRE.application.listenPanelEvent('show', '', '', this.onPanelShow.bind(this));
		},

		parseEvent : function(event)
		{
			var result = {};
			var paths = event.path.split('/');
			paths.shift();
			var path = paths[0];
			result.page = path;
			result.path = event.path;
			result.query = (event.queryString != '')?event.queryString.parseQueryString():{};
			return result;
		},

		handleEvent : function(event)
		{
			var address = this.parseEvent(event);
			SAPPHIRE.application.showPage(address.page, address.path, address.query);
		},

		onPageShow : function(name, path, query)
		{
			path = (path !== undefined)?path:name;
			var queryStr = Object.toQueryString(query);

			this.history.setPath(path, queryStr);
		},

		onPanelShow : function(name, path, query)
		{
			path = (path !== undefined)?path:name;
			var queryStr = Object.toQueryString(query);

			this.history.setPath(path, queryStr);
		}

	})
});

SAPPHIRE.history.installRouter(new Sapphire.DefaultRouter());


text:
Test data for GeographicLib
===========================

*NOTE:* It's not necessary to download these files to use
GeographicLib.

`GeodTest.dat.gz` and `GeodTest-short.dat.gz` provide test data for
geodesics.  See

> https://geographiclib.sourceforge.io/C++/doc/geodesic.html#testgeod

`TMCoords.dat.gz` provides test data for the transverse Mercator
projection.  See

> https://geographiclib.sourceforge.io/C++/doc/transversemercator.html#testmerc

`GeoidHeights.dat.gz` provides test data for geoid heights.  See

> https://geographiclib.sourceforge.io/C++/doc/geoid.html#testgeoid


text:
			<custom-nav></custom-nav>

How well do you know your friends?

			<button class="btn btn-outline-success" (click)="openPage('/list')">

				 BUY NOW
			</button>

						Introduction

Six Strange Tales is a complex and intertwined series of stories intricately woven around the fates of a small community of characters. Quentin Tarantino and Vincent Gallo come to mind as the plot twists and turns through alternating time periods in the lives of these anti-heroes, sadists, monsters and villains. This book may be the best noir literary work published in recent history.

Author, Individual Eleven, actually had these nightmares, wrote them down at dusk, elaborated and shared them with all of us. The book touches on subject matter such as gore and violence, mystery, sex, purgatory, the dangers of drug abuse and even...

...read more >>

						Synopsis

						chapter 1

						chapter 2

						chapter 3

						Author

Individual Eleven is a rare breed of author. This work was created when he decided that he would write down his bad dreams at night. Through that process he concocted some of the darkest stories driven by the depths and inner demons of one human mind.

Actually, Indie got his start as a musician later transitioning into the world of film and television producing what he calls artistic renditions of other peoples greed. Writing has been an off and on love affair, which eventually...

...read more >>


text:
require "mongoid"

Mongoid.logger.level = Logger::WARN
Mongoid.load! File.expand_path("../mongoid.yml", File.dirname(__FILE__))


text:
package rapture.plugin;

public enum PluginLocation {
    LOCAL, REMOTE, TMP, INSTALLED
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace GraphQL.Instrumentation
{
    public class Metrics : IDisposable
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly IList<PerfRecord> _records = new List<PerfRecord>();
        private PerfRecord _main;

        public void Start(string operationName)
        {
            _main = new PerfRecord("operation", operationName, 0);
            _records.Add(_main);
            _stopwatch.Start();
        }

        public void SetOperationName(string name)
        {
            _main.Subject = name;
        }

        public IDisposable Subject(string category, string subject, Dictionary<string, object> metadata = null)
        {
            var record = new PerfRecord(category, subject, _stopwatch.ElapsedMilliseconds, metadata);
            _records.Add(record);
            return new Marker(record, _stopwatch);
        }

        public IEnumerable<PerfRecord> AllRecords => _records.OrderBy(x => x.Start).ToArray();

        public IEnumerable<PerfRecord> Finish()
        {
            _main?.MarkEnd(_stopwatch.ElapsedMilliseconds);
            _stopwatch.Stop();
            return AllRecords;
        }

        public class Marker : IDisposable
        {
            private readonly PerfRecord _record;
            private readonly Stopwatch _stopwatch;

            public Marker(PerfRecord record, Stopwatch stopwatch)
            {
                _record = record;
                _stopwatch = stopwatch;
            }

            public void Dispose()
            {
                _record.MarkEnd(_stopwatch.ElapsedMilliseconds);
            }
        }

        public void Dispose()
        {
            if (_stopwatch.IsRunning) _stopwatch.Stop();
        }
    }
}


text:
Installation
------------

    # in the project root
    mvn clean package -DskipTests -pl encryption-cli -am

Preparation
-----------

Configure AWS [credentials](http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default)
and [region](http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#automatically-determine-the-aws-region-from-the-environment).

Usage
-----

### Encrypt

    ./run.sh --encrypt.plaintext='Hello World!' --aws.kms.keyId='9d9fca31-54c5-4df5-ba4f-127dfb9a5031'

### Decrypt

    ./run.sh --decrypt.ciphertext='CiA47hYvQqWFFGq3TLtzQO5ArcwDkjq69Q=='


text:
Monitor fs events and reload docker-compose on changes

Watches for FS events and reloads the docker-compose.yml from the current working dir.
Also sends livereload notifications.

### Usage

docker-compose-watcher --watch . --service app

if `--service` is not set reload all services.
If `--watch` is not set, watch current dir (and all subdirs).
`--watch` can be specified multiple times


text:
#import <OfficeImport/CMDiagramPointMapper.h>

// Not exported
@interface CMDiagramPointRoundedRectMapper : CMDiagramPointMapper
{
}

- (void)mapAt:(id)arg1 withState:(id)arg2;

@end