text:
from __future__ import absolute_import
from __future__ import with_statement

import os

from mock import Mock, patch
from pickle import loads, dumps

from kombu import Exchange

from celery import Celery
from celery import app as _app
from celery import state
from celery.app import defaults
from celery.loaders.base import BaseLoader
from celery.platforms import pyimplementation
from celery.utils.serialization import pickle

from celery.tests import config
from celery.tests.utils import (Case, mask_modules, platform_pyimp,
                                sys_platform, pypy_version)
from celery.utils import uuid
from celery.utils.mail import ErrorMail

THIS_IS_A_KEY = "this is a value"

class Object(object):

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

def _get_test_config():
    return dict((key, getattr(config, key))
                    for key in dir(config)
                        if key.isupper() and not key.startswith("_"))

test_config = _get_test_config()

class test_module(Case):

    def test_default_app(self):
        self.assertEqual(_app.default_app, state.default_app)

    def test_bugreport(self):
        self.assertTrue(_app.bugreport())

class test_App(Case):

    def setUp(self):
        self.app = Celery(set_as_current=False)
        self.app.conf.update(test_config)

    def test_task(self):
        app = Celery("foozibari", set_as_current=False)

        def fun():
            pass

        fun.__module__ = "__main__"
        task = app.task(fun)
        self.assertEqual(task.name, app.main + ".fun")

    def test_with_broker(self):
        prev = os.environ.get("CELERY_BROKER_URL")
        os.environ.pop("CELERY_BROKER_URL", None)
        try:
            app = Celery(set_as_current=False, broker="foo://baribaz")
            self.assertEqual(app.conf.BROKER_HOST, "foo://baribaz")
        finally:
            os.environ["CELERY_BROKER_URL"] = prev

    def test_repr(self):
        self.assertTrue(repr(self.app))

    def test_custom_task_registry(self):
        app1 = Celery(set_as_current=False)
        app2 = Celery(set_as_current=False, tasks=app1.tasks)
        self.assertIs(app2.tasks, app1.tasks)

    def test_include_argument(self):
        app = Celery(set_as_current=False, include=("foo", "bar.foo"))
        self.assertEqual(app.conf.CELERY_IMPORTS, ("foo", "bar.foo"))

    def test_set_as_current(self):
        current = state._tls.current_app
        try:
            app = Celery(set_as_current=True)
            self.assertIs(state._tls.current_app, app)
        finally:
            state._tls.current_app = current

    def test_current_task(self):
        app = Celery(set_as_current=False)

        @app.task
        def foo():
            pass

        state._task_stack.push(foo)
        try:
            self.assertEqual(app.current_task.name, foo.name)
        finally:
            state._task_stack.pop()

    def test_task_not_shared(self):
        with patch("celery.app.base.shared_task") as shared_task:
            app = Celery(set_as_current=False)
            @app.task(shared=False)
            def foo():
                pass
            self.assertFalse(shared_task.called)

    def test_task_compat_with_filter(self):
        app = Celery(set_as_current=False, accept_magic_kwargs=True)
        check = Mock()

        def filter(task):
            check(task)
            return task

        @app.task(filter=filter)
        def foo():
            pass
        check.assert_called_with(foo)

    def test_task_with_filter(self):
        app = Celery(set_as_current=False, accept_magic_kwargs=False)
        check = Mock()

        def filter(task):
            check(task)
            return task

        @app.task(filter=filter)
        def foo():
            pass
        check.assert_called_with(foo)

    def test_task_sets_main_name_MP_MAIN_FILE(self):
        from celery.app import task as _task
        _task.MP_MAIN_FILE = __file__
        try:
            app = Celery("xuzzy", set_as_current=False)

            @app.task
            def foo():
                pass

            self.assertEqual(foo.name, "xuzzy.foo")
        finally:
            _task.MP_MAIN_FILE = None

    def test_base_task_inherits_magic_kwargs_from_app(self):
        from celery.app.task import Task

        class timkX(Task):
            abstract = True

        app = Celery(set_as_current=False, accept_magic_kwargs=True)
        timkX.bind(app)
        self.assertTrue(timkX.accept_magic_kwargs)

    def test_annotate_decorator(self):
        from celery.app.task import Task

        class adX(Task):
            abstract = True

            def run(self, y, z, x):
                return y, z, x

        check = Mock()
        def deco(fun):
            def _inner(*args, **kwargs):
                check(*args, **kwargs)
                return fun(*args, **kwargs)
            return _inner

        app = Celery(set_as_current=False)
        app.conf.CELERY_ANNOTATIONS = {
                adX.name: {"@__call__": deco}
        }
        adX.bind(app)
        self.assertIs(adX.app, app)

        i = adX()
        i(2, 4, x=3)
        check.assert_called_with(i, 2, 4, x=3)

        i.annotate()
        i.annotate()

    def test_apply_async_has__self__(self):
        app = Celery(set_as_current=False)

        @app.task(__self__="hello")
        def aawsX():
            pass

        with patch("celery.app.amqp.TaskProducer.delay_task") as dt:
            aawsX.apply_async((4, 5))
            args = dt.call_args[0][1]
            self.assertEqual(args, ("hello", 4, 5))

    def test_apply_async__connection_arg(self):
        app = Celery(set_as_current=False)

        @app.task()
        def aacaX():
            pass

        connection = app.broker_connection("asd://")
        with self.assertRaises(KeyError):
            aacaX.apply_async(connection=connection)

    def test_apply_async_adds_children(self):
        from celery.state import _task_stack
        app = Celery(set_as_current=False)

        @app.task()
        def a3cX1(self):
            pass

        @app.task()
        def a3cX2(self):
            pass

        _task_stack.push(a3cX1)
        try:
            a3cX1.push_request(called_directly=False)
            try:
                res = a3cX2.apply_async(add_to_parent=True)
                self.assertIn(res, a3cX1.request.children)
            finally:
                a3cX1.pop_request()
        finally:
            _task_stack.pop()

    def test_TaskSet(self):
        ts = self.app.TaskSet()
        self.assertListEqual(ts.tasks, [])
        self.assertIs(ts.app, self.app)

    def test_pickle_app(self):
        changes = dict(THE_FOO_BAR="bars",
                       THE_MII_MAR="jars")
        self.app.conf.update(changes)
        saved = pickle.dumps(self.app)
        self.assertLess(len(saved), 2048)
        restored = pickle.loads(saved)
        self.assertDictContainsSubset(changes, restored.conf)

    def test_worker_main(self):
        from celery.bin import celeryd

        class WorkerCommand(celeryd.WorkerCommand):

            def execute_from_commandline(self, argv):
                return argv

        prev, celeryd.WorkerCommand = celeryd.WorkerCommand, WorkerCommand
        try:
            ret = self.app.worker_main(argv=["--version"])
            self.assertListEqual(ret, ["--version"])
        finally:
            celeryd.WorkerCommand = prev

    def test_config_from_envvar(self):
        os.environ["CELERYTEST_CONFIG_OBJECT"] = "celery.tests.app.test_app"
        self.app.config_from_envvar("CELERYTEST_CONFIG_OBJECT")
        self.assertEqual(self.app.conf.THIS_IS_A_KEY, "this is a value")

    def test_config_from_object(self):

        class Object(object):
            LEAVE_FOR_WORK = True
            MOMENT_TO_STOP = True
            CALL_ME_BACK = 123456789
            WANT_ME_TO = False
            UNDERSTAND_ME = True

        self.app.config_from_object(Object())

        self.assertTrue(self.app.conf.LEAVE_FOR_WORK)
        self.assertTrue(self.app.conf.MOMENT_TO_STOP)
        self.assertEqual(self.app.conf.CALL_ME_BACK, 123456789)
        self.assertFalse(self.app.conf.WANT_ME_TO)
        self.assertTrue(self.app.conf.UNDERSTAND_ME)

    def test_config_from_cmdline(self):
        cmdline = [".always_eager=no",
                   ".result_backend=/dev/null",
                   '.task_error_whitelist=(list)["a", "b", "c"]',
                   "celeryd.prefetch_multiplier=368",
                   ".foobarstring=(string)300",
                   ".foobarint=(int)300",
                   '.result_engine_options=(dict){"foo": "bar"}']
        self.app.config_from_cmdline(cmdline, namespace="celery")
        self.assertFalse(self.app.conf.CELERY_ALWAYS_EAGER)
        self.assertEqual(self.app.conf.CELERY_RESULT_BACKEND, "/dev/null")
        self.assertEqual(self.app.conf.CELERYD_PREFETCH_MULTIPLIER, 368)
        self.assertListEqual(self.app.conf.CELERY_TASK_ERROR_WHITELIST,
                             ["a", "b", "c"])
        self.assertEqual(self.app.conf.CELERY_FOOBARSTRING, "300")
        self.assertEqual(self.app.conf.CELERY_FOOBARINT, 300)
        self.assertDictEqual(self.app.conf.CELERY_RESULT_ENGINE_OPTIONS,
                             {"foo": "bar"})

    def test_compat_setting_CELERY_BACKEND(self):

        self.app.config_from_object(Object(CELERY_BACKEND="set_by_us"))
        self.assertEqual(self.app.conf.CELERY_RESULT_BACKEND, "set_by_us")

    def test_setting_BROKER_TRANSPORT_OPTIONS(self):

        _args = {'foo': 'bar', 'spam': 'baz'}

        self.app.config_from_object(Object())
        self.assertEqual(self.app.conf.BROKER_TRANSPORT_OPTIONS, {})

        self.app.config_from_object(Object(BROKER_TRANSPORT_OPTIONS=_args))
        self.assertEqual(self.app.conf.BROKER_TRANSPORT_OPTIONS, _args)

    def test_Windows_log_color_disabled(self):
        self.app.IS_WINDOWS = True
        self.assertFalse(self.app.log.supports_color())

    def test_compat_setting_CARROT_BACKEND(self):
        self.app.config_from_object(Object(CARROT_BACKEND="set_by_us"))
        self.assertEqual(self.app.conf.BROKER_TRANSPORT, "set_by_us")

    def test_WorkController(self):
        x = self.app.WorkController
        self.assertIs(x.app, self.app)

    def test_Worker(self):
        x = self.app.Worker
        self.assertIs(x.app, self.app)

    def test_AsyncResult(self):
        x = self.app.AsyncResult("1")
        self.assertIs(x.app, self.app)
        r = loads(dumps(x))
        # not set as current, so ends up as default app after reduce
        self.assertIs(r.app, state.default_app)

    @patch("celery.bin.celery.CeleryCommand.execute_from_commandline")
    def test_start(self, execute):
        self.app.start()
        self.assertTrue(execute.called)

    def test_mail_admins(self):

        class Loader(BaseLoader):

            def mail_admins(*args, **kwargs):
                return args, kwargs

        self.app.loader = Loader()
        self.app.conf.ADMINS = None
        self.assertFalse(self.app.mail_admins("Subject", "Body"))
        self.app.conf.ADMINS = [("George Costanza", "george@vandelay.com")]
        self.assertTrue(self.app.mail_admins("Subject", "Body"))

    def test_amqp_get_broker_info(self):
        self.assertDictContainsSubset({"hostname": "localhost",
                                       "userid": "guest",
                                       "password": "guest",
                                       "virtual_host": "/"},
                            self.app.broker_connection("amqplib://").info())
        self.app.conf.BROKER_PORT = 1978
        self.app.conf.BROKER_VHOST = "foo"
        self.assertDictContainsSubset({"port": 1978,
                                       "virtual_host": "foo"},
                    self.app.broker_connection("amqplib://:1978/foo").info())
        conn = self.app.broker_connection("amqplib:////value")
        self.assertDictContainsSubset({"virtual_host": "/value"},
                                      conn.info())

    def test_BROKER_BACKEND_alias(self):
        self.assertEqual(self.app.conf.BROKER_BACKEND,
                         self.app.conf.BROKER_TRANSPORT)

    def test_with_default_connection(self):

        @self.app.with_default_connection
        def handler(connection=None, foo=None):
            return connection, foo

        connection, foo = handler(foo=42)
        self.assertEqual(foo, 42)
        self.assertTrue(connection)

    def test_after_fork(self):
        p = self.app._pool = Mock()
        self.app._after_fork(self.app)
        p.force_close_all.assert_called_with()
        self.assertIsNone(self.app._pool)
        self.app._after_fork(self.app)

    def test_pool_no_multiprocessing(self):
        with mask_modules("multiprocessing.util"):
            pool = self.app.pool
            self.assertIs(pool, self.app._pool)

    def test_bugreport(self):
        self.assertTrue(self.app.bugreport())

    def test_send_task_sent_event(self):

        class Dispatcher(object):
            sent = []

            def send(self, type, **fields):
                self.sent.append((type, fields))

        conn = self.app.broker_connection()
        chan = conn.channel()
        try:
            for e in ("foo_exchange", "moo_exchange", "bar_exchange"):
                chan.exchange_declare(e, "direct", durable=True)
                chan.queue_declare(e, durable=True)
                chan.queue_bind(e, e, e)
        finally:
            chan.close()
        assert conn.transport_cls == "memory"

        pub = self.app.amqp.TaskProducer(conn,
                exchange=Exchange("foo_exchange"))

        dispatcher = Dispatcher()
        self.assertTrue(pub.delay_task("footask", (), {},
                                       exchange="moo_exchange",
                                       routing_key="moo_exchange",
                                       event_dispatcher=dispatcher))
        self.assertTrue(dispatcher.sent)
        self.assertEqual(dispatcher.sent[0][0], "task-sent")
        self.assertTrue(pub.delay_task("footask", (), {},
                                       event_dispatcher=dispatcher,
                                       exchange="bar_exchange",
                                       routing_key="bar_exchange"))

    def test_error_mail_sender(self):
        x = ErrorMail.subject % {"name": "task_name",
                                 "id": uuid(),
                                 "exc": "FOOBARBAZ",
                                 "hostname": "lana"}
        self.assertTrue(x)

class test_defaults(Case):

    def test_str_to_bool(self):
        for s in ("false", "no", "0"):
            self.assertFalse(defaults.strtobool(s))
        for s in ("true", "yes", "1"):
            self.assertTrue(defaults.strtobool(s))
        with self.assertRaises(TypeError):
            defaults.strtobool("unsure")

class test_debugging_utils(Case):

    def test_enable_disable_trace(self):
        try:
            _app.enable_trace()
            self.assertEqual(_app.app_or_default, _app._app_or_default_trace)
            _app.disable_trace()
            self.assertEqual(_app.app_or_default, _app._app_or_default)
        finally:
            _app.disable_trace()

class test_pyimplementation(Case):

    def test_platform_python_implementation(self):
        with platform_pyimp(lambda: "Xython"):
            self.assertEqual(pyimplementation(), "Xython")

    def test_platform_jython(self):
        with platform_pyimp():
            with sys_platform("java 1.6.51"):
                self.assertIn("Jython", pyimplementation())

    def test_platform_pypy(self):
        with platform_pyimp():
            with sys_platform("darwin"):
                with pypy_version((1, 4, 3)):
                    self.assertIn("PyPy", pyimplementation())
                with pypy_version((1, 4, 3, "a4")):
                    self.assertIn("PyPy", pyimplementation())

    def test_platform_fallback(self):
        with platform_pyimp():
            with sys_platform("darwin"):
                with pypy_version():
                    self.assertEqual("CPython", pyimplementation())


text: init :"bridgetown-feed"

redpajama_set_name: RedPajamaGithub


text:
module Mongo
  class BulkWrite

    # Defines behaviour around validations.
    #
    # @api private
    #
    # @since 2.1.0
    module Validatable

      # Validate the document.
      #
      # @api private
      #
      # @example Validate the document.
      #   validatable.validate(:insert_one, { _id: 0 })
      #
      # @param [ Symbol ] name The operation name.
      # @param [ Hash, BSON::Document ] document The document.
      #
      # @raise [ InvalidBulkOperation ] If not valid.
      #
      # @return [ Hash, BSON::Document ] The document.
      #
      # @since 2.1.0
      def validate(name, document)
        validate_operation(name)
        validate_document(name, document)
        if document.respond_to?(:keys) && (document[:collation] || document[Operation::COLLATION])
          @has_collation = true
        end
      end

      private

      def validate_document(name, document)
        if document.respond_to?(:keys) || document.respond_to?(:data)
          document
        else
          raise Error::InvalidBulkOperation.new(name, document)
        end
      end

      def validate_operation(name)
        unless Transformable::MAPPERS.key?(name)
          raise Error::InvalidBulkOperationType.new(name)
        end
      end
    end
  end
end


text:
namespace {

static const char kMediaRecorderHtmlFile[] = "/media/mediarecorder_test.html";

static struct EncodingParameters {
  bool disable_accelerator;
  std::string mime_type;
} const kEncodingParameters[] = {
    {true, "video/webm;codecs=VP8"},
    {true, "video/webm;codecs=VP9"},
    {true, "video/x-matroska;codecs=AVC1"},
    {false, ""},  // Instructs the platform to choose any accelerated codec.
    {false, "video/webm;codecs=VP8"},
    {false, "video/webm;codecs=VP9"},
    {false, "video/x-matroska;codecs=AVC1"},
};

}  // namespace

namespace content {

// This class tests the recording of a media stream.
class WebRtcMediaRecorderTest
    : public WebRtcContentBrowserTestBase,
      public testing::WithParamInterface<struct EncodingParameters> {
 public:
  WebRtcMediaRecorderTest() {}
  ~WebRtcMediaRecorderTest() override {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    WebRtcContentBrowserTestBase::SetUpCommandLine(command_line);

    AppendUseFakeUIForMediaStreamFlag();

    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kUseFakeDeviceForMediaStream);

    base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kEnableBlinkFeatures, "GetUserMedia");
  }

  void MaybeForceDisableEncodeAccelerator(bool disable) {
    if (!disable)
      return;
    // This flag is also used for encoding, https://crbug.com/616640.
    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kDisableAcceleratedVideoDecode);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(WebRtcMediaRecorderTest);
};

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Start) {
  MakeTypicalCall("testStartAndRecorderState();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, StartAndStop) {
  MakeTypicalCall("testStartStopAndRecorderState();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, StartAndDataAvailable) {
  MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
  MakeTypicalCall(base::StringPrintf("testStartAndDataAvailable(\"%s\");",
                                     GetParam().mime_type.c_str()),
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, StartWithTimeSlice) {
  MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
  MakeTypicalCall(base::StringPrintf("testStartWithTimeSlice(\"%s\");",
                                     GetParam().mime_type.c_str()),
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Resume) {
  MakeTypicalCall("testResumeAndRecorderState();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, NoResumeWhenRecorderInactive) {
  MakeTypicalCall("testIllegalResumeThrowsDOMError();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, ResumeAndDataAvailable) {
  MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
  MakeTypicalCall(base::StringPrintf("testResumeAndDataAvailable(\"%s\");",
                                     GetParam().mime_type.c_str()),
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Pause) {
  MakeTypicalCall("testPauseAndRecorderState();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, PauseStop) {
  MakeTypicalCall("testPauseStopAndRecorderState();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       PausePreventsDataavailableFromBeingFired) {
  MakeTypicalCall("testPausePreventsDataavailableFromBeingFired();",
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, IllegalPauseThrowsDOMError) {
  MakeTypicalCall("testIllegalPauseThrowsDOMError();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, TwoChannelAudioRecording) {
  MakeTypicalCall("testTwoChannelAudio();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, IllegalStopThrowsDOMError) {
  MakeTypicalCall("testIllegalStopThrowsDOMError();", kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       IllegalStartWhileRecordingThrowsDOMError) {
  MakeTypicalCall("testIllegalStartInRecordingStateThrowsDOMError();",
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       IllegalStartWhilePausedThrowsDOMError) {
  MakeTypicalCall("testIllegalStartInPausedStateThrowsDOMError();",
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       IllegalRequestDataThrowsDOMError) {
  MakeTypicalCall("testIllegalRequestDataThrowsDOMError();",
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, PeerConnection) {
  MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
  MakeTypicalCall(base::StringPrintf("testRecordRemotePeerConnection(\"%s\");",
                                     GetParam().mime_type.c_str()),
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       AddingTrackToMediaStreamFiresErrorEvent) {
  MakeTypicalCall("testAddingTrackToMediaStreamFiresErrorEvent();",
                  kMediaRecorderHtmlFile);
}

IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
                       RemovingTrackFromMediaStreamFiresErrorEvent) {
  MakeTypicalCall("testRemovingTrackFromMediaStreamFiresErrorEvent();",
                  kMediaRecorderHtmlFile);
}

INSTANTIATE_TEST_CASE_P(,
                        WebRtcMediaRecorderTest,
                        testing::ValuesIn(kEncodingParameters));

}  // namespace content


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001
002
007
008package org.jsimpledb.util;
009
010import com.google.common.base.Converter;
011
012import java.util.Comparator;
013import java.util.Map;
014import java.util.NavigableMap;
015import java.util.NavigableSet;
016import java.util.NoSuchElementException;
017import java.util.Set;
018
019/**
020 * Provides a transformed view of a wrapped {@link NavigableMap} using a strictly invertable {@link Converter}.
021 *
022 * @param <K> key type of this map
023 * @param <V> value type of this map
024 * @param <WK> key type of wrapped map
025 * @param <WV> value type of wrapped map
026 */
027public class ConvertedNavigableMap<K, V, WK, WV> extends AbstractNavigableMap<K, V> {
028
029    private final NavigableMap<WK, WV> map;
030    private final Converter<K, WK> keyConverter;
031    private final Converter<V, WV> valueConverter;
032
033    /**
034     * Constructor.
035     *
036     * @param map wrapped map
037     * @param keyConverter key converter
038     * @param valueConverter value converter
039     * @throws IllegalArgumentException if any parameter is null
040     */
041    public ConvertedNavigableMap(NavigableMap<WK, WV> map, Converter<K, WK> keyConverter, Converter<V, WV> valueConverter) {
042        this(map, keyConverter, valueConverter, new Bounds<K>());
043    }
044
045    /**
046     * Internal constructor.
047     *
048     * @param map wrapped map
049     * @param keyConverter key converter
050     * @param valueConverter value converter
051     * @throws IllegalArgumentException if any parameter is null
052     */
053    ConvertedNavigableMap(NavigableMap<WK, WV> map,
054      Converter<K, WK> keyConverter, Converter<V, WV> valueConverter, Bounds<K> bounds) {
055        super(bounds);
056        if (map == null)
057            throw new IllegalArgumentException("null map");
058        if (keyConverter == null)
059            throw new IllegalArgumentException("null keyConverter");
060        if (valueConverter == null)
061            throw new IllegalArgumentException("null valueConverter");
062        this.map = map;
063        this.keyConverter = keyConverter;
064        this.valueConverter = valueConverter;
065    }
066
067    public Converter<K, WK> getKeyConverter() {
068        return this.keyConverter;
069    }
070
071    public Converter<V, WV> getValueConverter() {
072        return this.valueConverter;
073    }
074
075    @Override
076    public Comparator<? super K> comparator() {
077        return new ConvertedComparator<K, WK>(this.map.comparator(), this.keyConverter);
078    }
079
080    @Override
081    @SuppressWarnings("unchecked")
082    public V get(Object key) {
083        WK wkey = null;
084        if (key != null) {
085            try {
086                wkey = this.keyConverter.convert((K)key);
087            } catch (ClassCastException e) {
088                return null;
089            }
090        }
091        final WV wvalue = this.map.get(wkey);
092        return wvalue != null ? this.valueConverter.reverse().convert(wvalue) : null;
093    }
094
095    @Override
096    public Set<Map.Entry<K, V>> entrySet() {
097        return new ConvertedEntrySet<K, V, WK, WV>(this.map, this.keyConverter, this.valueConverter);
098    }
099
100    @Override
101    public NavigableSet<K> navigableKeySet() {
102        return new ConvertedNavigableSet<K, WK>(this.map.navigableKeySet(), this.keyConverter);
103    }
104
105    @Override
106    public V put(K key, V value) {
107        final WK wkey = key != null ? this.keyConverter.convert(key) : null;
108        final WV wvalue = value != null ? this.valueConverter.convert(value) : null;
109        final WV wprev = this.map.put(wkey, wvalue);
110        return wprev != null ? this.valueConverter.reverse().convert(wprev) : null;
111    }
112
113    @Override
114    @SuppressWarnings("unchecked")
115    public V remove(Object key) {
116        WK wkey = null;
117        if (key != null) {
118            try {
119                wkey = this.keyConverter.convert((K)key);
120            } catch (ClassCastException e) {
121                return null;
122            }
123        }
124        final WV wvalue = this.map.remove(wkey);
125        return wvalue != null ? this.valueConverter.reverse().convert(wvalue) : null;
126    }
127
128    @Override
129    public void clear() {
130        this.map.clear();
131    }
132
133    @Override
134    public boolean isEmpty() {
135        return this.map.isEmpty();
136    }
137
138    @Override
139    public int size() {
140        return this.map.size();
141    }
142
143    @Override
144    protected Map.Entry<K, V> searchBelow(K maxKey, boolean inclusive) {
145        try {
146            return super.searchBelow(maxKey, inclusive);
147        } catch (IllegalArgumentException e) {                      // handle case where elem is out of bounds
148            final Map.Entry<K, V> lastEntry;
149            try {
150                lastEntry = this.lastEntry();
151            } catch (NoSuchElementException e2) {
152                return null;
153            }
154            return this.getComparator(false).compare(maxKey, lastEntry.getKey()) > 0 ? lastEntry : null;
155        }
156    }
157
158    @Override
159    protected Map.Entry<K, V> searchAbove(K minKey, boolean inclusive) {
160        try {
161            return super.searchAbove(minKey, inclusive);
162        } catch (IllegalArgumentException e) {                      // handle case where elem is out of bounds
163            final Map.Entry<K, V> firstEntry;
164            try {
165                firstEntry = this.firstEntry();
166            } catch (NoSuchElementException e2) {
167                return null;
168            }
169            return this.getComparator(false).compare(minKey, firstEntry.getKey()) < 0 ? firstEntry : null;
170        }
171    }
172
173    @Override
174    protected NavigableMap<K, V> createSubMap(boolean reverse, Bounds<K> newBounds) {
175        final K lower = newBounds.getLowerBound();
176        final K upper = newBounds.getUpperBound();
177        final WK wlower = newBounds.getLowerBoundType() != BoundType.NONE && lower != null ?
178          this.keyConverter.convert(lower) : null;
179        final WK wupper = newBounds.getUpperBoundType() != BoundType.NONE && upper != null ?
180          this.keyConverter.convert(upper) : null;
181        NavigableMap<WK, WV> subMap = reverse ? this.map.descendingMap() : this.map;
182        if (newBounds.getLowerBoundType() != BoundType.NONE && newBounds.getUpperBoundType() != BoundType.NONE) {
183            subMap = subMap.subMap(
184              wlower, newBounds.getLowerBoundType().isInclusive(),
185              wupper, newBounds.getUpperBoundType().isInclusive());
186        } else if (newBounds.getLowerBoundType() != BoundType.NONE)
187            subMap = subMap.tailMap(wlower, newBounds.getLowerBoundType().isInclusive());
188        else if (newBounds.getUpperBoundType() != BoundType.NONE)
189            subMap = subMap.headMap(wupper, newBounds.getUpperBoundType().isInclusive());
190        return new ConvertedNavigableMap<K, V, WK, WV>(subMap, this.keyConverter, this.valueConverter, newBounds);
191    }
192}
193


text:
package com.imc.mobile.android;

import android.text.Spanned;

public class IMCPost {
	public Spanned Title;
	public String Image ;
	public Spanned Excerpt;
	public String CommentCount;
	public String LikeCount;
	public String PostID;
	public String dateposted;
	public String Content;
	public String Author;
	public String ZillaLikeCnt;
	public String PostUrl;

	public String getPostUrl(String _postUrl)
	{
		return _postUrl;
	}
	public void setPostUrl(String _postUrl)
	{
		this.ZillaLikeCnt = _postUrl;
	}

	public String getZillaLikeCnt(String _zilla)
	{
		return _zilla;
	}
	public void setZillaLikeCnt(String _zilla)
	{
		this.ZillaLikeCnt = _zilla;
	}

	public String getAuthor(String _author)
	{
		return _author;
	}
	public void setAuthor(String _author)
	{
		this.Author = _author;
	}
	public String getContent(String _content)
	{
		return _content;
	}
	public void setContent(String _content)
	{
		this.Content = _content;
	}
	public String getdatePosted(String _datePosted)
	{
		return _datePosted;
	}
	public void setdatePosted(String _datePosted)
	{
		this.dateposted = _datePosted;
	}

	public String getPostID(String _postID)
	{
		return _postID;
	}
	public void setPostID(String _postID)
	{
		this.PostID = _postID;
	}

	public Spanned getTitle(Spanned _title)
	{
		return _title;
	}
	public void setTitle (Spanned _title){
		this.Title = _title;
	}
	public String getImage(String _image)
	{
		return _image;
	}
	public void setImage (String _image)
	{
		this.Image = _image;
	}
	public String getCommentCount(String _commentCount)
	{
			return _commentCount;
	}
	public void setCommentCount(String _commentCount)
	{
			this.CommentCount = _commentCount;
	}
	public String getlikeCount(String _likeCount)
	{
		return _likeCount;
	}
	public void setLikeCount(String _likeCount)
	{
		this.LikeCount = _likeCount;
	}

	public Spanned getExcerpt(Spanned _excerpt)
	{
		return _excerpt;
	}
	public void setExcerpt (Spanned _excerpt){
		this.Excerpt = _excerpt;
	}

}


text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
using System.Numerics;
#endif
using System.Text;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;

#endif

namespace Newtonsoft.Json.Tests.Linq
{
    [TestFixture]
    public class JTokenWriterTest : TestFixtureBase
    {
        [Test]
        public void ValueFormatting()
        {
            byte[] data = Encoding.UTF8.GetBytes("Hello world.");

            JToken root;
            using (JTokenWriter jsonWriter = new JTokenWriter())
            {
                jsonWriter.WriteStartArray();
                jsonWriter.WriteValue('@');
                jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
                jsonWriter.WriteValue(true);
                jsonWriter.WriteValue(10);
                jsonWriter.WriteValue(10.99);
                jsonWriter.WriteValue(0.99);
                jsonWriter.WriteValue(0.000000000000000001d);
                jsonWriter.WriteValue(0.000000000000000001m);
                jsonWriter.WriteValue((string)null);
                jsonWriter.WriteValue("This is a string.");
                jsonWriter.WriteNull();
                jsonWriter.WriteUndefined();
                jsonWriter.WriteValue(data);
                jsonWriter.WriteEndArray();

                root = jsonWriter.Token;
            }

            CustomAssert.IsInstanceOfType(typeof(JArray), root);
            Assert.AreEqual(13, root.Children().Count());
            Assert.AreEqual("@", (string)root[0]);
            Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
            Assert.AreEqual(true, (bool)root[2]);
            Assert.AreEqual(10, (int)root[3]);
            Assert.AreEqual(10.99, (double)root[4]);
            Assert.AreEqual(0.99, (double)root[5]);
            Assert.AreEqual(0.000000000000000001d, (double)root[6]);
            Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
            Assert.AreEqual(null, (string)root[8]);
            Assert.AreEqual("This is a string.", (string)root[9]);
            Assert.AreEqual(null, ((JValue)root[10]).Value);
            Assert.AreEqual(null, ((JValue)root[11]).Value);
            Assert.AreEqual(data, (byte[])root[12]);
        }

        [Test]
        public void State()
        {
            using (JsonWriter jsonWriter = new JTokenWriter())
            {
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);

                jsonWriter.WriteStartObject();
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WritePropertyName("CPU");
                Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

                jsonWriter.WriteValue("Intel");
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WritePropertyName("Drives");
                Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

                jsonWriter.WriteStartArray();
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

                jsonWriter.WriteValue("DVD read/writer");
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
                jsonWriter.WriteValue(new BigInteger(123));
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif

                jsonWriter.WriteValue(new byte[0]);
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

                jsonWriter.WriteEnd();
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WriteEndObject();
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
            }
        }

        [Test]
        public void WriteComment()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteComment("fail");
            writer.WriteEndArray();

            StringAssert.AreEqual(@"[
  /*fail*/]", writer.Token.ToString());
        }

#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
        [Test]
        public void WriteBigInteger()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteValue(new BigInteger(123));
            writer.WriteEndArray();

            JValue i = (JValue)writer.Token[0];

            Assert.AreEqual(new BigInteger(123), i.Value);
            Assert.AreEqual(JTokenType.Integer, i.Type);

            StringAssert.AreEqual(@"[
  123
]", writer.Token.ToString());
        }
#endif

        [Test]
        public void WriteRaw()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteRaw("fail");
            writer.WriteRaw("fail");
            writer.WriteEndArray();

            // this is a bug. write raw shouldn't be autocompleting like this
            // hard to fix without introducing Raw and RawValue token types
            // meh
            StringAssert.AreEqual(@"[
  fail,
  fail
]", writer.Token.ToString());
        }

        [Test]
        public void WriteRawValue()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteRawValue("fail");
            writer.WriteRawValue("fail");
            writer.WriteEndArray();

            StringAssert.AreEqual(@"[
  fail,
  fail
]", writer.Token.ToString());
        }

        [Test]
        public void DateTimeZoneHandling()
        {
            JTokenWriter writer = new JTokenWriter
            {
                DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
            };

            writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));

            JValue value = (JValue)writer.Token;
            DateTime dt = (DateTime)value.Value;

            Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
        }
    }
}


text:
@implementation RZCardSlideAnimationController

@synthesize isPositiveAnimation = _isPositiveAnimation;

- (id)init
{
    self = [super init];
    if (self)
    {
        _transitionTime = kRZSlideTransitionTime;
        _horizontalOrientation = TRUE;
        _containerBackgroundColor = [UIColor blackColor];
    }
    return self;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *container = [transitionContext containerView];

    UIView *bgView = [[UIView alloc] initWithFrame:container.bounds];
    bgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    bgView.backgroundColor = self.containerBackgroundColor;
    [container insertSubview:bgView atIndex:0];

    if (self.isPositiveAnimation)
    {
        [container insertSubview:toViewController.view belowSubview:fromViewController.view];
        toViewController.view.transform = CGAffineTransformMakeScale(1.0 - kRZSlideScaleChangePct, 1.0 - kRZSlideScaleChangePct);
        toViewController.view.alpha = 0.1f;

        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             toViewController.view.transform = CGAffineTransformIdentity;
                             toViewController.view.alpha = 1.0f;
                             if (self.horizontalOrientation)
                             {
                                 fromViewController.view.transform = CGAffineTransformMakeTranslation(-container.bounds.size.width, 0);
                             }
                             else
                             {
                                 fromViewController.view.transform = CGAffineTransformMakeTranslation(0, container.bounds.size.height);
                             }
                         }
                         completion:^(BOOL finished) {
                             toViewController.view.transform = CGAffineTransformIdentity;
                             fromViewController.view.transform = CGAffineTransformIdentity;
                             [bgView removeFromSuperview];
                             [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
                         }];
    }
    else
    {
        [container addSubview:toViewController.view];
        if (self.horizontalOrientation)
        {
            toViewController.view.transform = CGAffineTransformMakeTranslation(-container.bounds.size.width, 0);
        }
        else
        {
            toViewController.view.transform = CGAffineTransformMakeTranslation(0, container.bounds.size.height);
        }

        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             toViewController.view.transform = CGAffineTransformIdentity;
                             fromViewController.view.transform = CGAffineTransformMakeScale(1.0 - kRZSlideScaleChangePct, 1.0 - kRZSlideScaleChangePct);
                             fromViewController.view.alpha = 0.1f;
                         }
                         completion:^(BOOL finished) {
                             toViewController.view.transform = CGAffineTransformIdentity;
                             fromViewController.view.transform = CGAffineTransformIdentity;
                             fromViewController.view.alpha = 1.0f;
                             [bgView removeFromSuperview];
                             [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
                         }];
    }
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return self.transitionTime;
}

@end


text:
package org.apache.activemq.artemis.core.config.impl;

import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.core.config.FileDeploymentManager;
import org.apache.activemq.artemis.core.config.ha.LiveOnlyPolicyConfiguration;
import org.junit.Test;

import java.util.Collections;

import org.junit.Assert;

import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.journal.impl.JournalConstants;

public class DefaultsFileConfigurationTest extends ConfigurationImplTest {

   @Override
   @Test
   public void testDefaults() {

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), conf.getScheduledThreadPoolMaxSize());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultThreadPoolMaxSize(), conf.getThreadPoolMaxSize());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval(), conf.getSecurityInvalidationInterval());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultSecurityEnabled(), conf.isSecurityEnabled());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJmxManagementEnabled(), conf.isJMXManagementEnabled());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), conf.getJMXDomain());

      Assert.assertEquals(0, conf.getIncomingInterceptorClassNames().size());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultConnectionTtlOverride(), conf.getConnectionTTLOverride());

      Assert.assertEquals(0, conf.getAcceptorConfigurations().size());

      Assert.assertEquals(Collections.emptyMap(), conf.getConnectorConfigurations());

      Assert.assertEquals(Collections.emptyList(), conf.getBroadcastGroupConfigurations());

      Assert.assertEquals(Collections.emptyMap(), conf.getDiscoveryGroupConfigurations());

      Assert.assertEquals(Collections.emptyList(), conf.getBridgeConfigurations());

      Assert.assertEquals(Collections.emptyList(), conf.getDivertConfigurations());

      Assert.assertEquals(Collections.emptyList(), conf.getClusterConfigurations());

      Assert.assertEquals(Collections.emptyList(), conf.getQueueConfigurations());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementAddress(), conf.getManagementAddress());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress(), conf.getManagementNotificationAddress());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultClusterUser(), conf.getClusterUser());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultClusterPassword(), conf.getClusterPassword());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultIdCacheSize(), conf.getIDCacheSize());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultPersistIdCache(), conf.isPersistIDCache());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultBindingsDirectory(), conf.getBindingsDirectory());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalDir(), conf.getJournalDirectory());

      Assert.assertEquals(getDefaultJournalType(), conf.getJournalType());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncTransactional(), conf.isJournalSyncTransactional());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional(), conf.isJournalSyncNonTransactional());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), conf.getJournalFileSize());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles(), conf.getJournalCompactMinFiles());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage(), conf.getJournalCompactPercentage());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles(), conf.getJournalMinFiles());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio(), conf.getJournalMaxIO_AIO());

      Assert.assertEquals(JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, conf.getJournalBufferTimeout_AIO());

      Assert.assertEquals(JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, conf.getJournalBufferSize_AIO());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalMaxIoNio(), conf.getJournalMaxIO_NIO());

      Assert.assertEquals(JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, conf.getJournalBufferTimeout_NIO());

      Assert.assertEquals(JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, conf.getJournalBufferSize_NIO());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultCreateBindingsDir(), conf.isCreateBindingsDir());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultCreateJournalDir(), conf.isCreateJournalDir());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultPagingDir(), conf.getPagingDirectory());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultLargeMessagesDir(), conf.getLargeMessagesDirectory());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultWildcardRoutingEnabled(), conf.isWildcardRoutingEnabled());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeout(), conf.getTransactionTimeout());

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultMessageCounterEnabled(), conf.isMessageCounterEnabled());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod(), conf.getTransactionTimeoutScanPeriod());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryScanPeriod(), conf.getMessageExpiryScanPeriod());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(), conf.getMessageExpiryThreadPriority());

      Assert.assertTrue(conf.getHAPolicyConfiguration() instanceof LiveOnlyPolicyConfiguration);

      Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultGracefulShutdownEnabled(), conf.isGracefulShutdownEnabled());

      Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultGracefulShutdownTimeout(), conf.getGracefulShutdownTimeout());
   }

   // Protected ---------------------------------------------------------------------------------------------

   @Override
   protected Configuration createConfiguration() throws Exception {
      FileConfiguration fc = new FileConfiguration();
      FileDeploymentManager deploymentManager = new FileDeploymentManager("ConfigurationTest-defaults.xml");
      deploymentManager.addDeployable(fc);
      deploymentManager.readConfiguration();

      return fc;
   }
}


text:
require File.join(File.dirname(__FILE__), *%w[lib rorem])

module Rorem

  class << self

    alias_method_chain :init, :rails

    def init_with_rails
      init_without_rails
      require File.join(File.dirname(__FILE__), *%w[lib rorem active_record])
      require File.join(RAILS_ROOT, 'config', 'rorem')
    end

  end

end


text:
using System;
using System.Diagnostics.Contracts;
using DotNetRevolution.Core.Domain.CodeContract;

namespace DotNetRevolution.Core.Domain
{
    [ContractClass(typeof(DomainEventEntryRegistrationContract))]
    public interface IDomainEventEntryRegistration : IDisposable
    {
        IDomainEventEntry Entry { [Pure] get; }
    }
}


text:
export const points_vert = `
precision highp float;
precision highp int;

#include common
#include read_from_texture
#include common_vert_params
#include color_vert_params
#include size_vert_params
#include common_clip

uniform float uPixelRatio;
uniform vec4 uViewport;

attribute vec3 aPosition;
attribute mat4 aTransform;
attribute float aInstance;
attribute float aGroup;

void main(){
    #include assign_group
    #include assign_color_varying
    #include assign_marker_varying
    #include assign_clipping_varying
    #include assign_position
    #include assign_size

    #ifdef dPointSizeAttenuation
        gl_PointSize = size * uPixelRatio * ((uViewport.w / 2.0) / -mvPosition.z) * 5.0;
    #else
        gl_PointSize = size * uPixelRatio;
    #endif
    gl_PointSize = max(1.0, gl_PointSize);

    gl_Position = uProjection * mvPosition;

    #include clip_instance
}
`;


text:
@interface DuoJiSubViewController : UIViewController
@property (nonatomic,strong)NSArray *subDataArray;
@end


text:
<?php

namespace Vae\BaseBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FormationController extends controller {

    public function indexAction($_locale, $nomSite, $slugRubrique){

        //on va chercher dans la base de données
        $modelManager = $this->getDoctrine()->getManager();

        $rSite = $modelManager->getRepository('VaeMultiSiteBundle:Sites')->findOneByNom($nomSite);

        if(!$rSite){

            return $this->render('VaeBaseBundle:Erreurs:404.html.twig',
               array('langue' => $_locale));
        }

        if($_locale == 'fr'){

        $rRubrique = $modelManager->getRepository('VaeBaseBundle:Rubriques')->findOneBy(array('sites'=>$rSite->getId(),
                                                                                'slug'=>$slugRubrique));
        $rsFormation = $modelManager->getRepository('VaeBaseBundle:Formations')->findBy(array('rubriques'=>$rRubrique->getId()));

        }

        else{

        $rRubrique = $modelManager->getRepository('VaeBaseBundle:Rubriques')->findOneBy(array('sites'=>$rSite->getId(),
                                                                                'slugEn'=>$slugRubrique));
        $rsFormation = $modelManager->createQueryBuilder()
                                        ->select('f')
                                        ->from('VaeBaseBundle:Formations', 'f')
                                        ->where('f.rubriques = :Id')
                                        ->andWhere('f.slugEn IS NOT NULL')
                                        ->setParameter('Id', $rRubrique->getId())
                                        ->getQuery()
                                        ->getResult();
        }

        if(!$rRubrique){

            return $this->render('VaeBaseBundle:Erreurs:404.html.twig',
               array('langue' => $_locale));
        }

        if(!$rsFormation){

            return $this->render('VaeBaseBundle:Formation:aucune.html.twig',
                array('langue' => $_locale));
        }

        //on charge la vue et on lui envoi la liste des catégories

        return $this->render('VaeBaseBundle:Formation:liste.html.twig',
                array('formations' => $rsFormation,
                      'site' => $rSite,
                      'rubrique' => $rRubrique,
                      'langue' => $_locale));
    }

    public function detailAction($_locale, $nomSite, $slugRubrique, $slugFormation){

        //on va chercher dans la base de données
        $modelManager = $this->getDoctrine()->getManager();

        $rSite = $modelManager->getRepository('VaeMultiSiteBundle:Sites')->findOneByNom($nomSite);

        if(!$rSite){

            return $this->render('VaeBaseBundle:Erreurs:404.html.twig',
               array('langue' => $_locale));
        }

        if($_locale == 'fr'){

            $rRubrique = $modelManager->getRepository('VaeBaseBundle:Rubriques')->findOneBy(array('sites'=>$rSite->getId(),
                                                                                'slug'=>$slugRubrique));

            $rFormation = $modelManager->getRepository('VaeBaseBundle:Formations')->findOneBy(array('rubriques'=>$rRubrique->getId(),
                                                                                'slug'=>$slugFormation));
        }

        else{

            $rRubrique = $modelManager->getRepository('VaeBaseBundle:Rubriques')->findOneBy(array('sites'=>$rSite->getId(),
                                                                                'slugEn'=>$slugRubrique));

            $rFormation = $modelManager->getRepository('VaeBaseBundle:Formations')->findOneBy(array('rubriques'=>$rRubrique->getId(),
                                                                                'slugEn'=>$slugFormation));
        }

        if(!$rFormation){

            return $this->render('VaeBaseBundle:Erreurs:404.html.twig',
               array('langue' => $_locale));
        }

        $User = $this->get('security.context')->getToken()->getUser();

        $verifUser = $modelManager->getRepository('VaeInscriptionBundle:Inscriptions')->findOneBy(array('formations'=>$rFormation->getId(),
                                                                                'users'=>$User));

        $verifFormation = $modelManager->getRepository('VaeInscriptionBundle:Inscriptions')->findBy(array('formations'=>$rFormation->getId()));

        $nbInscrit = count($verifFormation);
        //var_dump($result);
        //die();

        //on charge la vue et on lui envoi la liste des catégories
        return $this->render('VaeBaseBundle:Formation:detail.html.twig',
                array('formation' => $rFormation,
                      'site' => $rSite,
                      'rubrique' => $rRubrique,
                      'langue' => $_locale,
                      'verifUser' => $verifUser,
                      'nbInscrit' => $nbInscrit));
    }

}

?>


text:
package org.apache.maven.plugin.version;

import java.util.List;

import org.apache.maven.model.Model;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;

/**
 * Collects settings required to resolve the version for a plugin.
 *
 * @since 3.0
 * @author Benjamin Bentmann
 */
public interface PluginVersionRequest
{

    /**
     * Gets the group id of the plugin.
     *
     * @return The group id of the plugin.
     */
    String getGroupId();

    /**
     * Sets the group id of the plugin.
     *
     * @param groupId The group id of the plugin.
     * @return This request, never {@code null}.
     */
    PluginVersionRequest setGroupId( String groupId );

    /**
     * Gets the artifact id of the plugin.
     *
     * @return The artifact id of the plugin.
     */
    String getArtifactId();

    /**
     * Sets the artifact id of the plugin.
     *
     * @param artifactId The artifact id of the plugin.
     * @return This request, never {@code null}.
     */
    PluginVersionRequest setArtifactId( String artifactId );

    /**
     * Gets the POM whose build plugins are to be scanned for the version.
     *
     * @return The POM whose build plugins are to be scanned for the verion or {@code null} to only search the plugin
     *         repositories.
     */
    Model getPom();

    /**
     * Sets the POM whose build plugins are to be scanned for the version.
     *
     * @param pom The POM whose build plugins are to be scanned for the version, may be {@code null} to only search the
     *            plugin repositories.
     * @return This request, never {@code null}.
     */
    PluginVersionRequest setPom( Model pom );

    /**
     * Gets the remote repositories to use.
     *
     * @return The remote repositories to use, never {@code null}.
     */
    List<RemoteRepository> getRepositories();

    /**
     * Sets the remote repositories to use. Note: When creating a request from a project, be sure to use the
     * plugin repositories and not the regular project repositories.
     *
     * @param repositories The remote repositories to use.
     * @return This request, never {@code null}.
     */
    PluginVersionRequest setRepositories( List<RemoteRepository> repositories );

    /**
     * Gets the session to use for repository access.
     *
     * @return The repository session or {@code null} if not set.
     */
    RepositorySystemSession getRepositorySession();

    /**
     * Sets the session to use for repository access.
     *
     * @param repositorySession The repository session to use.
     * @return This request, never {@code null}.
     */
    PluginVersionRequest setRepositorySession( RepositorySystemSession repositorySession );

}


text:
	    _{pageBg}
	    _{pageHeader}
	    _{adminNav}
	    _{pageBody}
	    _{pageFooter}

                _{bgColor}

                    文字颜色

菜单高度

请点击箭头调整菜单高度

                _{bgPic}

	                    _{selectPic}
	                     _{uploadPic}
	                    _{fillPicUrl}

                图片排列
                    <select name="background-repeat" id="background-repeat">
                    <option value="repeat-x" >横向</option>
                    <option value="repeat-y" >纵向</option>
                    <option value="repeat" >纵横</option>
                    <option value="no-repeat" >不平铺</option>
                    </select>

                    <select name="background-position" id="background-position" disabled="disabled">
                    <option value="" selected>默认</option>
                    <option value="top center" >上部中间</option>
                    <option value="top left" >上部左侧</option>
                    <option value="top right" >上部右侧</option>
                    <option value="center left" >中间左侧</option>
                    <option value="center center" >正中间</option>
                    <option value="center right" >中间右侧</option>
                    <option value="bottom left" >底部左侧</option>
                    <option value="bottom center" >底部中间</option>
                    <option value="bottom right" >底部右侧</option>
                    </select>

                <input id="chkDeleteBgPic" type="checkbox" /> 不使用背景图

#{autoSaveScript}


text:
package org.guvnor.ala.ui.client.provider;

import java.util.Collection;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.guvnor.ala.ui.client.events.AddNewRuntimeEvent;
import org.guvnor.ala.ui.client.events.ProviderSelectedEvent;
import org.guvnor.ala.ui.client.events.ProviderTypeSelectedEvent;
import org.guvnor.ala.ui.client.events.RefreshRuntimeEvent;
import org.guvnor.ala.ui.client.handler.ClientProviderHandler;
import org.guvnor.ala.ui.client.handler.ClientProviderHandlerRegistry;
import org.guvnor.ala.ui.client.handler.FormResolver;
import org.guvnor.ala.ui.client.handler.ProviderConfigurationForm;
import org.guvnor.ala.ui.client.provider.status.ProviderStatusPresenter;
import org.guvnor.ala.ui.client.provider.status.empty.ProviderStatusEmptyPresenter;
import org.guvnor.ala.ui.client.wizard.provider.empty.ProviderConfigEmptyPresenter;
import org.guvnor.ala.ui.events.PipelineExecutionChange;
import org.guvnor.ala.ui.events.PipelineExecutionChangeEvent;
import org.guvnor.ala.ui.events.RuntimeChange;
import org.guvnor.ala.ui.events.RuntimeChangeEvent;
import org.guvnor.ala.ui.model.PipelineExecutionTraceKey;
import org.guvnor.ala.ui.model.Provider;
import org.guvnor.ala.ui.model.ProviderConfiguration;
import org.guvnor.ala.ui.model.ProviderKey;
import org.guvnor.ala.ui.model.ProviderTypeKey;
import org.guvnor.ala.ui.model.RuntimeKey;
import org.guvnor.ala.ui.model.RuntimeListItem;
import org.guvnor.ala.ui.model.RuntimesInfo;
import org.guvnor.ala.ui.service.ProviderService;
import org.guvnor.ala.ui.service.ProvisioningScreensService;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.IsElement;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.mocks.CallerMock;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;
import org.uberfire.workbench.events.NotificationEvent;

import static org.guvnor.ala.ui.ProvisioningManagementTestCommons.ERROR_MESSAGE;
import static org.guvnor.ala.ui.ProvisioningManagementTestCommons.SUCCESS_MESSAGE;
import static org.guvnor.ala.ui.ProvisioningManagementTestCommons.mockProviderKey;
import static org.guvnor.ala.ui.ProvisioningManagementTestCommons.mockProviderTypeKey;
import static org.guvnor.ala.ui.ProvisioningManagementTestCommons.prepareServiceCallerError;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class ProviderPresenterTest {

    @Mock
    private ProviderPresenter.View view;

    @Mock
    private ProviderService providerService;

    private Caller<ProviderService> providerServiceCaller;

    @Mock
    private ProvisioningScreensService provisioningScreensService;

    private Caller<ProvisioningScreensService> provisioningScreensServiceCaller;

    @Mock
    private ProviderStatusEmptyPresenter providerStatusEmptyPresenter;

    @Mock
    private ProviderStatusEmptyPresenter.View providerStatusEmptyPresenterView;

    @Mock
    private ProviderStatusPresenter providerStatusPresenter;

    @Mock
    private ProviderStatusPresenter.View providerStatusPresenterView;

    @Mock
    private ProviderConfigEmptyPresenter providerConfigEmptyPresenter;

    @Mock
    private ClientProviderHandlerRegistry handlerRegistry;

    @Mock
    private ClientProviderHandler handler;

    @Mock
    private EventSourceMock<ProviderTypeSelectedEvent> providerTypeSelectedEvent;

    @Mock
    private EventSourceMock<NotificationEvent> notification;

    @Mock
    private EventSourceMock<AddNewRuntimeEvent> addNewRuntimeEvent;

    @Mock
    private FormResolver formResolver;

    @Mock
    private ProviderConfigurationForm configurationForm;

    @Mock
    private IsElement configurationFormView;

    private ProviderPresenter presenter;

    private Provider provider;

    private ProviderKey providerKey;

    private RuntimesInfo runtimesInfo;

    @SuppressWarnings("unchecked")
    private Collection<RuntimeListItem> runtimeItems = mock(Collection.class);

    @Before
    public void setUp() {

        when(providerStatusPresenter.getView()).thenReturn(providerStatusPresenterView);
        when(providerStatusEmptyPresenter.getView()).thenReturn(providerStatusEmptyPresenterView);

        providerServiceCaller = spy(new CallerMock<>(providerService));
        provisioningScreensServiceCaller = spy(new CallerMock<>(provisioningScreensService));
        presenter = spy(new ProviderPresenter(view,
                                              providerServiceCaller,
                                              provisioningScreensServiceCaller,
                                              providerStatusEmptyPresenter,
                                              providerStatusPresenter,
                                              providerConfigEmptyPresenter,
                                              handlerRegistry,
                                              notification,
                                              providerTypeSelectedEvent,
                                              addNewRuntimeEvent));
        presenter.init();
        verify(view,
               times(1)).init(presenter);
    }

    @Test
    public void testOnProviderSelectedWithRuntimes() {

        prepareRuntimesInfo();

        //emulate that there are runtimes.
        when(runtimeItems.isEmpty()).thenReturn(false);

        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        //the ui must have been loaded with the items.
        verifyUILoadedWithItems(1);

        //common verifications.
        verifyRuntimesInfoLoaded(1);
    }

    @Test
    public void testOnProviderSelectedWithNoRuntimes() {

        prepareRuntimesInfo();

        //emulate that there are no runtimes.
        when(runtimeItems.isEmpty()).thenReturn(true);

        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        verifyUILoadedWithNoItems(1);

        //common verifications.
        verifyRuntimesInfoLoaded(1);
    }

    @Test
    public void testOnRefreshRuntimesWithItems() {
        //emulate that the provider was already loaded.
        prepareRefreshWithItems();

        //emulate the refresh action in a later time.
        presenter.onRefreshRuntime(new RefreshRuntimeEvent(providerKey));

        //the ui must have been loaded with the items twice, the initial loading + the refresh
        verify(providerStatusPresenter,
               times(2)).setupItems(runtimeItems);
        verify(view,
               times(2)).setStatus(providerStatusPresenterView);

        //common verifications.
        verifyRuntimesInfoLoaded(2);
    }

    @Test
    public void testOnRefreshRuntimesWithNoItems() {
        //emulate that the provider was already loaded.
        prepareRefreshWithNoItems();

        //emulate the refresh action in a later time.
        presenter.onRefreshRuntime(new RefreshRuntimeEvent(providerKey));

        //the ui must have been loaded with the items twice, the initial loading + the refresh
        //the empty status must have been set twice.
        verifyUILoadedWithNoItems(2);

        //common verifications.
        verifyRuntimesInfoLoaded(2);
    }

    @Test
    public void testRefreshWithItems() {
        //emulate that the provider was already loaded.
        prepareRefreshWithItems();

        //emulate the refresh action in a later time.
        presenter.refresh();

        //the ui must have been loaded with the items twice, the initial loading + the refresh
        verify(providerStatusPresenter,
               times(2)).setupItems(runtimeItems);
        verify(view,
               times(2)).setStatus(providerStatusPresenterView);

        //common verifications.
        verifyRuntimesInfoLoaded(2);
    }

    @Test
    public void testRefreshWithNoItems() {
        //emulate that the provider was already loaded.
        prepareRefreshWithNoItems();

        //emulate the refresh action in a later time.
        presenter.refresh();

        //the ui must have been loaded with the items twice, the initial loading + the refresh
        //the empty status must have been set twice.
        verifyUILoadedWithNoItems(2);

        //common verifications.
        verifyRuntimesInfoLoaded(2);
    }

    @Test
    public void testOnRemoveProviderWithRuntimes() {
        //emulate that the provider was previously loaded.
        prepareRuntimesInfo();
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        when(provisioningScreensService.hasRuntimes(providerKey)).thenReturn(true);
        presenter.onRemoveProvider();

        verify(view,
               times(1)).showProviderCantBeDeleted();
    }

    @Test
    public void testOnRemoveProviderWithNoRuntimesSuccessful() {
        //emulate that the provider was previously loaded.
        prepareRuntimesInfo();
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        when(provisioningScreensService.hasRuntimes(providerKey)).thenReturn(false);
        presenter.onRemoveProvider();

        verify(view,
               never()).showProviderCantBeDeleted();
        verify(view,
               times(1)).confirmRemove(any(Command.class));
    }

    @Test
    public void testRemoveProviderSuccessFull() {
        testRemoveProvider(false);
    }

    @Test
    public void testRemoveProviderWithError() {
        testRemoveProvider(true);
    }

    private void testRemoveProvider(boolean withErrors) {
        //emulate that the provider was previously loaded.
        prepareRuntimesInfo();
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        when(view.getRemoveProviderSuccessMessage()).thenReturn(SUCCESS_MESSAGE);
        when(view.getRemoveProviderErrorMessage()).thenReturn(ERROR_MESSAGE);

        if (withErrors) {
            //make the providerService fail.
            prepareServiceCallerError(providerService,
                                      providerServiceCaller);
        }

        //the user confirms the delete operation at a later time from the ui.
        presenter.removeProvider();

        verify(providerService,
               times(1)).deleteProvider(providerKey);
        verify(providerTypeSelectedEvent,
               times(1)).fire(new ProviderTypeSelectedEvent(providerKey.getProviderTypeKey()));

        if (withErrors) {
            verify(notification,
                   times(1)).fire(new NotificationEvent(ERROR_MESSAGE,
                                                        NotificationEvent.NotificationType.ERROR));
        } else {
            verify(notification,
                   times(1)).fire(new NotificationEvent(SUCCESS_MESSAGE,
                                                        NotificationEvent.NotificationType.SUCCESS));
        }
    }

    @Test
    public void testDeploy() {
        //emulate that the provider was previously loaded.
        prepareRuntimesInfo();
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        //emulate the user adding a new deploy.
        presenter.deploy();

        verify(addNewRuntimeEvent,
               times(1)).fire(new AddNewRuntimeEvent(provider));
    }

    @Test
    public void testOnRuntimeDeleted() {
        //load the presenter.
        prepareRuntimesInfo();
        when(runtimeItems.isEmpty()).thenReturn(true);
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        RuntimeKey runtimeKey = mock(RuntimeKey.class);
        when(runtimeKey.getProviderKey()).thenReturn(providerKey);
        when(providerStatusPresenter.removeItem(runtimeKey)).thenReturn(true);
        //the provider status presenter is not empty after the removal.
        when(providerStatusPresenter.isEmpty()).thenReturn(false);

        presenter.onRuntimeChange(new RuntimeChangeEvent(RuntimeChange.DELETED,
                                                         runtimeKey));
        verify(providerStatusPresenter,
               times(1)).removeItem(runtimeKey);
    }

    @Test
    public void testOnRuntimeDeletedRefreshRequired() {
        //load the presenter.
        prepareRuntimesInfo();
        when(runtimeItems.isEmpty()).thenReturn(true);
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        RuntimeKey runtimeKey = mock(RuntimeKey.class);
        when(runtimeKey.getProviderKey()).thenReturn(providerKey);
        when(providerStatusPresenter.removeItem(runtimeKey)).thenReturn(true);
        //the provider status presenter is empty after the removal.
        when(providerStatusPresenter.isEmpty()).thenReturn(true);

        presenter.onRuntimeChange(new RuntimeChangeEvent(RuntimeChange.DELETED,
                                                         runtimeKey));
        verify(providerStatusPresenter,
               times(1)).removeItem(runtimeKey);
        verify(presenter,
               times(1)).refresh();
    }

    @Test
    public void testPipelineExecutionDeleted() {
        //load the presenter.
        prepareRuntimesInfo();
        when(runtimeItems.isEmpty()).thenReturn(true);
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        PipelineExecutionTraceKey pipelineExecutionTraceKey = mock(PipelineExecutionTraceKey.class);
        when(providerStatusPresenter.removeItem(pipelineExecutionTraceKey)).thenReturn(true);
        //the provider status presenter is not empty after the removal.
        when(providerStatusPresenter.isEmpty()).thenReturn(false);

        presenter.onPipelineExecutionChange(new PipelineExecutionChangeEvent(PipelineExecutionChange.DELETED,
                                                                             pipelineExecutionTraceKey));
        verify(providerStatusPresenter,
               times(1)).removeItem(pipelineExecutionTraceKey);
    }

    @Test
    public void testPipelineExecutionDeletedRefreshRequired() {
        //load the presenter.
        prepareRuntimesInfo();
        when(runtimeItems.isEmpty()).thenReturn(true);
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));

        PipelineExecutionTraceKey pipelineExecutionTraceKey = mock(PipelineExecutionTraceKey.class);
        when(providerStatusPresenter.removeItem(pipelineExecutionTraceKey)).thenReturn(true);
        //the status presenter is empty after the removal.
        when(providerStatusPresenter.isEmpty()).thenReturn(true);

        presenter.onPipelineExecutionChange(new PipelineExecutionChangeEvent(PipelineExecutionChange.DELETED,
                                                                             pipelineExecutionTraceKey));
        verify(providerStatusPresenter,
               times(1)).removeItem(pipelineExecutionTraceKey);
        verify(presenter,
               times(1)).refresh();
    }

    private void prepareRuntimesInfo() {
        ProviderTypeKey providerTypeKey = mockProviderTypeKey("1");
        providerKey = mockProviderKey(providerTypeKey,
                                      "1");
        ProviderConfiguration configuration = mock(ProviderConfiguration.class);
        provider = new Provider(providerKey,
                                configuration);
        runtimesInfo = mock(RuntimesInfo.class);
        when(runtimesInfo.getProvider()).thenReturn(provider);
        when(runtimesInfo.getRuntimeItems()).thenReturn(runtimeItems);
        when(providerService.getProvider(providerKey)).thenReturn(provider);
        when(provisioningScreensService.getRuntimesInfo(providerKey)).thenReturn(runtimesInfo);

        when(handlerRegistry.isProviderInstalled(providerTypeKey)).thenReturn(true);
        when(handlerRegistry.getProviderHandler(providerTypeKey)).thenReturn(handler);
        when(handler.getFormResolver()).thenReturn(formResolver);
        when(formResolver.newProviderConfigurationForm()).thenReturn(configurationForm);
        when(configurationForm.getView()).thenReturn(configurationFormView);
    }

    private void verifyRuntimesInfoLoaded(int currentTimes) {
        verify(provisioningScreensService,
               times(currentTimes)).getRuntimesInfo(providerKey);

        verify(providerStatusPresenter,
               times(currentTimes)).clear();

        verify(view,
               times(currentTimes)).setProviderName(provider.getKey().getId());

        verify(handlerRegistry,
               times(currentTimes)).getProviderHandler(providerKey.getProviderTypeKey());
        verify(handler,
               times(currentTimes)).getFormResolver();
        verify(formResolver,
               times(currentTimes)).newProviderConfigurationForm();
        verify(configurationForm,
               times(currentTimes)).load(provider);
        verify(configurationForm,
               times(currentTimes)).disable();
        verify(view,
               times(currentTimes)).setConfig(configurationForm.getView());
    }

    private void verifyUILoadedWithItems(int currentTimes) {
        //the ui must have been loaded with the items.
        verify(providerStatusPresenter,
               times(currentTimes)).setupItems(runtimeItems);
        verify(view,
               times(currentTimes)).setStatus(providerStatusPresenterView);
    }

    private void verifyUILoadedWithNoItems(int currentItems) {
        //the empty status must have been set.
        verify(providerStatusEmptyPresenter,
               times(currentItems)).setup(providerKey);
        verify(view,
               times(currentItems)).setStatus(providerStatusEmptyPresenterView);
    }

    /**
     * Prepares the refresh action. The refresh action only takes place if the provider has been loaded first.
     */
    private void prepareRefreshWithItems() {
        prepareRuntimesInfo();

        //emulate that there are runtimes.
        when(runtimeItems.isEmpty()).thenReturn(false);

        //emulate that the presenter was initially loaded. If not the refresh button is not available.
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));
    }

    /**
     * Prepares the refresh action. The refresh action only takes place if the provider has been loaded first.
     */
    private void prepareRefreshWithNoItems() {
        prepareRuntimesInfo();

        //emulate that there are no runtimes.
        when(runtimeItems.isEmpty()).thenReturn(true);

        //emulate that the presenter was initially loaded. If not the refresh button is not available.
        presenter.onProviderSelected(new ProviderSelectedEvent(providerKey));
    }
}


text:
require 'spec_helper'

provider = Puppet::Type.type(:package).provider(:yum)

describe provider do
  before do
    # Create a mock resource
     @resource = stub 'resource'
     @resource.stubs(:[]).with(:name).returns 'mypackage'
     @provider = provider.new(@resource)
     @provider.stubs(:resource).returns @resource
     @provider.stubs(:yum).returns 'yum'
     @provider.stubs(:rpm).returns 'rpm'
     @provider.stubs(:get).with(:name).returns 'mypackage'
     @provider.stubs(:get).with(:version).returns '1'
     @provider.stubs(:get).with(:release).returns '1'
     @provider.stubs(:get).with(:arch).returns 'i386'
  end
  # provider should repond to the following methods
   [:install, :latest, :update, :purge].each do |method|
     it "should have a(n) #{method}" do
       @provider.should respond_to(method)
    end
  end

  describe 'when installing' do
    before(:each) do
      Puppet::Util.stubs(:which).with("rpm").returns("/bin/rpm")
      provider.stubs(:which).with("rpm").returns("/bin/rpm")
      Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).returns("4.10.1\n").at_most_once
    end

    it 'should call yum install for :installed' do
      @resource.stubs(:should).with(:ensure).returns :installed
      @provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :install, 'mypackage')
      @provider.install
    end

    it 'should use :install to update' do
      @provider.expects(:install)
      @provider.update
    end

    it 'should be able to set version' do
      @resource.stubs(:should).with(:ensure).returns '1.2'
      @provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :install, 'mypackage-1.2')
      @provider.stubs(:query).returns :ensure => '1.2'
      @provider.install
    end

    it 'should be able to downgrade' do
      @resource.stubs(:should).with(:ensure).returns '1.0'
      @provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :downgrade, 'mypackage-1.0')
      @provider.stubs(:query).returns(:ensure => '1.2').then.returns(:ensure => '1.0')
      @provider.install
    end
  end

  describe 'when uninstalling' do
    it 'should use erase to purge' do
      @provider.expects(:yum).with('-y', :erase, 'mypackage')
      @provider.purge
    end
  end

  it 'should be versionable' do
    provider.should be_versionable
  end

  describe '#latest' do
    describe 'when latest_info is nil' do
      before :each do
        @provider.stubs(:latest_info).returns(nil)
      end

      it 'raises if ensure is absent and latest_info is nil' do
        @provider.stubs(:properties).returns({:ensure => :absent})

        expect { @provider.latest }.to raise_error(
          Puppet::DevError,
          'Tried to get latest on a missing package'
        )
      end

      it 'returns the ensure value if the package is not already installed' do
        @provider.stubs(:properties).returns({:ensure => '3.4.5'})

        @provider.latest.should == '3.4.5'
      end
    end

    describe 'when latest_info is populated' do
      before :each do
        @provider.stubs(:latest_info).returns({
          :name     => 'mypackage',
          :epoch    => '1',
          :version  => '2.3.4',
          :release  => '5',
          :arch     => 'i686',
          :provider => :yum,
          :ensure   => '2.3.4-5'
        })
      end

      it 'includes the epoch in the version string' do
        @provider.latest.should == '1:2.3.4-5'
      end
    end
  end

  describe 'prefetching' do
    let(:nevra_format) { Puppet::Type::Package::ProviderRpm::NEVRA_FORMAT }

    let(:packages) do
      <<-RPM_OUTPUT
      cracklib-dicts 0 2.8.9 3.3 x86_64 :DESC: The standard CrackLib dictionaries
      basesystem 0 8.0 5.1.1.el5.centos noarch :DESC: The skeleton package which defines a simple Red Hat Enterprise Linux system
      chkconfig 0 1.3.30.2 2.el5 x86_64 :DESC: A system tool for maintaining the /etc/rc*.d hierarchy
      myresource 0 1.2.3.4 5.el4 noarch :DESC: Now with summary
      mysummaryless 0 1.2.3.4 5.el4 noarch :DESC:
      RPM_OUTPUT
    end

    let(:yumhelper_output) do
      <<-YUMHELPER_OUTPUT
 * base: centos.tcpdiag.net
 * extras: centos.mirrors.hoobly.com
 * updates: mirrors.arsc.edu
_pkg nss-tools 0 3.14.3 4.el6_4 x86_64
_pkg pixman 0 0.26.2 5.el6_4 x86_64
_pkg myresource 0 1.2.3.4 5.el4 noarch
_pkg mysummaryless 0 1.2.3.4 5.el4 noarch
     YUMHELPER_OUTPUT
    end

    let(:execute_options) do
      {:failonfail => true, :combine => true, :custom_environment => {}}
    end

    let(:rpm_version) { "RPM version 4.8.0\n" }

    let(:package_type) { Puppet::Type.type(:package) }
    let(:yum_provider) { provider }

    def pretend_we_are_root_for_yum_provider
      Process.stubs(:euid).returns(0)
    end

    def expect_yum_provider_to_provide_rpm
      Puppet::Type::Package::ProviderYum.stubs(:rpm).with('--version').returns(rpm_version)
      Puppet::Type::Package::ProviderYum.expects(:command).with(:rpm).returns("/bin/rpm")
    end

    def expect_execpipe_to_provide_package_info_for_an_rpm_query
      Puppet::Util::Execution.expects(:execpipe).with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}'").yields(packages)
    end

    def expect_python_yumhelper_call_to_return_latest_info
      Puppet::Type::Package::ProviderYum.expects(:python).with(regexp_matches(/yumhelper.py$/)).returns(yumhelper_output)
    end

    def a_package_type_instance_with_yum_provider_and_ensure_latest(name)
      type_instance = package_type.new(:name => name)
      type_instance.provider = yum_provider.new
      type_instance[:ensure] = :latest
      return type_instance
    end

    before do
      pretend_we_are_root_for_yum_provider
      expect_yum_provider_to_provide_rpm
      expect_execpipe_to_provide_package_info_for_an_rpm_query
      expect_python_yumhelper_call_to_return_latest_info
    end

    it "injects latest provider info into passed resources when prefetching" do
      myresource = a_package_type_instance_with_yum_provider_and_ensure_latest('myresource')
      mysummaryless = a_package_type_instance_with_yum_provider_and_ensure_latest('mysummaryless')

      yum_provider.prefetch({ "myresource" => myresource, "mysummaryless" => mysummaryless })

      expect(@logs.map(&:message).grep(/^Failed to match rpm line/)).to be_empty
      expect(myresource.provider.latest_info).to eq({
        :name=>"myresource",
        :epoch=>"0",
        :version=>"1.2.3.4",
        :release=>"5.el4",
        :arch=>"noarch",
        :provider=>:yum,
        :ensure=>"1.2.3.4-5.el4"
      })
    end
  end

  describe "with transactional rollback support" do
    let(:yum_options) { %w(-d 0 -e 0 -y) }
    let(:file_dir) { '/var/lib/puppet/rollback' }
    let(:rollback_file_down) { '/var/lib/puppet/rollback/mypackage_2.0_1.0.yaml' }
    let(:rollback_file_up) { '/var/lib/puppet/rollback/mypackage_1.0_2.0.yaml' }

    let(:before) do
      {
        'otherpkg' => '1',
        'asdf' => '1.0',
        'asdf-lib' => '1.0',
        'asdf-old-dep' => '1',
      }
    end

    let (:after) do
      {
        'otherpkg' => '1',
        'asdf' => '2.0',
        'asdf-lib' => '2.0',
        'asdf-new-dep' => '1',
      }
    end

    let (:diff) do
      {
        'installed' => {
            'asdf' => '2.0',
            'asdf-lib' => '2.0',
            'asdf-new-dep' => '1'
        },
        'removed' => {
            'asdf' => '1.0',
            'asdf-lib' => '1.0',
            'asdf-old-dep' => '1'
        }
      }
    end

    after(:each) do
      @provider.properties
      @provider.install
    end

    before(:each) do
      File.stubs(:directory?).with(file_dir).returns true
    end

    describe "when updating" do
      before(:each) {
        @provider.stubs(:read_diff).returns nil
      }

      it "saves diff only when version is changing and there is no rollback file" do
        @resource.stubs(:should).with(:ensure).returns '2.0'
        @provider.stubs(:query).returns(:ensure => '1.0')
        @provider.stubs(:check_query).returns(:ensure => '2.0')
        @provider.stubs(:yum_with_changes).with(yum_options, :install, 'mypackage-2.0')
        @provider.stubs(:make_package_diff).times(1)
        @provider.stubs(:save_diff).times(1)
      end

      it "doesn't save diff when package is being installed the first time" do
        @resource.stubs(:should).with(:ensure).returns :present
        @provider.stubs(:query).returns(:ensure => :absent)
        @provider.stubs(:yum).with(*yum_options, :install, 'mypackage')
        @provider.stubs(:save_diff).times(0)
      end

      it "saves correct diff to the rollback file" do
        @resource.stubs(:should).with(:ensure).returns '2.0'
        @provider.stubs(:query).returns(:ensure => '1.0')
        @provider.stubs(:check_query).returns(:ensure => '2.0')
        @provider.stubs(:yum_with_changes).with(yum_options, :install, 'mypackage-2.0').returns([before, after])
        @provider.stubs(:save_diff).with(rollback_file_up, diff)
      end
    end

    describe "when rolling back" do
      it 'only when rollback file is found' do
        @resource.stubs(:should).with(:ensure).returns '1.0'
        @provider.stubs(:query).returns(:ensure => '2.0')
        @provider.stubs(:check_query).returns(:ensure => '1.0')
        @provider.stubs(:read_diff).with(rollback_file_up).returns nil
        @provider.stubs(:yum).with(*yum_options, :downgrade, 'mypackage-1.0')
        @provider.stubs(:save_diff).times(1)
      end

      it "calls apt-get with correct package list" do
        @resource.stubs(:should).with(:ensure).returns '1.0'
        @provider.stubs(:query).returns(:ensure => '2.0')
        @provider.stubs(:check_query).returns(:ensure => '1.0')
        @provider.stubs(:read_diff).with(rollback_file_up).returns diff
        @provider.stubs(:yum_shell).times(1)
        @provider.stubs(:save_diff).times(0)
      end
    end

  end

end


text:
<?php

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class InvoiceItem extends AbstractHelper
{

	public function __invoke()
    {
       return 'InvoiceItem aus ApplicationModule';
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>T-Index</title>
<meta name="date" content="2015-10-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

C D E F G I L M P Q R S T U W

T

terrier - package terrier

TestCHVExpansion - Class in tests

A simple class to test CHV expansion.

TestCHVExpansion() - Constructor for class tests.TestCHVExpansion

tests - package tests

toString() - Method in class dataStructures.WordStatistics

tuneMu(double) - Method in class terrier.ModifiedTerrier

Automatically set DJM's mu parameter using the Tunner class.

tuneMu(double, double) - Method in class terrier.Tunner

Tunes the mu parameter, used on Dirichlet or DJM Language Model based on the
 corpus.

Tunner - Class in terrier

This class determined the best mu for the collection using the formulas described
 on the reference paper.

Tunner(Index) - Constructor for class terrier.Tunner

Creates a Tunner object, which is able to fit mu and lambda according to
 C.

TwoSidedHash - Class in dataStructures

A class that wraps a standard HashMap<String, Integer>, but after invertDictionary is
 invoked, the table is updated on the form HashMap<Integer, String>.

TwoSidedHash() - Constructor for class dataStructures.TwoSidedHash

C D E F G I L M P Q R S T U W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using System;
using UnityEngine;
using VRStandardAssets.Common;
using Random = UnityEngine.Random;

namespace VRStandardAssets.Flyer
{
    // This class controls each asteroid in the flyer scene.
    public class Asteroid : MonoBehaviour
    {
        public event Action<Asteroid> OnAsteroidRemovalDistance;    // This event is triggered when it is far enough behind the camera to be removed.
        public event Action<Asteroid> OnAsteroidHit;                // This event is triggered when the asteroid is hit either the ship or a laser.

        [SerializeField] private float m_AsteroidMinSize = 10f;     // The minimum amount an asteroid can be scaled up.
        [SerializeField] private float m_AsteroidMaxSize = 20f;     // The maximum amount an asteroid can be scaled up.
        [SerializeField] private float m_MinSpeed = 0f;             // The minimum speed the asteroid will move towards the camera.
        [SerializeField] private float m_MaxSpeed = 10f;            // The maximum speed the asteroid will move towards the camera.
        [SerializeField] private float m_MinRotationSpeed = 100f;   // The minimum speed the asteroid will rotate at.
        [SerializeField] private float m_MaxRotationSpeed = 140f;   // The maximum speed the asteroid will rotate at.
        [SerializeField] private int m_PlayerDamage = 20;           // The amount of damage the asteroid will do to the ship if it hits.
        [SerializeField] private int m_Score = 10;                  // The amount added to the score when the asteroid hits either the ship or a laser.

        private Rigidbody m_RigidBody;                              // Reference to the asteroid's rigidbody, used to move and rotate it.
        private FlyerHealthController m_FlyerHealthController;      // Reference to the flyer's health script, used to damage it.
        private GameObject m_Flyer;                                 // Reference to the flyer itself, used to determine what was hit.
        private Transform m_Cam;                                    // Reference to the camera so this can be destroyed when it's behind the camera.
        private float m_Speed;                                      // How fast asteroid will move towards the camera.
        private Vector3 m_RotationAxis;                             // The axis around which the asteroid will rotate.
        private float m_RotationSpeed;                              // How fast the asteroid will rotate.

        private const float k_RemovalDistance = 50f;                // How far behind the camera the asteroid must be before it is removed.

        public int Score { get { return m_Score; } }

        private void Awake ()
        {
            m_RigidBody = GetComponent<Rigidbody>();

            m_FlyerHealthController = FindObjectOfType<FlyerHealthController>();
            m_Flyer = m_FlyerHealthController.gameObject;

            m_Cam = Camera.main.transform;
        }

        private void Start()
        {
            // Set a random scale for the asteroid.
            float scaleMultiplier = Random.Range(m_AsteroidMinSize, m_AsteroidMaxSize);
            transform.localScale = new Vector3(scaleMultiplier, scaleMultiplier, scaleMultiplier);

            // Set a random rotation for the asteroid.
            transform.rotation = Random.rotation;

            // Set a random speed for the asteroid.
            m_Speed = Random.Range(m_MinSpeed, m_MaxSpeed);

            // Setup a random spin for the asteroid.
            m_RotationAxis = Random.insideUnitSphere;
            m_RotationSpeed = Random.Range (m_MinRotationSpeed, m_MaxRotationSpeed);
        }

        private void Update()
        {
            // Move and rotate the asteroid given the previously set up parameters.
            m_RigidBody.MoveRotation (m_RigidBody.rotation * Quaternion.AngleAxis (m_RotationSpeed * Time.deltaTime, m_RotationAxis));
            m_RigidBody.MovePosition (m_RigidBody.position - Vector3.forward * m_Speed * Time.deltaTime);

            // If the asteroid is far enough behind the camera and something has subscribed to OnAsteroidRemovalDistance call it.
            if (transform.position.z < m_Cam.position.z - k_RemovalDistance)
                if (OnAsteroidRemovalDistance != null)
                    OnAsteroidRemovalDistance(this);
        }

        private void OnTriggerEnter(Collider other)
        {
            // Only continue if the asteroid has hit the flyer.
            if (other.gameObject != m_Flyer)
                return;

            // Damage the flyer.
            m_FlyerHealthController.TakeDamage(m_PlayerDamage);

            // If the damage didn't kill the flyer add to the score and call the appropriate events.
            if (!m_FlyerHealthController.IsDead)
                Hit();
        }

        private void OnDestroy()
        {
            // Ensure the events are completely unsubscribed when the asteroid is destroyed.
            OnAsteroidRemovalDistance = null;
            OnAsteroidHit = null;
        }

        public void Hit()
        {
            // Add to the score.
            SessionData.AddScore(m_Score);

            // If OnAsteroidHit has any subscribers call it.
            if (OnAsteroidHit != null)
                OnAsteroidHit(this);
        }
    }
}


text:
'use strict';

/**
 * A {@link Path} is a {@link Fabric}-native link to a {@link Document}
 * within the network.
 */
class Path extends String {
  /**
   * Create a new {@link Path}.
   * @param {String|Object} input Named path.
   */
  constructor (input = {}) {
    super(input);

    if (typeof input === 'string') input = { input };

    this.settings = Object.assign({
      input: '/'
    }, settings);

    return this;
  }

  /**
   * @returns {Boolean} Whether or not the Path is valid.
   */
  isValid () {
    return (
      this.id.length === 32
    ) ? true : false;
  }
}

module.exports = Path;


text:
set -ve

uname -a
${TRAVIS_COMPILER} --version

make
make -C test


text:
/*jslint node: true */
/*global module, require*/
'use strict';

var util = require('util');

module.exports = function TimeoutError(message, details) {
  Error.captureStackTrace(this, this.constructor);
  this.code = 408;
  this.name = this.constructor.name;
  this.message = message;
  this.details = details;
};

util.inherits(module.exports, Error);