text:
const { expect } = require('chai');

const { log, setup } = require('./helpers/setup')
const ping = require('./helpers/fakePing')
const FakeServiceManager = require('./helpers/fakeServiceManager')

const delayForDuration = require('../helpers/delayForDuration')
const { getDevice } = require('../helpers/getDevice')

const { Switch } = require('../accessories')

const data = {
  on: 'ON',
  off: 'OFF'
}

// TODO: Check cancellation of timeouts

describe('switchAccessory', () => {

  // Switch Turn On
  it('turns on', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address
    }

    const switchAccessory = new Switch(null, config, 'FakeServiceManager')
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)

    expect(switchAccessory.state.switchState).to.equal(true);

    // Check hex code was sent
    const hasSentCode = device.hasSentCode('ON');
    expect(hasSentCode).to.equal(true);

    // Check that only one code has been sent
    const sentHexCodeCount = device.getSentHexCodeCount();
    expect(sentHexCodeCount).to.equal(1);
  });

  // Switch Turn On then Off
  it('turns off', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address
    }

    const switchAccessory = new Switch(null, config, 'FakeServiceManager')

    // Turn On Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Turn Off Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, false)
    expect(switchAccessory.state.switchState).to.equal(false);

    // Check hex code was sent
    const hasSentCodes = device.hasSentCodes([ 'ON', 'OFF' ]);
    expect(hasSentCodes).to.equal(true);

    // Check that only one code has been sent
    const sentHexCodeCount = device.getSentHexCodeCount();
    expect(sentHexCodeCount).to.equal(2);
  });

  // Auto Off
  it('"enableAutoOff": true, "onDuration": 1', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      enableAutoOff: true,
      onDuration: 1
    }

    const switchAccessory = new Switch(null, config, 'FakeServiceManager')

    // Turn On Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    await delayForDuration(0.4)
    // Expecting on after 0.4s total
    expect(switchAccessory.state.switchState).to.equal(true);

    await delayForDuration(0.7)
    // Expecting off after 1.1s total
    expect(switchAccessory.state.switchState).to.equal(false);
  }).timeout(4000);

  // Auto On
  it('"enableAutoOn": true, "offDuration": 1', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      enableAutoOn: true,
      offDuration: 1
    }

    const switchAccessory = new Switch(null, config, 'FakeServiceManager')

    // Turn On Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Turn Off Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, false)
    expect(switchAccessory.state.switchState).to.equal(false);

    await delayForDuration(0.4)
    // Expecting off after 0.4s total
    expect(switchAccessory.state.switchState).to.equal(false);

    await delayForDuration(0.7)
    // Expecting on after 1.1s total
    expect(switchAccessory.state.switchState).to.equal(true);
  }).timeout(4000);

  // Persist State
  it('"persistState": true', async () => {
    const { device } = setup();

    const config = {
      data,
      host: device.host.address,
      name: 'Unit Test Switch',
      persistState: true
    }

    let switchAccessory

    // Turn On Switch
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Should still be on when loading within a new instance
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(true);

    // Turn Off Switch
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, false)
    expect(switchAccessory.state.switchState).to.equal(false);

    // Should still be off when loading within a new instance
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(false);
  });

  it('"persistState": false', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      name: 'Unit Test Switch'
    }

    let switchAccessory

    // Turn On Switch
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Should be off again with a new instance
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(undefined);
  });

  // IP Address used to for state
  it('"pingIPAddress": "192.168.1.1", host up', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      pingIPAddress: '192.168.1.1',
      isUnitTest: true
    }

    let switchAccessory = new Switch(null, config, 'FakeServiceManager')
    const pingInterval = switchAccessory.checkPing(ping.bind({ isActive: true }))

    await delayForDuration(0.3)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Stop the ping setInterval
    clearInterval(pingInterval)
  });

  it('"pingIPAddress": "192.168.1.1", host down', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      pingIPAddress: '192.168.1.1',
      isUnitTest: true
    }

    let switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(undefined);

    const pingInterval = switchAccessory.checkPing(ping.bind({ isActive: false }))

    await delayForDuration(0.3)
    expect(switchAccessory.state.switchState).to.equal(false);

    // Stop the ping setInterval
    clearInterval(pingInterval)
  });

  it('"pingIPAddressStateOnly": true, "pingIPAddress": "192.168.1.1", host up', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      pingIPAddress: '192.168.1.1',
      pingIPAddressStateOnly: true,
      isUnitTest: true
    }

    let switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(undefined);

    const pingInterval = switchAccessory.checkPing(ping.bind({ isActive: true }))

    await delayForDuration(0.3)
    expect(switchAccessory.serviceManager.hasRecordedSetCharacteristic).to.equal(false);
    expect(switchAccessory.state.switchState).to.equal(true);

    // Stop the ping setInterval
    clearInterval(pingInterval)
  });

  it('"pingIPAddressStateOnly": false, "pingIPAddress": "192.168.1.1", host up', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: false,
      host: device.host.address,
      pingIPAddress: '192.168.1.1',
      pingIPAddressStateOnly: false,
      isUnitTest: true
    }

    let switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(undefined);

    const pingInterval = switchAccessory.checkPing(ping.bind({ isActive: true }))

    await delayForDuration(0.3)
    expect(switchAccessory.state.switchState).to.equal(true);
    expect(switchAccessory.serviceManager.hasRecordedSetCharacteristic).to.equal(true);

    // Stop the ping setInterval
    clearInterval(pingInterval)
  });

  // Ensure the hex is resent after reload
  it('"resendHexAfterReload": true, "persistState": true', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: true,
      host: device.host.address,
      resendHexAfterReload: true,
      resendDataAfterReloadDelay: 0.1,
      isUnitTest: true
    }

    let switchAccessory

    // Turn On Switch
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    device.resetSentHexCodes()

    // Should be on still with a new instance
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(true);

    // We should find that setCharacteristic has been called after a duration of resendHexAfterReloadDelay
    await delayForDuration(0.3)
    expect(switchAccessory.serviceManager.hasRecordedSetCharacteristic).to.equal(true);

    // Check ON hex code was sent
    const hasSentOnCode = device.hasSentCode('ON');
    expect(hasSentOnCode).to.equal(true);

    // Check that only one code has been sent
    const sentHexCodeCount = device.getSentHexCodeCount();
    expect(sentHexCodeCount).to.equal(1);
  });

  // Ensure the hex is not resent after reload
  it('"resendHexAfterReload": false, "persistState": true', async () => {
    const { device } = setup();

    const config = {
      data,
      persistState: true,
      host: device.host.address,
      resendHexAfterReload: false,
      resendDataAfterReloadDelay: 0.1,
      isUnitTest: true
    }

    let switchAccessory

    // Turn On Switch
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    switchAccessory.serviceManager.setCharacteristic(Characteristic.On, true)
    expect(switchAccessory.state.switchState).to.equal(true);

    // Should be on still with a new instance
    switchAccessory = new Switch(null, config, 'FakeServiceManager')
    expect(switchAccessory.state.switchState).to.equal(true);

    device.resetSentHexCodes()

    // We should find that setCharacteristic has not been called after a duration of resendHexAfterReloadDelay
    await delayForDuration(0.3)
    expect(switchAccessory.serviceManager.hasRecordedSetCharacteristic).to.equal(false);

    // Check ON hex code was not sent
    const hasSentOnCode = device.hasSentCode('ON');
    expect(hasSentOnCode).to.equal(false);

    // Check that no code was sent
    const sentHexCodeCount = device.getSentHexCodeCount();
    expect(sentHexCodeCount).to.equal(0);
  });
})


text:
namespace google {
namespace api_manager {
namespace service_control {

namespace {

using ::google::api::LabelDescriptor;
using ::google::api::LogDescriptor;
using ::google::api::MetricDescriptor;
using ::google::api::Service;
using ::google::api_manager::utils::Status;
using ::google::protobuf::RepeatedPtrField;

using ::testing::_;
using ::testing::Eq;
using ::testing::Pair;
using ::testing::Property;
using ::testing::UnorderedElementsAre;

template <class Message>
Message Parse(const char *text) {
  ::google::protobuf::TextFormat::Parser parser;
  ::google::protobuf::io::ArrayInputStream input(text, strlen(text));
  Message msg;
  bool success = parser.Parse(&input, &msg);
  EXPECT_TRUE(success);
  return msg;
}

const char unsupported_prefix[] = "unsupported/";

bool StartsWith(const std::string &value, const char *prefix, size_t size) {
  return value.compare(0, size, prefix) == 0;
}

bool IsLabelSupported(const LabelDescriptor &ld) {
  return !StartsWith(ld.key(), unsupported_prefix,
                     sizeof(unsupported_prefix) - 1);
}

bool IsMetricSupported(const MetricDescriptor &md) {
  return !StartsWith(md.name(), unsupported_prefix,
                     sizeof(unsupported_prefix) - 1);
}

typedef std::map<std::string, const LabelDescriptor &> LabelMap;
typedef std::map<std::string, const MetricDescriptor &> MetricMap;

}  // namespace

TEST(LogsMetricsLoaderTest, StartsWith) {
  ASSERT_TRUE(StartsWith("abc", "ab", 2));
  ASSERT_FALSE(
      StartsWith("abc", unsupported_prefix, sizeof(unsupported_prefix) - 1));
}

TEST(LogsMetricsLoaderTest, IsSupported) {
  LabelDescriptor ld;
  ld.set_key("a");
  ASSERT_TRUE(IsLabelSupported(ld));
  ld.set_key("unsupported");
  ASSERT_TRUE(IsLabelSupported(ld));
  ld.set_key("supported/foo");
  ASSERT_TRUE(IsLabelSupported(ld));
  ld.set_key("unsupported/");
  ASSERT_FALSE(IsLabelSupported(ld));
  ld.set_key("unsupported/foo");
  ASSERT_FALSE(IsLabelSupported(ld));

  MetricDescriptor md;
  md.set_name("a");
  ASSERT_TRUE(IsMetricSupported(md));
  md.set_name("unsupported");
  ASSERT_TRUE(IsMetricSupported(md));
  md.set_name("supported/foo");
  ASSERT_TRUE(IsMetricSupported(md));
  md.set_name("unsupported/");
  ASSERT_FALSE(IsMetricSupported(md));
  md.set_name("unsupported/foo");
  ASSERT_FALSE(IsMetricSupported(md));
}

// Configuration contains duplicate labels. We de-dupe them.
TEST(LogsMetricsLoader, AddDuplicateLabels) {
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  {
    RepeatedPtrField<LabelDescriptor> lds;
    lds.Add()->set_key("duplicate");
    lds.Add()->set_key("duplicate");

    LabelMap labels;
    ASSERT_TRUE(lml.AddLabels(lds, &labels).ok());
    ASSERT_THAT(labels, UnorderedElementsAre(Pair("duplicate", _)));
  }
  {
    // Unsupported duplicates are not added.
    RepeatedPtrField<LabelDescriptor> lds;
    lds.Add()->set_key("unsupported/duplicate");
    lds.Add()->set_key("unsupported/duplicate");

    LabelMap empty;
    ASSERT_TRUE(lml.AddLabels(lds, &empty).ok());
    ASSERT_TRUE(empty.empty());
  }
}

// Set of labels so far collected contains label which is in conflict with label
// newly added.
TEST(LogsMetricsLoader, AddConflictingLabels) {
  const char log_descriptor[] =  // We parse LogDescriptor but all we need are
                                 // its labels
      "labels {"
      "  key: \"api-key\""  // lexicographically before 'conflicting'
      "}"
      "labels {"
      "  key: \"conflicting\""
      "  value_type: BOOL"
      "}"
      "labels {"
      "  key: \"request-size\""
      "  value_type: INT64"
      "}";

  LogDescriptor ld = Parse<LogDescriptor>(log_descriptor);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  LabelDescriptor ld_string;
  ld_string.set_key("conflicting");
  ld_string.set_value_type(LabelDescriptor::STRING);
  LabelMap conflict({{"conflicting", ld_string}});
  ASSERT_FALSE(lml.AddLabels(ld.labels(), &conflict).ok());

  // Assert that the label map was not modified.
  ASSERT_THAT(conflict,
              UnorderedElementsAre(
                  Pair("conflicting", Property(&LabelDescriptor::value_type,
                                               Eq(LabelDescriptor::STRING)))));
}

TEST(LogsMetricsLoader, AddUnsupportedLabels) {
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);
  RepeatedPtrField<LabelDescriptor> lds;
  lds.Add()->set_key("unsupported/foo");
  lds.Add()->set_key("supported/baz");
  lds.Add()->set_key("unsupported/bar");

  LabelMap labels;
  ASSERT_TRUE(lml.AddLabels(lds, &labels).ok());
  ASSERT_THAT(labels, UnorderedElementsAre(Pair("supported/baz", _)));
}

TEST(LogsMetricsLoader, AddRedundantLabels) {
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);
  const std::string name("redundant");
  RepeatedPtrField<LabelDescriptor> lds;
  lds.Add()->set_key(name);

  LabelDescriptor redundant;
  redundant.set_key(name);
  LabelMap labels({{name, redundant}});

  ASSERT_TRUE(lml.AddLabels(lds, &labels).ok());
  ASSERT_THAT(labels, UnorderedElementsAre(Pair(name, _)));
}

TEST(LogsMetricsLoader, AddNoLabels) {
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);
  RepeatedPtrField<LabelDescriptor> lds;

  // Adding no labels must work.
  LabelMap labels;
  ASSERT_TRUE(lml.AddLabels(lds, &labels).ok());
  EXPECT_TRUE(labels.empty());
}

TEST(LogsMetricsLoader, AddLogLabels) {
  const char service_config[] =  // Only contains logs, that's all we need.
      "logs {"
      "  name: \"endpoints\""
      "  labels {"
      "    key: \"unsupported/endpoints\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints\""
      "  }"
      "}"
      "logs {"
      "  name: \"startpoints\""
      "  labels {"
      "    key: \"supported/startpoints\""
      "  }"
      "  labels {"
      "    key: \"unsupported/startpoints\""
      "  }"
      "}";

  Service service = Parse<Service>(service_config);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  // Test that only supported labels from the named log are added.
  {
    LabelMap labels;
    ASSERT_TRUE(lml.AddLogLabels(service.logs(), "endpoints", &labels).ok());
    ASSERT_THAT(labels, UnorderedElementsAre(Pair("supported/endpoints", _)));
  }
  {
    LabelMap labels;
    ASSERT_TRUE(lml.AddLogLabels(service.logs(), "startpoints", &labels).ok());
    ASSERT_THAT(labels, UnorderedElementsAre(Pair("supported/startpoints", _)));
  }

  // Referencing log not present in the config --> error.
  {
    LabelMap labels;
    ASSERT_FALSE(lml.AddLogLabels(service.logs(), "notfound", &labels).ok());
    ASSERT_TRUE(labels.empty());
  }
}

TEST(LogsMetricsLoader, AddMonitoredResourceLabels) {
  const char service_config[] =  // Only contains monitored resources, that's
                                 // all we need.
      "monitored_resources {"
      "  type: \"endpoints.googleapis.com/endpoints\""
      "  labels {"
      "    key: \"unsupported/endpoints\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints\""
      "  }"
      "}"
      "monitored_resources {"
      "  type: \"startpoints.googleapis.com/startpoints\""
      "  labels {"
      "    key: \"supported/startpoints\""
      "  }"
      "  labels {"
      "    key: \"unsupported/startpoints\""
      "  }"
      "}";

  Service service = Parse<Service>(service_config);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  // Test that only supported labels from the specific monitored resource are
  // added.
  {
    LabelMap labels;
    ASSERT_TRUE(lml.AddMonitoredResourceLabels(
                       service.monitored_resources(),
                       "endpoints.googleapis.com/endpoints", &labels)
                    .ok());
    ASSERT_THAT(labels, UnorderedElementsAre(Pair("supported/endpoints", _)));
  }
  {
    LabelMap labels;
    ASSERT_TRUE(lml.AddMonitoredResourceLabels(
                       service.monitored_resources(),
                       "startpoints.googleapis.com/startpoints", &labels)
                    .ok());
    ASSERT_THAT(labels, UnorderedElementsAre(Pair("supported/startpoints", _)));
  }

  // Referencing non-existent monitored resource --> error.
  {
    LabelMap labels;
    ASSERT_FALSE(lml.AddMonitoredResourceLabels(
                        service.monitored_resources(),
                        "endpoints.googleapis.com/notfound", &labels)
                     .ok());
    ASSERT_TRUE(labels.empty());
  }
}

TEST(LogsMetricsLoader, AddLoggingDestinations) {
  const char service_config[] =
      // A valid log with one supported label.
      "logs {"
      "  name: \"endpoints-log\""
      "  labels {"
      "    key: \"supported/endpoints-log-label\""
      "  }"
      "  labels {"
      "    key: \"unsupported/endpoints-log-label\""
      "  }"
      "}"

      // A log otherwise unreferenced in the config.
      "logs {"
      "  name: \"unreferenced-log\""
      "  labels: {"
      "    key: \"supported/unreferenced-log-label\""
      "  }"
      "}"

      // Only one valid monitored resource.
      "monitored_resources {"
      "  type: \"endpoints.googleapis.com/endpoints\""
      "  labels {"
      "    key: \"unsupported/endpoints\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints\""
      "  }"
      "}"

      // Logging section
      "logging {"
      // Invalid logging destination (bad resource, log).
      "  producer_destinations {"
      "    monitored_resource: \"bad-monitored-resource\""
      "    logs: \"bad-monitored-resource-log\""
      "  }"

      // Partly valid logging destination (good resource, some good logs).
      "  producer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/endpoints\""
      "    logs: \"bad-endpoints-log\""
      "    logs: \"endpoints-log\""
      "  }"
      "}";

  Service service = Parse<Service>(service_config);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  std::set<std::string> logs;
  LabelMap labels;

  Status s = lml.AddLoggingDestinations(
      service.logging().producer_destinations(), service.monitored_resources(),
      service.logs(), &logs, &labels);
  ASSERT_TRUE(s.ok());

  // Only one log was referenced, and valid.
  ASSERT_THAT(logs, UnorderedElementsAre("endpoints-log"));

  // Only the supported labels from the monitored resource and the log
  // are going to be reported.
  ASSERT_THAT(labels,
              UnorderedElementsAre(Pair("supported/endpoints", _),
                                   Pair("supported/endpoints-log-label", _)));
}

TEST(LogsMetricsLoader, AddMonitoringDestinations) {
  const char service_config[] =
      // A valid metric with one supported label.
      "metrics {"
      "  name: \"supported/endpoints-metric\""
      "  labels {"
      "    key: \"supported/endpoints-metric-label\""
      "  }"
      "  labels {"
      "    key: \"unsupported/endpoints-metric-label\""
      "  }"
      "}"

      // An unsupported metric with a supported label. The supported label won't
      // be reported because the metric isn't.
      "metrics {"
      "  name: \"unsupported/unsupported-endpoints-metric\""
      "  labels {"
      "    key: \"supported/unreferenced-metric-label\""
      "  }"
      "}"

      // Supported metric used by non-existent monitored resource. Thus, it
      // won't be reported.
      "metrics {"
      "  name: \"supported/non-existent-resource-metric\""
      "  labels {"
      "    key: \"supported/non-existent-resource-metric-label\""
      "  }"
      "}"

      // Only one valid monitored resource.
      "monitored_resources {"
      "  type: \"endpoints.googleapis.com/endpoints\""
      "  labels {"
      "    key: \"unsupported/endpoints\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints\""
      "  }"
      "}"

      // Monitoring section. Use consumer destinations only for the purpose of
      // the test.
      "monitoring {"
      "  consumer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/endpoints\""
      "    metrics: \"supported/endpoints-metric\""
      "    metrics: \"unsupported/unsupported-endpoints-metric\""
      "    metrics: \"supported/unknown-metric\""
      "  }"

      // One valid metric but on unrecognized monitored resource. This should be
      // skipped.
      "  consumer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/non-existent\""
      "    metrics: \"supported/endpoints-metric\""
      "    metrics: \"unsupported/unsupported-endpoints-metric\""
      "    metrics: \"supported/unknown-metric\""
      "    metrics: \"supported/non-existent-resource-metric\""
      "  }"
      "}";

  Service service = Parse<Service>(service_config);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  MetricMap metrics;
  LabelMap labels;
  Status s = lml.AddMonitoringDestinations(
      service.monitoring().consumer_destinations(),
      service.monitored_resources(), service.metrics(), &metrics, &labels);
  ASSERT_TRUE(s.ok());

  // Only the supported metrics from valid monitored resources have been added.
  ASSERT_THAT(metrics,
              UnorderedElementsAre(Pair("supported/endpoints-metric", _)));

  // Only the supported labels from the monitored resource and from the metric
  // are recognized.
  ASSERT_THAT(labels, UnorderedElementsAre(
                          Pair("supported/endpoints", _),
                          Pair("supported/endpoints-metric-label", _)));
}

TEST(LogsMetricsLoader, LoadLogsMetrics) {
  const char service_config[] =
      // A valid log with one supported label.
      "logs {"
      "  name: \"endpoints-log\""
      "  labels {"
      "    key: \"supported/endpoints-log-label\""
      "  }"
      "  labels {"
      "    key: \"unsupported/endpoints-log-label\""
      "  }"
      "}"

      // Shared metric.
      "metrics {"
      "  name: \"supported/endpoints-metric\""
      "  labels {"
      "    key: \"supported/endpoints-metric-label\""
      "  }"
      "  labels {"
      "    key: \"unsupported/endpoints-metric-label\""
      "  }"
      "}"
      // Consumer metric.
      "metrics {"
      "  name: \"supported/endpoints-consumer-metric\""
      "  labels {"
      "    key: \"supported/endpoints-metric-label\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints-consumer-metric-label\""
      "  }"
      "}"
      // Producer metric.
      "metrics {"
      "  name: \"supported/endpoints-producer-metric\""
      "  labels {"
      "    key: \"supported/endpoints-metric-label\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints-producer-metric-label\""
      "  }"
      "}"

      // Only one valid monitored resource.
      "monitored_resources {"
      "  type: \"endpoints.googleapis.com/endpoints\""
      "  labels {"
      "    key: \"unsupported/endpoints\""
      "  }"
      "  labels {"
      "    key: \"supported/endpoints\""
      "  }"
      "}"

      // Logging section
      "logging {"
      "  producer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/endpoints\""
      "    logs: \"endpoints-log\""
      "  }"
      "}"

      // Monitoring section.
      "monitoring {"
      "  consumer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/endpoints\""
      "    metrics: \"supported/endpoints-consumer-metric\""
      "    metrics: \"supported/endpoints-metric\""
      "  }"

      // One valid metric but on unrecognized monitored resource. This should be
      // skipped.
      "  producer_destinations {"
      "    monitored_resource: \"endpoints.googleapis.com/endpoints\""
      "    metrics: \"supported/endpoints-producer-metric\""
      "    metrics: \"supported/endpoints-metric\""
      "  }"
      "}";

  Service service = Parse<Service>(service_config);
  LogsMetricsLoader lml(IsLabelSupported, IsMetricSupported);

  std::set<std::string> logs, metrics, labels;
  Status s = lml.LoadLogsMetrics(service, &logs, &metrics, &labels);
  ASSERT_TRUE(s.ok());

  ASSERT_THAT(logs, UnorderedElementsAre("endpoints-log"));
  ASSERT_THAT(metrics,
              UnorderedElementsAre("supported/endpoints-metric",
                                   "supported/endpoints-consumer-metric",
                                   "supported/endpoints-producer-metric"));
  ASSERT_THAT(
      labels,
      UnorderedElementsAre(
          "supported/endpoints",               // from monitored resource
          "supported/endpoints-log-label",     // from log
          "supported/endpoints-metric-label",  // from both metrics
          "supported/endpoints-consumer-metric-label",  // from consumer metric
          "supported/endpoints-producer-metric-label"   // from producer metric
          ));
}

}  // namespace service_control
}  // namespace api_manager
}  // namespace google

redpajama_set_name: RedPajamaGithub


text:
package sun.jvm.hotspot.memory;

import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.types.*;
import sun.jvm.hotspot.runtime.*;

public class AFLBinaryTreeDictionary extends VMObject {
   static {
      VM.registerVMInitializedObserver(new Observer() {
         public void update(Observable o, Object data) {
            initialize(VM.getVM().getTypeDataBase());
         }
      });
   }

   private static synchronized void initialize(TypeDataBase db) {
      Type type = db.lookupType("AFLBinaryTreeDictionary");
      totalSizeField = type.getCIntegerField("_total_size");
   }

   // Fields
   private static CIntegerField totalSizeField;

   // Accessors
   public long size() {
      return totalSizeField.getValue(addr);
   }

   // Constructor
   public AFLBinaryTreeDictionary(Address addr) {
      super(addr);
   }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace AnimatorAccess {
	/// <summary>
	/// Layer status regarding the current Animator state and transition (if any). Both status values are updated at
	/// the begining when checking for events is enabled. Previous values are saved automatically when the state or
	/// transition is set. Use layerStatus.State.Current to get the current state and layerStatus.State.Previous to get
	/// the previous value.
	/// </summary>
	public class LayerStatus
	{
		/// <summary>
		/// Stores the current value of T in field previous whenever set is called. This is done even if the new value
		/// equals to current.
		/// </summary>
        public class HistorisedProperty <T> where T : System.IComparable<T>
		{
			T previous = default (T);
			/// <summary>
			/// Gets the previous values.
			/// </summary>
			/// <value>The previous value.</value>
			public T Previous { get { return previous; } }

			T current = default (T);
			/// <summary>
			/// Gets or sets a new value to current and saves the last one to previous.
			/// </summary>
			/// <value>The current.</value>
			public T Current {
				get { return current; }
				set {
					previous = current;
					current = value;
				}
			}
			/// <summary>
			/// true if Current != Previous
			/// </summary>
			/// <value><c>true</c> if this instance has changed; otherwise, <c>false</c>.</value>
			public bool HasChanged { get {
                    return 0 != current.CompareTo (previous);
                    //return !current.Equals (previous);
                } }
		}

		/// <summary>
		/// The layer to consider when checking for changes in states or transitions.
		/// </summary>
		public int Layer;
		/// <summary>
		/// The Animator state, use State.Current to get the current state's hash ID and State.Previous for the
		/// previous state. Note that 0 is returned on the very first call.
		/// </summary>
		public HistorisedProperty<int> State = new HistorisedProperty<int> ();
		/// <summary>
		/// The transition hash ID or 0 if no transition is active. Use Transition.Current to get the current
		/// transition's hash ID.
		/// </summary>
		public HistorisedProperty<int> Transition = new HistorisedProperty<int> ();

		public LayerStatus (int layer, int state, int transition) {
			this.Layer = layer;
			State.Current = state;
			Transition.Current = transition;
		}
	}
}


text:
package org.bm

import scala.collection.immutable.Queue

/**
 * .
 * @author Baptiste Morin
 */
package object logviewer {
  type Token = String
  type Tokens = Queue[String]

  type ParsedMessage = Map[String, String]
}


text:
package de.tum.in.www1.exerciseapp.web.rest;

import com.codahale.metrics.annotation.Timed;
import de.tum.in.www1.exerciseapp.domain.Question;
import de.tum.in.www1.exerciseapp.repository.QuestionRepository;
import de.tum.in.www1.exerciseapp.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Question.
 */
@RestController
@RequestMapping("/api")
public class QuestionResource {

    private final Logger log = LoggerFactory.getLogger(QuestionResource.class);

    private static final String ENTITY_NAME = "question";

    private final QuestionRepository questionRepository;
    public QuestionResource(QuestionRepository questionRepository) {
        this.questionRepository = questionRepository;
    }

    /**
     * POST  /questions : Create a new question.
     *
     * @param question the question to create
     * @return the ResponseEntity with status 201 (Created) and with body the new question, or with status 400 (Bad Request) if the question has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/questions")
    @Timed
    public ResponseEntity<Question> createQuestion(@RequestBody Question question) throws URISyntaxException {
        log.debug("REST request to save Question : {}", question);
        if (question.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new question cannot already have an ID")).body(null);
        }
        Question result = questionRepository.save(question);
        return ResponseEntity.created(new URI("/api/questions/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /questions : Updates an existing question.
     *
     * @param question the question to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated question,
     * or with status 400 (Bad Request) if the question is not valid,
     * or with status 500 (Internal Server Error) if the question couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/questions")
    @Timed
    public ResponseEntity<Question> updateQuestion(@RequestBody Question question) throws URISyntaxException {
        log.debug("REST request to update Question : {}", question);
        if (question.getId() == null) {
            return createQuestion(question);
        }
        Question result = questionRepository.save(question);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, question.getId().toString()))
            .body(result);
    }

    /**
     * GET  /questions : get all the questions.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of questions in body
     */
    @GetMapping("/questions")
    @Timed
    public List<Question> getAllQuestions() {
        log.debug("REST request to get all Questions");
        return questionRepository.findAll();
        }

    /**
     * GET  /questions/:id : get the "id" question.
     *
     * @param id the id of the question to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the question, or with status 404 (Not Found)
     */
    @GetMapping("/questions/{id}")
    @Timed
    public ResponseEntity<Question> getQuestion(@PathVariable Long id) {
        log.debug("REST request to get Question : {}", id);
        Question question = questionRepository.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(question));
    }

    /**
     * DELETE  /questions/:id : delete the "id" question.
     *
     * @param id the id of the question to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/questions/{id}")
    @Timed
    public ResponseEntity<Void> deleteQuestion(@PathVariable Long id) {
        log.debug("REST request to delete Question : {}", id);
        questionRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}


text:
<!DOCTYPE html>

     <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Ristorante Con Fusion: About Us </title>

    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">

Home

Contact Us

Contact Us

Location Information

Our Address

                    <address style="font-size: 100%">
		              121, Clear Water Bay Road

		              Clear Water Bay, Kowloon

		              HONG KONG

		              : +852 1234 5678

		              : +852 8765 4321

		              :
                        confusion@food.net
		           </address>

Map of our Location

                     Call
                     Skype
                     Email

Send us your Feedback

                <form class="form-horizontal" role="form" name="feedbackForm" ng-submit="sendFeedback()" novalidate>

                        First Name

                        <input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name"
                        ng-model="feedback.firstName" required>
                           Your First name is required.

                        Last Name

                            <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Enter Last Name"
                            ng-model="feedback.lastName" required>
                             Your Last name is required.

                        Contact Tel.

(

                                    <input type="tel" class="form-control" id="areacode" name="areacode" placeholder="Area code"
                                      ng-model="feedback.tel.areaCode">

)

                                    <input type="tel" class="form-control" id="telnum" name="telnum" placeholder="Tel. number"
                                    ng-model="feedback.tel.number">

                        Email

                            <input type="email" class="form-control" id="emailid" name="emailid" placeholder="Email"
                            ng-model="feedback.email" required>

                            Enter a valid email address.

                                <input type="checkbox" name="approve" value=""
                                ng-model="feedback.agree">
                                May we contact you?

                            <select class="form-control" ng-model="feedback.mychannel"
                               ng-options="channel.value as channel.label for channel in channels">
                               <option value="">Tel. or Email?</option>
                            </select>
                            Select an option.

                        Your Feedback

                            <textarea class="form-control" id="feedback" name="feedback" rows="12"
                            ng-model="feedback.comments"></textarea>

                            <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Send Feedback</button>

                </form>

Your Current Feedback:

{{feedback.firstName}} {{feedback.lastName | uppercase }}

Contact Tel.: ({{feedback.tel.areaCode}}) {{feedback.tel.number}}

Contact Email: {{feedback.email}}

Contact by: {{feedback.mychannel}}

Comments: {{feedback.comments}}


text:
This purpose of this Exercise was to describe and show a function for counting the number of elements in a list

# SAMPLE RUN

```
Interpreting project: Prolog Programs
  Loading Extensions:  aosutils.lsx (always loaded in IDE)
  Consulting Source Files: 'program4.pro'
Type 'quit.' to end and [Ctrl]-C to stop user input.

?- countEm([a,b,c,d],N).

N = 4 ;
no
?- quit.
```


text:
//
//  commentTableViewCell.m
//  saltfish
//
//  Created by alfred on 15/12/16.
//  Copyright © 2015年 Alfred. All rights reserved.
//

#import "commentTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "colorManager.h"
#import "YYWebImage.h"

@implementation commentTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark - custom cells

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        /*
         CGRect nameLabelRect = CGRectMake(0, 5, 70, 15);
         UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
         nameLabel.text = @"Name:";
         nameLabel.font = [UIFont boldSystemFontOfSize:12];
         [self.contentView addSubview: nameLabel];
         */

        _screenHeight = [UIScreen mainScreen].bounds.size.height;
        _screenWidth = [UIScreen mainScreen].bounds.size.width;

        // 一些初始化的值
        _nickname = @"梦遗大师";
        _comment = @"跟同学摄影的朋友们在金山海滩群拍,抢不到机位就用新入的小傻瓜机按了几张,1比3的比例,电影感极强,冲扫出来却很是喜欢";
        _createTime = @"2014-09-23";
        _picURL = @"";
        self.tag = 999999;

        // 昵称
        _nicknameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 15, _screenWidth-50, 15)];
        _nicknameLabel.text = _nickname;
        _nicknameLabel.font = [UIFont fontWithName:@"Helvetica" size: 13];
        _nicknameLabel.textColor = [colorManager commentTextColor];
        [self.contentView addSubview:_nicknameLabel];

        // 评论内容
        _commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 41, _screenWidth-50, 30)];
        _commentLabel.text = _comment;
        _commentLabel.font = [UIFont fontWithName:@"Helvetica" size: 13];
        _commentLabel.textColor = [colorManager commentTextColor];
        [self.contentView addSubview:_commentLabel];

        // 创建时间
        _createTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, _screenWidth-50, 15)];
        _createTimeLabel.text = _createTime;
        _createTimeLabel.font = [UIFont fontWithName:@"Helvetica" size: 11];
        _createTimeLabel.textColor = [colorManager lightTextColor];
        [self.contentView addSubview:_createTimeLabel];

        // 头像(1.0是固定的默认头像)
//        _picImageView = [[UIImageView alloc] initWithFrame:CGRectMake(13, 9, 26, 26)];
//        UIImage *oneImage = [UIImage imageNamed:@"portrait.png"]; // 使用ImageView通过name找到图片
//        [_picImageView setImage:oneImage];
//        [self.contentView addSubview:_picImageView];

        // 头像(2.0是用户自己的头像)
        _picImageView = [[UIImageView alloc] initWithFrame:CGRectMake(13, 9, 26, 26)];
        _picImageView.backgroundColor = [UIColor grayColor];
        // uiimageview居中裁剪
        _picImageView.contentMode = UIViewContentModeScaleAspectFill;
        _picImageView.clipsToBounds  = YES;
        _picImageView.layer.cornerRadius = 13;
        [self.contentView addSubview:_picImageView];

        // 背景、分割线
        _partLine = [[UIView alloc] initWithFrame:CGRectMake(50, 0, _screenWidth, 0.5)];
        _partLine.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
        [self.contentView addSubview:_partLine];
        self.contentView.backgroundColor = [UIColor whiteColor];

        // not usefull
        self.frame = CGRectMake(0, 0, 300, 300);
        NSLog(@"%f", self.frame.size.height);

    }
    return self;
}

#pragma mark - 重写cell属性

- (void)rewritePortrait:(NSString *)newPortrait
{
    _picURL = newPortrait;
    // 普通加载网络图片 yy库
    _picImageView.yy_imageURL = [NSURL URLWithString:_picURL];
}

- (void)rewriteNickname:(NSString *)newNickname
{
    _nickname = newNickname;
    _nicknameLabel.text = _nickname;
}

- (void)rewriteCreateTime:(NSString *)newCreateTime
{
    _createTime = newCreateTime;
    _createTimeLabel.text = _createTime;
}

- (void)rewriteComment:(NSString *)newComment
{
    _comment = newComment;
    //_commentLabel.text = _comment;

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_comment];
    //设置行距
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 3;//行距
    [text addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, text.length)];
    _commentLabel.attributedText = text;

    // ===================设置UIlabel文本折行====================
    NSString *str = _comment;
    CGSize maxSize = {_screenWidth-50-15, 5000};  // 设置文本区域最大宽高
    CGSize labelSize = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:13]
                       constrainedToSize:maxSize
                           lineBreakMode:_commentLabel.lineBreakMode];   // str是要显示的字符串
    _commentLabel.frame = CGRectMake(50,42,labelSize.width,labelSize.height/13*16);  // 因为行距增加了,所以要用参数修正height
    _commentLabel.numberOfLines = 0;  // 不可少Label属性之一
    //_postTextLabel.lineBreakMode = UILineBreakModeCharacterWrap;  // 不可少Label属性之二
    // ========================================================
    // 使用uitextview也可以,可以研究下。。。

    // 设置cellHeight (所有高度和间距加起来)
    _cellHeight = 42 + _commentLabel.frame.size.height + 10 + 15 +15;
    // 设置createTime的位置
    _createTimeLabel.frame = CGRectMake(50, 42+_commentLabel.frame.size.height+10, _screenWidth-60, 15);
    // 设置分割线的位置
    _partLine.frame = CGRectMake(50, _cellHeight-0.5, _screenWidth-50, 0.5);
}

@end


text:
package com.podio.sdk.domain;

/**
 * Created by sai on 8/31/16.
 */
public class LinkedAccountData {
    private final String url = null;
    private final String info = null;
    private final String type = null;
    private final String id = null;

    public String getUrl() {
        return url;
    }

    public String getInfo() {
        return info;
    }

    public String getType() {
        return type;
    }

    public String getId() {
        return id;
    }
}


text:
package org.apache.hadoop.yarn.sls;

import org.apache.hadoop.yarn.api.records.ExecutionType;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.exceptions.YarnException;
import java.util.Map;

import static org.apache.hadoop.yarn.sls.AMDefinitionRumen.DEFAULT_MAPPER_PRIORITY;

public class TaskContainerDefinition {
  private long duration;
  private Resource resource;
  private int priority;
  private String type;
  private int count;
  private ExecutionType executionType;
  private long allocationId = -1;
  private long requestDelay = 0;
  private String hostname;

  public long getDuration() {
    return duration;
  }

  public Resource getResource() {
    return resource;
  }

  public int getPriority() {
    return priority;
  }

  public String getType() {
    return type;
  }

  public int getCount() {
    return count;
  }

  public ExecutionType getExecutionType() {
    return executionType;
  }

  public long getAllocationId() {
    return allocationId;
  }

  public long getRequestDelay() {
    return requestDelay;
  }

  public String getHostname() {
    return hostname;
  }

  public static final class Builder {
    private long duration = -1;
    private long durationLegacy = -1;
    private long taskStart = -1;
    private long taskFinish = -1;
    private Resource resource;
    private int priority = DEFAULT_MAPPER_PRIORITY;
    private String type = "map";
    private int count = 1;
    private ExecutionType executionType = ExecutionType.GUARANTEED;
    private long allocationId = -1;
    private long requestDelay = 0;
    private String hostname;

    public static Builder create() {
      return new Builder();
    }

    public Builder withDuration(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.duration = Integer.parseInt(jsonTask.get(key));
      }
      return this;
    }

    public Builder withDuration(long duration) {
      this.duration = duration;
      return this;
    }

    /**
     * Also support "duration.ms" for backward compatibility.
     * @param jsonTask the json representation of the task.
     * @param key The json key.
     * @return the builder
     */
    public Builder withDurationLegacy(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.durationLegacy = Integer.parseInt(jsonTask.get(key));
      }
      return this;
    }

    public Builder withTaskStart(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.taskStart = Long.parseLong(jsonTask.get(key));
      }
      return this;
    }

    public Builder withTaskFinish(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.taskFinish = Long.parseLong(jsonTask.get(key));
      }
      return this;
    }

    public Builder withResource(Resource resource) {
      this.resource = resource;
      return this;
    }

    public Builder withPriority(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.priority = Integer.parseInt(jsonTask.get(key));
      }
      return this;
    }

    public Builder withPriority(int priority) {
      this.priority = priority;
      return this;
    }

    public Builder withType(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.type = jsonTask.get(key);
      }
      return this;
    }

    public Builder withType(String type) {
      this.type = type;
      return this;
    }

    public Builder withCount(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        count = Integer.parseInt(jsonTask.get(key));
        count = Math.max(count, 1);
      }
      return this;
    }

    public Builder withCount(int count) {
      this.count = count;
      return this;
    }

    public Builder withExecutionType(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.executionType = ExecutionType.valueOf(jsonTask.get(key));
      }
      return this;
    }

    public Builder withExecutionType(ExecutionType executionType) {
      this.executionType = executionType;
      return this;
    }

    public Builder withAllocationId(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        this.allocationId = Long.parseLong(jsonTask.get(key));
      }
      return this;
    }

    public Builder withAllocationId(long allocationId) {
      this.allocationId = allocationId;
      return this;
    }

    public Builder withRequestDelay(Map<String, String> jsonTask, String key) {
      if (jsonTask.containsKey(key)) {
        requestDelay = Long.parseLong(jsonTask.get(key));
        requestDelay = Math.max(requestDelay, 0);
      }
      return this;
    }

    public Builder withRequestDelay(long requestDelay) {
      this.requestDelay = requestDelay;
      return this;
    }

    public Builder withHostname(String hostname) {
      this.hostname = hostname;
      return this;
    }

    public TaskContainerDefinition build() throws YarnException {
      TaskContainerDefinition taskContainerDef =
          new TaskContainerDefinition();
      taskContainerDef.duration = validateAndGetDuration(this);
      taskContainerDef.resource = this.resource;
      taskContainerDef.type = this.type;
      taskContainerDef.requestDelay = this.requestDelay;
      taskContainerDef.priority = this.priority;
      taskContainerDef.count = this.count;
      taskContainerDef.allocationId = this.allocationId;
      taskContainerDef.executionType = this.executionType;
      taskContainerDef.hostname = this.hostname;
      return taskContainerDef;
    }

    private long validateAndGetDuration(Builder builder) throws YarnException {
      long duration = 0;

      if (builder.duration != -1) {
        duration = builder.duration;
      } else if (builder.durationLegacy != -1) {
        duration = builder.durationLegacy;
      } else if (builder.taskStart != -1 && builder.taskFinish != -1) {
        duration = builder.taskFinish - builder.taskStart;
      }

      if (duration <= 0) {
        throw new YarnException("Duration of a task shouldn't be less or equal"
            + " to 0!");
      }
      return duration;
    }
  }
}


text:
package uk.gov.gds.ier.transaction.overseas.nino

import uk.gov.gds.ier.test._
import uk.gov.gds.ier.model.Nino
import uk.gov.gds.ier.transaction.overseas.InprogressOverseas

class NinoMustacheTests
  extends MustacheTestSuite
  with NinoForms
  with NinoMustache {

  it should "empty progress form should produce empty Model" in {
    val emptyApplicationForm = ninoForm
    val ninoModel = mustache.data(
      emptyApplicationForm,
      Call("POST", "/register-to-vote/overseas/nino"),
      InprogressOverseas()
    ).asInstanceOf[NinoModel]

    ninoModel.question.title should be("What is your National Insurance number?")
    ninoModel.question.postUrl should be("/register-to-vote/overseas/nino")

    ninoModel.nino.value should be("")
    ninoModel.noNinoReason.value should be("")
  }

  it should "progress form with filled applicant nino should produce Mustache Model with nino values present" in {
    val partiallyFilledApplicationForm = ninoForm.fill(InprogressOverseas(
      nino = Some(Nino(
        nino = Some("AB123456C"),
        noNinoReason = None))))

    val ninoModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST", "/register-to-vote/overseas/nino"),
      InprogressOverseas()
    ).asInstanceOf[NinoModel]

    ninoModel.question.title should be("What is your National Insurance number?")
    ninoModel.question.postUrl should be("/register-to-vote/overseas/nino")

    ninoModel.nino.value should be("AB123456C")
    ninoModel.noNinoReason.value should be("")
  }

  it should "progress form with filled applicant no nino reason should produce Mustache Model with no nino reason values present" in {
    val partiallyFilledApplicationForm = ninoForm.fill(InprogressOverseas(
      nino = Some(Nino(
        nino = None,
        noNinoReason = Some("dunno!")))))

    val ninoModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST", "/register-to-vote/overseas/nino"),
      InprogressOverseas()
    ).asInstanceOf[NinoModel]

    ninoModel.question.title should be("What is your National Insurance number?")
    ninoModel.question.postUrl should be("/register-to-vote/overseas/nino")

    ninoModel.nino.value should be("")
    ninoModel.noNinoReason.value should be("dunno!")
  }

  it should "progress form with validation errors should produce Model with error list present" in {
    val partiallyFilledApplicationForm = ninoForm.fillAndValidate(InprogressOverseas(
      nino = Some(Nino(
        nino = Some("ABCDE"),
        noNinoReason = None))))

    val ninoModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST", "/register-to-vote/overseas/nino"),
      InprogressOverseas()
    ).asInstanceOf[NinoModel]

    ninoModel.question.title should be("What is your National Insurance number?")
    ninoModel.question.postUrl should be("/register-to-vote/overseas/nino")

    ninoModel.nino.value should be("ABCDE")
    ninoModel.noNinoReason.value should be("")

    ninoModel.question.errorMessages.mkString(", ") should be("Your National Insurance number is not correct")
  }
}


text:
;
(function (win, $, undefined) {

    var classes = {
        stackTable: 'tablesaw-stack',
        cellLabels: 'tablesaw-cell-label',
        cellContentLabels: 'tablesaw-cell-content'
    };

    var data = {
        obj: 'tablesaw-stack'
    };

    var attrs = {
        labelless: 'data-tablesaw-no-labels',
        hideempty: 'data-tablesaw-hide-empty'
    };

    var Stack = function (element) {

        this.$table = $(element);

        this.labelless = this.$table.is('[' + attrs.labelless + ']');
        this.hideempty = this.$table.is('[' + attrs.hideempty + ']');

        if (!this.labelless) {
            // allHeaders references headers, plus all THs in the thead, which may include several rows, or not
            this.allHeaders = this.$table.find("th");
        }

        this.$table.data(data.obj, this);
    };

    Stack.prototype.init = function (colstart) {
        this.$table.addClass(classes.stackTable);

        if (this.labelless) {
            return;
        }

        // get headers in reverse order so that top-level headers are appended last
        var reverseHeaders = $(this.allHeaders);
        var hideempty = this.hideempty;

        // create the hide/show toggles
        reverseHeaders.each(function () {
            var $t = $(this),
                $cells = $(this.cells).filter(function () {
                    return !$(this).parent().is("[" + attrs.labelless + "]") && ( !hideempty || !$(this).is(":empty") );
                }),
                hierarchyClass = $cells.not(this).filter("thead th").length && " tablesaw-cell-label-top",
            // TODO reduce coupling with sortable
                $sortableButton = $t.find(".tablesaw-sortable-btn"),
                html = $sortableButton.length ? $sortableButton.html() : $t.html();

            if (html !== "") {
                if (hierarchyClass) {
                    var iteration = parseInt($(this).attr("colspan"), 10),
                        filter = "";

                    if (iteration) {
                        filter = "td:nth-child(" + iteration + "n + " + ( colstart ) + ")";
                    }
                    $cells.filter(filter).prepend("" + html + "");
                } else {
                    $cells.wrapInner("");
                    $cells.prepend("" + html + "");
                }
            }
        });
    };

    Stack.prototype.destroy = function () {
        this.$table.removeClass(classes.stackTable);
        this.$table.find('.' + classes.cellLabels).remove();
        this.$table.find('.' + classes.cellContentLabels).each(function () {
            $(this).replaceWith(this.childNodes);
        });
    };

    // on tablecreate, init
    $(document).on("tablesawcreate", function (e, Tablesaw, colstart) {
        if (Tablesaw.mode === 'stack') {
            var table = new Stack(Tablesaw.table);
            table.init(colstart);
        }

    });

    $(document).on("tablesawdestroy", function (e, Tablesaw) {

        if (Tablesaw.mode === 'stack') {
            $(Tablesaw.table).data(data.obj).destroy();
        }

    });

}(this, jQuery));


text:
/***********************************************************************
    filename:   ImageLoaderManager.cpp
    created:    10 Jun 2006
    author:     Olivier Delannoy

    purpose:    Manage the list of existing ImageLoader
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "SILLYImageLoaderManager.h"

#ifndef SILLY_OPT_INLINE
#define inline
#include "SILLYImageLoaderManager.icpp"
#undef inline
#endif
#include "SILLYImageLoader.h"
#include "loaders/SILLYTGAImageLoader.h"

#ifdef SILLY_HAVE_JPG
#include "loaders/SILLYJPGImageLoader.h"
#endif

#ifdef SILLY_HAVE_PNG
#include "loaders/SILLYPNGImageLoader.h"
#endif

// Start of SILLY namespace section
namespace SILLY
{

// we need to do "reference counting" for init/exit to allow silly to be used
// from inside multiple independent libraries simultaneously.
static size_t silly_init_counter = 0;

ImageLoaderManager* ImageLoaderManager::d_instance = 0;

ImageLoaderManager::ImageLoaderManager()
{
    assert(d_instance == 0);
    d_instance = this;
    add(new TGAImageLoader);
#ifdef SILLY_HAVE_JPG
    add(new JPGImageLoader);
#endif
#ifdef SILLY_HAVE_PNG
    add(new PNGImageLoader);
#endif
// Add other builtins loader here

}

ImageLoaderManager::~ImageLoaderManager()
{
    for(ImageLoaderList::iterator iter = d_loaders.begin() ; iter != d_loaders.end() ; ++iter)
    {
        delete (*iter);
    }
    d_instance = 0;
}

bool SILLYInit()
{
    if (ImageLoaderManager::getSingletonPtr() == 0)
    {
        if (!new ImageLoaderManager)
        {
            return false;
        }
    }
    ++silly_init_counter;
    return true;
}

void SILLYCleanup()
{
    if (--silly_init_counter == 0)
    {
        delete ImageLoaderManager::getSingletonPtr();
    }
}

} // End of SILLY namespace section


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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
STANFORD UNIVERSITY 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.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.poller.v3;

import java.io.*;
import java.net.*;
import java.util.*;

import org.mortbay.util.*;

import org.lockss.app.*;
import org.lockss.config.*;
import org.lockss.config.Configuration.*;
import org.lockss.hasher.*;
import org.lockss.plugin.*;
import org.lockss.poller.*;
import org.lockss.poller.v3.V3Serializer.*;
import org.lockss.protocol.*;
import org.lockss.protocol.BlockingStreamComm.*;
import org.lockss.protocol.LcapDatagramRouter.MessageHandler;
import org.lockss.protocol.LcapStreamComm.*;
import org.lockss.protocol.psm.*;
import org.lockss.repository.*;
import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.util.Queue;

/**
 * Functional tests for the V3Poller.
 */
public class FuncV3Poller extends LockssTestCase {

  private IdentityManager idmgr;
  private MockLockssDaemon theDaemon;
  private HashService hashService;

  private PeerIdentity pollerId;

  private String tempDirPath;
  private ArchivalUnit testau;
  private PollManager pollmanager;

  private PeerIdentity[] voters;
  private V3LcapMessage[] pollAcks;
  private V3LcapMessage[] nominates;
  private V3LcapMessage[] votes;
  private byte[][] pollerNonces;
  private byte[][] voterNonces;
  private byte[][] voterNonce2s;
  private File tempDir;

  private static final String BASE_URL = "http://www.test.org/";

  private static String[] urls = {
    "lockssau:",
    BASE_URL,
    BASE_URL + "index.html",
    BASE_URL + "file1.html",
    BASE_URL + "file2.html",
    BASE_URL + "file3.html",
    BASE_URL + "file4.html"
  };

  private static List voteBlocks;
  static {
    voteBlocks = new ArrayList();
    for (int ix = 2; ix < urls.length; ix++) {
      VoteBlock vb = V3TestUtils.makeVoteBlock(urls[ix]);
      voteBlocks.add(vb);
    }
  }

  public void setUp() throws Exception {
    super.setUp();
    tempDir = getTempDir();
    tempDirPath = tempDir.getAbsolutePath();
    System.setProperty("java.io.tmpdir", tempDirPath);
    startDaemon();
    getMockLockssDaemon().getPsmManager().startService();
  }

  public void tearDown() throws Exception {
    stopDaemon();
    super.tearDown();
  }

  private void startDaemon() throws Exception {
    TimeBase.setSimulated();
    this.testau = setupAu();
    theDaemon = getMockLockssDaemon();
    Properties p = new Properties();
    p.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath + "iddb");
    p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath);
    p.setProperty(IdentityManager.PARAM_LOCAL_IP, "127.0.0.1");
    p.setProperty(ConfigManager.PARAM_NEW_SCHEDULER, "true");
    p.setProperty(V3Poller.PARAM_MAX_POLL_DURATION, "6m");
    p.setProperty(V3Poller.PARAM_QUORUM, "3");
    p.setProperty(LcapStreamComm.PARAM_ENABLED, "true");
    p.setProperty(LcapDatagramComm.PARAM_ENABLED, "false");
    p.setProperty(IdentityManager.PARAM_LOCAL_V3_IDENTITY,
		  "TCP:[127.0.0.1]:3456");
    p.setProperty(IdentityManagerImpl.PARAM_INITIAL_PEERS,
                  "TCP:[127.0.0.2]:3456;TCP:[127.0.0.3]:3456;"
                  + "TCP:[127.0.0.4]:3456;TCP:[127.0.0.5]:3456;"
                  + "TCP:[127.0.0.6]:3456;TCP:[127.0.0.7]:3456");
    ConfigurationUtil.setCurrentConfigFromProps(p);
    idmgr = theDaemon.getIdentityManager();
    pollmanager = theDaemon.getPollManager();
    hashService = theDaemon.getHashService();
    theDaemon.setStreamCommManager(new MyMockStreamCommManager(theDaemon));
    theDaemon.setDatagramRouterManager(new MyMockLcapDatagramRouter());
    theDaemon.setRouterManager(new MyMockLcapRouter());
    theDaemon.setNodeManager(new MockNodeManager(), testau);
    theDaemon.setPluginManager(new MyMockPluginManager(theDaemon, testau));
    theDaemon.setDaemonInited(true);
    theDaemon.getSchedService().startService();
    theDaemon.getActivityRegulator(testau).startService();
    idmgr.startService();
    hashService.startService();
    pollmanager.startService();
    this.pollerId = idmgr.stringToPeerIdentity("127.0.0.1");
    this.voters = makeVoters(4);
    this.pollerNonces = makeNonces();
    this.voterNonces = makeNonces();
    this.voterNonce2s = makeNonces();
    this.pollAcks = makePollAckMessages();
    this.nominates = makeNominateMessages();
    this.votes = makeVoteMessages();
  }

  private void stopDaemon() throws Exception {
    theDaemon.getPollManager().stopService();
    theDaemon.getPluginManager().stopService();
    theDaemon.getActivityRegulator(testau).stopService();
    theDaemon.getSystemMetrics().stopService();
    theDaemon.getRouterManager().stopService();
    theDaemon.getDatagramRouterManager().stopService();
    theDaemon.getHashService().stopService();
    theDaemon.getSchedService().stopService();
    theDaemon.getIdentityManager().stopService();
    theDaemon.setDaemonInited(false);
    this.testau = null;
    TimeBase.setReal();
  }

  private MockArchivalUnit setupAu() {
    MockArchivalUnit mau = new MockArchivalUnit();
    mau.setAuId("mock");
    MockPlugin plug = new MockPlugin();
    mau.setPlugin(plug);
    MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
    cus.setEstimatedHashDuration(3000);
    List files = new ArrayList();
    for (int ix = 2; ix < urls.length; ix++) {
      MockCachedUrl cu = (MockCachedUrl)mau.addUrl(urls[ix], false, true);
      // Add mock file content.
      cu.setContent("This is content for CUS file " + ix);
      files.add(cu);
    }
    cus.setHashItSource(files);
    cus.setFlatItSource(files);
    return mau;
  }

  private PeerIdentity[] makeVoters(int count) throws Exception {
    PeerIdentity[] ids = new PeerIdentity[count];
    for (int i = 0; i < count; i++) {
      ids[i] = idmgr.stringToPeerIdentity("10.1.0." + (i+1));
    }
    return ids;
  }

  private byte[][] makeNonces() {
    byte[][] nonces = new byte[voters.length][];
    for (int ix = 0; ix < voters.length; ix++) {
      nonces[ix] = ByteArray.makeRandomBytes(20);
    }
    return nonces;
  }

  private V3LcapMessage[] makePollAckMessages() {
    V3LcapMessage[] msgs = new V3LcapMessage[voters.length];
    for (int i = 0; i < voters.length; i++) {
      msgs[i] = new V3LcapMessage("auid", "key", "3", pollerNonces[i],
                                  voterNonces[i], voterNonce2s[i],
				  V3LcapMessage.MSG_POLL_ACK,
                                  123456789, voters[i], tempDir, theDaemon);
    }
    return msgs;
  }

  private V3LcapMessage[] makeNominateMessages() {
    V3LcapMessage[] msgs = new V3LcapMessage[voters.length];
    for (int i = 0; i < voters.length; i++) {
      V3LcapMessage msg = new V3LcapMessage("auid", "key", "3",
                                            pollerNonces[i], voterNonces[i],
					    voterNonce2s[i],
                                            V3LcapMessage.MSG_NOMINATE,
                                            123456789, voters[i], tempDir,
                                            theDaemon);
      msg.setNominees(ListUtil.list("10.0." + i + ".1",
				    "10.0." + i + ".2",
				    "10.0." + i + ".3",
				    "10.0." + i + ".4"));
      msgs[i] = msg;
    }
    return msgs;
  }

  private V3LcapMessage[] makeVoteMessages() throws IOException {
    V3LcapMessage[] msgs = new V3LcapMessage[voters.length];
    for (int i = 0; i < voters.length; i++) {
      V3LcapMessage msg = new V3LcapMessage("auid", "key", "3",
                                            pollerNonces[i], voterNonces[i],
					    voterNonce2s[i],
                                            V3LcapMessage.MSG_VOTE, 123456789,
                                            voters[i], tempDir, theDaemon);
      for (Iterator it = voteBlocks.iterator(); it.hasNext(); ) {
	msg.addVoteBlock((VoteBlock)it.next());
      }
      msgs[i] = msg;
    }
    return msgs;
  }

  public void testStub() {
    // This file is in need of a total overhaul.  Until then, this
    // stub method is here to let builds proceed normally.
  }

//  public void testRestorePoll() throws Exception {
//    PollSpec pollspec = new PollSpec(testau.getAuCachedUrlSet(),
//                                     Poll.V3_POLL);
//    Poll p1 = pollmanager.callPoll(pollspec);
//    assertNotNull(p1);
//    assertEquals(1, pollmanager.getV3Pollers().size());
//    stopDaemon();
//    assertEquals(0, pollmanager.getV3Pollers().size());
//    startDaemon();
//    assertEquals(1, pollmanager.getV3Pollers().size());
//    Poll p2 = pollmanager.getPoll(p1.getKey());
//    assertNotNull(p2);
//    assertEquals(p2.getKey(), p1.getKey());
//    V3Poller p1V3 = (V3Poller)p1;
//    V3Poller p2V3 = (V3Poller)p2;
//    assertEquals(p1V3.getCallerID(), p2V3.getCallerID());
//    assertEquals(p1V3.getDeadline(), p2V3.getDeadline());
//    assertEquals(p1V3.getDuration(), p2V3.getDuration());
//    assertEquals(p1V3.getStatusString(), p2V3.getStatusString());
//    assertEquals(p1V3.theParticipants.size(), p2V3.theParticipants.size());
//    V3TestUtil.assertEqualPollerStateBeans(p1V3.getPollerStateBean(),
//                                           p2V3.getPollerStateBean());
//    for (Iterator it = p1V3.theParticipants.keySet().iterator(); it.hasNext(); ) {
//      PeerIdentity voter = (PeerIdentity)it.next();
//      ParticipantUserData ud1 =
//        (ParticipantUserData)p1V3.theParticipants.get(voter);
//      ParticipantUserData ud2 =
//        (ParticipantUserData)p2V3.theParticipants.get(voter);
//      V3TestUtil.assertEqualParticipantUserData(ud1, ud2);
//    }
//    pollmanager.cancelAuPolls(testau);
//  }

  public class MyV3Poller extends V3Poller {
    // For testing:  Hashmap of voter IDs to V3LcapMessages.
    private Map sentMsgs = Collections.synchronizedMap(new HashMap());
    private Map semaphores = new HashMap();
    private PeerIdentity[] mockVoters;

    MyV3Poller(PollSpec spec, LockssDaemon daemon, PeerIdentity id,
	       String pollkey, long duration, String hashAlg,
               PeerIdentity[] mockVoters)
        throws PollSerializerException {
      super(spec, daemon, id, pollkey, duration, hashAlg);
      this.mockVoters = mockVoters;
    }

    Collection getReferenceList() {
      return ListUtil.fromArray(mockVoters);
    }

    public void nominatePeers(PeerIdentity voter, List nominees) {
      // do nothing.
    }

    public void sendMessageTo(V3LcapMessage msg, PeerIdentity to) {
      sentMsgs.put(to, msg);
      SimpleBinarySemaphore sem = (SimpleBinarySemaphore)semaphores.get(to);
      if (sem == null) {
	sem = new SimpleBinarySemaphore();
	semaphores.put(to, sem);
      }
      sem.give();
    }

    public V3LcapMessage getSentMessage(PeerIdentity voter) {
      SimpleBinarySemaphore sem = (SimpleBinarySemaphore)semaphores.get(voter);
      if (sem == null) {
        fail ("Message never sent!");
      }
      sem.take(5000); // Really shouldn't take this long
      return (V3LcapMessage)sentMsgs.get(voter);
    }
  }

  class MyMockLcapRouter extends LcapRouter {
    public void registerMessageHandler(org.lockss.protocol.LcapRouter.MessageHandler handler) {
    }

    public void send(V1LcapMessage msg, ArchivalUnit au) throws IOException {
    }

    public void sendTo(V1LcapMessage msg, ArchivalUnit au, PeerIdentity id)
        throws IOException {
    }

    public void sendTo(V3LcapMessage msg, PeerIdentity id) throws IOException {
    }

    public void setConfig(Configuration config, Configuration oldConfig,
                          Differences changedKeys) {
    }

    public void startService() {
    }

    public void stopService() {
    }

    public void unregisterMessageHandler(org.lockss.protocol.LcapRouter.MessageHandler handler) {
    }
  }

  class MyMockLcapDatagramRouter extends LcapDatagramRouter {
    public void registerMessageHandler(MessageHandler handler) {
    }
    public void send(V1LcapMessage msg, ArchivalUnit au)
        throws IOException {
    }
    public void sendTo(V1LcapMessage msg, ArchivalUnit au, PeerIdentity id)
        throws IOException {
    }
    public void setConfig(Configuration config, Configuration oldConfig,
                          Differences changedKeys) {
    }
    public void startService() {
    }
    public void stopService() {
    }
    public void unregisterMessageHandler(MessageHandler handler) {
    }
  }

  class MyMockStreamCommManager extends BlockingStreamComm {
    private LockssDaemon theDaemon;

    public MyMockStreamCommManager(LockssDaemon daemon) {
      this.theDaemon = daemon;
    }
    public void sendTo(PeerMessage msg, PeerIdentity id,
                       RateLimiter limiter) throws IOException {
      log.debug("sendTo: id=" + id);
    }
    public void setConfig(Configuration config, Configuration prevConfig,
                          Differences changedKeys) {
    }
    public PeerMessage newPeerMessage() {
      throw new UnsupportedOperationException("Not implemented");
    }
    public PeerMessage newPeerMessage(long estSize) {
      throw new UnsupportedOperationException("Not implemented");
    }
    public void registerMessageHandler(int protocol, MessageHandler handler) {
      log.debug("MockStreamCommManager: registerMessageHandler");
    }
    public void unregisterMessageHandler(int protocol) {
      log.debug("MockStreamCommManager: unregisterMessageHandler");
    }
    public void startService() {
      log.debug("MockStreamCommManager: startService()");
    }
    public void stopService() {
      log.debug("MockStreamCommManager: stopService()");
    }
    public LockssDaemon getDaemon() {
      return theDaemon;
    }
    public void initService(LockssApp app) throws LockssAppException {
      log.debug("MockStreamCommManager: initService(app)");
    }
    public void initService(LockssDaemon daemon) throws LockssAppException {
      log.debug("MockStreamCommManager: initService(daemon)");
    }
    public LockssApp getApp() {
      log.debug("MockStreamCommManager: getApp()");
      return null;
    }
    protected boolean isAppInited() {
      return true;
    }
    protected void resetConfig() {
      log.debug("MockStreamCommManager: resetConfig()");
    }

  }

  class MyMockPluginManager extends PluginManager {
    ArchivalUnit au;
    LockssDaemon daemon;

    public MyMockPluginManager(LockssDaemon daemon, ArchivalUnit au) {
      this.daemon = daemon;
      this.au = au;
    }

    public LockssDaemon getDaemon() {
      return daemon;
    }

    public CachedUrlSet findCachedUrlSet(String auId) {
      return au.getAuCachedUrlSet();
    }
  }
}


text:
using Neo.IO;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Neo.Persistence
{
    /// <summary>
    /// An in-memory <see cref="IStore"/> implementation that uses ConcurrentDictionary as the underlying storage.
    /// </summary>
    public class MemoryStore : IStore
    {
        private readonly ConcurrentDictionary<byte[], byte[]> innerData = new(ByteArrayEqualityComparer.Default);

        public void Delete(byte[] key)
        {
            innerData.TryRemove(key.EnsureNotNull(), out _);
        }

        public void Dispose()
        {
        }

        public ISnapshot GetSnapshot()
        {
            return new MemorySnapshot(innerData);
        }

        public void Put(byte[] key, byte[] value)
        {
            innerData[key.EnsureNotNull()] = value;
        }

        public IEnumerable<(byte[] Key, byte[] Value)> Seek(byte[] keyOrPrefix, SeekDirection direction = SeekDirection.Forward)
        {
            if (direction == SeekDirection.Backward && keyOrPrefix?.Length == 0) yield break;

            ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse;
            IEnumerable<KeyValuePair<byte[], byte[]>> records = innerData;
            if (keyOrPrefix?.Length > 0)
                records = records.Where(p => comparer.Compare(p.Key, keyOrPrefix) >= 0);
            records = records.OrderBy(p => p.Key, comparer);
            foreach (var pair in records)
                yield return (pair.Key, pair.Value);
        }

        public byte[] TryGet(byte[] key)
        {
            innerData.TryGetValue(key.EnsureNotNull(), out byte[] value);
            return value;
        }

        public bool Contains(byte[] key)
        {
            return innerData.ContainsKey(key.EnsureNotNull());
        }
    }
}


text:
package com.github.xeolite.enigma.machine;

import com.github.xeolite.enigma.io.OutputStyle;
import com.github.xeolite.enigma.plugboard.Plugboard;
import com.github.xeolite.enigma.reflector.StandardReflector;
import com.github.xeolite.enigma.rotor.StandardRotor;
import org.junit.Test;

import static com.github.xeolite.enigma.io.Letter.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class EnigmaM3Test {

    @Test
    public void enciphersText() {

        EnigmaM3 enigma = new EnigmaM3(
                StandardReflector.C,
                StandardRotor.I.withSetting(13).startAt(P),
                StandardRotor.II.withSetting(10).startAt(D),
                StandardRotor.III.withSetting(8).startAt(T),
                new Plugboard()
                        .connect(A, U)
                        .connect(F, O)
                        .connect(K, R)
                        .connect(I, S)
                        .connect(D, P)
                        .connect(X, W)
                    );

        assertThat(enigma.encipher(SOURCE_TEXT, OutputStyle.groupsOf(4)),
                is("ZYXH QZSW QGMJ RLNR KBRJ LNWI KPKU OZTF WDED BBHL ZEMQ TQBH XKBV QDTN VWWJ YKND UWCX CITA RQJS PLJC XJSU HVJC ZTCD BDIJ HPWC JRAZ CSZE IQXH VVEX QPYC MIMD WVNH WUQN IPZE ZXWY ZGFQ GTOX UXYT UJWV JFIV PCQQ EWBX DRAY RVMU OAFX RJQG LRUS RBHR JQ"));

    }

    private static final String SOURCE_TEXT =
            "And on the pedestal these words appear:\n" +
            "'My name is Ozymandias, king of kings:\n" +
            "Look on my works, ye Mighty, and despair!'\n" +
            "Nothing beside remains. Round the decay\n" +
            "Of that colossal wreck, boundless and bare\n" +
            "The lone and level sands stretch far away.";

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Index;
using Lucene.Net.Store;

namespace DotJEM.Json.Index.Storage.Snapshot;

public interface ISnapshotTarget
{
    ISnapshotWriter Open(IndexCommit commit);
}

public interface ISnapshotWriter : IDisposable
{
    void WriteFile(IndexInputStream stream);
    void WriteSegmentsFile(IndexInputStream stream);
}

public interface ISnapshotSource
{
    ISnapshot Open();
}

public interface ISnapshot : IDisposable
{
    long Generation { get; }
    ILuceneFile SegmentsFile { get; }
    IEnumerable<ILuceneFile> Files { get; }
}

public interface ILuceneFile
{
    string Name { get; }
    Stream Open();
}
    public class IndexOutputStream : Stream
    {
        public string FileName { get; }
        public IndexOutput IndexOutput { get; }

        public IndexOutputStream(string fileName, IndexOutput indexOutput)
        {
            FileName = fileName;
            IndexOutput = indexOutput;
        }

        public override void Flush()
        {
            IndexOutput.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    Position = offset;
                    break;
                case SeekOrigin.Current:
                    Position += offset;
                    break;
                case SeekOrigin.End:
                    Position = Length - offset;
                    break;
            }
            return Position;
        }

        public override void SetLength(long value)
        {
            IndexOutput.SetLength(value);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new InvalidOperationException("Cannot read from a writeonly stream.");
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            IndexOutput.WriteBytes(buffer, offset, count);
        }

        public override bool CanRead => false;
        public override bool CanSeek => true;
        public override bool CanWrite => true;
        public override long Length => IndexOutput.Length;

        public override long Position
        {
            get => IndexOutput.FilePointer;
            set => IndexOutput.Seek(value);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                IndexOutput.Dispose();
            }
            base.Dispose(disposing);
        }
    }

    public class IndexInputStream : Stream
    {
        public string FileName { get; }
        public IndexInput IndexInput { get; }

        public IndexInputStream(string fileName, IndexInput indexInput)
        {
            FileName = fileName;
            IndexInput = indexInput;
        }

        public override void Flush()
        {
            throw new InvalidOperationException("Cannot flush a readonly stream.");
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    Position = offset;
                    break;
                case SeekOrigin.Current:
                    Position += offset;
                    break;
                case SeekOrigin.End:
                    Position = Length - offset;
                    break;
            }
            return Position;
        }

        public override void SetLength(long value)
        {
            throw new InvalidOperationException("Cannot change length of a readonly stream.");
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int remaining = (int)(IndexInput.Length() - IndexInput.FilePointer);
            int readCount = Math.Min(remaining, count);
            IndexInput.ReadBytes(buffer, offset, readCount);
            return readCount;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new InvalidCastException("Cannot write to a readonly stream.");
        }

        public override bool CanRead => true;
        public override bool CanSeek => true;
        public override bool CanWrite => false;
        public override long Length => IndexInput.Length();

        public override long Position
        {
            get => IndexInput.FilePointer;
            set => IndexInput.Seek(value);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                IndexInput.Dispose();
            }
            base.Dispose(disposing);
        }
    }


text:
// LICENSE : MIT
"use strict";
const visit = require('unist-util-visit');
/**
 * Ignore node manager that manager ignored ranges.
 *
 */
export default class IgnoreNodeManger {
    constructor() {
        /**
         * @type {[number,number][]}
         * @private
         */
        this._ignoredRangeList = []
    }

    /**
     * |.......|
     * ^       ^
     * Ignored Range
     *
     *    |........|
     *    ^
     *  index
     * @param {number} index
     * @returns {boolean}
     */
    isIgnoredIndex(index) {
        return this._ignoredRangeList.some(range => {
            const [start, end] = range;
            return start <= index && index <= end;
        })
    }

    /**
     * @param {[number, number]} aRange
     * @returns {boolean}
     */
    isIgnoredRange(aRange) {
        const index = aRange[0];
        return this.isIgnoredIndex(index);
    }

    /**
     * @param {Object} node
     * @returns {boolean}
     */
    isIgnored(node) {
        const index = node.index;
        return this.isIgnoredIndex(index);
    }

    /**
     * add node to ignore range list
     * @param {TxtNode} node
     */
    ignore(node) {
        this.ignoreRange(node.range);
    }

    /**
     * add range to ignore range list
     * @param {[number, number]} range
     */
    ignoreRange(range) {
        this._ignoredRangeList.push(range);
    }

    /**
     * ignore children node of `node`,
     * if the children node has the type that is included in `ignoredNodeTypes`.
     * @param {TxtNode} targetNode
     * @param {string[]} ignoredNodeTypes
     */
    ignoreChildrenByTypes(targetNode, ignoredNodeTypes) {
        visit(targetNode, visitedNode => {
            if (ignoredNodeTypes.indexOf(visitedNode.type) !== -1) {
                this.ignore(visitedNode);
            }
        });
    }
}


text:
package net.sourceforge.ganttproject.time;

import java.util.Date;

import net.sourceforge.ganttproject.time.TimeUnit;
import net.sourceforge.ganttproject.time.TimeUnitGraph;
import net.sourceforge.ganttproject.time.TimeUnitGraph.Composition;

/**
 * Created by IntelliJ IDEA.
 * @author bard
 * Date: 01.02.2004
 */
public class TimeUnitImpl implements TimeUnit {
    private final String myName;
    private final TimeUnitGraph myGraph;
    private final TimeUnit myDirectAtomUnit;
    private TextFormatter myTextFormatter;

    public TimeUnitImpl(String name, TimeUnitGraph graph, TimeUnit directAtomUnit) {
        myName = name;
        myGraph = graph;
        myDirectAtomUnit = directAtomUnit;
    }

    public String getName() {
        return myName;
    }

    public boolean isConstructedFrom(TimeUnit atomUnit) {
        return myGraph.getComposition(this, atomUnit)!=null;
    }

    public int getAtomCount(TimeUnit atomUnit) {
        Composition composition = myGraph.getComposition(this, atomUnit);
        if (composition==null) {
            throw new RuntimeException("Failed to find a composition of time unit="+this+" from time unit="+atomUnit);
        }
        return composition.getAtomCount();
    }

    public TimeUnit getDirectAtomUnit() {
        return myDirectAtomUnit;
    }

    public String toString() {
    	return getName()+" hash="+hashCode();
    }

    public void setTextFormatter(TextFormatter formatter) {
        myTextFormatter = formatter;
    }

    public TimeUnitText format(Date baseDate) {
        return myTextFormatter==null ? new TimeUnitText("") : myTextFormatter.format(this, baseDate);
    }

    protected TextFormatter getTextFormatter() {
        return myTextFormatter;
    }

	public Date adjustRight(Date baseDate) {
		throw new UnsupportedOperationException("Time unit="+this+" doesnt support this operation");
	}

	public Date adjustLeft(Date baseDate) {
		throw new UnsupportedOperationException("Time unit="+this+" doesnt support this operation");
	}

	public Date jumpLeft(Date baseDate) {
		throw new UnsupportedOperationException("Time unit="+this+" doesnt support this operation");
	}

}


text:
<?php
/**
 * TV Widget Spanish lexicon topic
 *
 * @language es_MX
 * @package modx
 * @subpackage lexicon
 */
$_lang['attributes'] = 'Atributos';
$_lang['capitalize'] = 'Capitalizar';
$_lang['checkbox'] = 'Opciones Múltiples';
$_lang['class'] = 'Clase';
$_lang['combo_allowaddnewdata'] = 'Permitir Añadir Nuevos Artículos';
$_lang['combo_allowaddnewdata_desc'] = 'Cuando sea Si, permite añadir artículos que no existan en la lista.  El valor prefijado es No.';
$_lang['combo_forceselection'] = 'Forzar Selección a Lista';
$_lang['combo_forceselection_desc'] = 'Si se usa Type-Ahead, si esto está configurado a Si, sólo permite el ingreso de artículos en la lista.';
$_lang['combo_listempty_text'] = 'Vaciar Texto de Lista';
$_lang['combo_listempty_text_desc'] = 'Si Type-Ahead está activado, y el usario ingresa un valor que no esté en la lista, mostrar este texto.';
$_lang['combo_listwidth'] = 'Ancho de Lista';
$_lang['combo_listwidth_desc'] = 'El ancho, en pixeles, de la lista de menu desplegable.  El valor prefijado es el ancho del combobox.';
$_lang['combo_maxheight'] = 'Altura Máxima';
$_lang['combo_maxheight_desc'] = 'La altura máxima en pixeles de la lista desplegable antes de que las barras de navegación sean mostradas (valor prefijado es 300).';
$_lang['combo_stackitems'] = 'Encimar Artículos Seleccionados';
$_lang['combo_stackitems_desc'] = 'Cuando está configurado a Si, los artículos estarán encimados uno por línea.  El valor prefijado es No, el cual musetra los artículos en una línea.';
$_lang['combo_title'] = 'Encabezado de la Lista';
$_lang['combo_title_desc'] = 'Si se provee, un elemento de encabezado es creado conteniendo este texto y añadido a la parte de arriba de la lista desplegable.';
$_lang['combo_typeahead'] = 'Habilitar Type-Ahead';
$_lang['combo_typeahead_desc'] = 'Si está configuradoa Si, llenar y auto-seleccionar lo que falta del texto que se está ingresando después de un retrazo configurable (Retraso de Type-Ahead) si coincide con un valor conocido (el valor prefijado es No).';
$_lang['combo_typeahead_delay'] = 'Retrazo de Type-Ahead';
$_lang['combo_typeahead_delay_desc'] = 'El tiempo en milisegundos que se espera hasta que el texto Type-Ahead es mostrado si Type-Ahead está habilitado (el valor prefijado es 250).';
$_lang['date'] = 'Fecha';
$_lang['date_format'] = 'Formato de Fecha';
$_lang['date_use_current'] = 'Si no hay valor, usa fecha actual';
$_lang['default'] = 'Prefijado';
$_lang['delim'] = 'Separador';
$_lang['delimiter'] = 'Separador';
$_lang['disabled_dates'] = 'Disabled Dates';
$_lang['disabled_dates_desc'] = 'Una lista separada por comas de "fechas" a deshabilitar, como palabras.  Estas palabras serán usadas para construir una expresión regular dinámica así que son muy poderosas.  Algunos ejemplos:

- Deshabilitar estas fechas exactas: 2003-03-08,2003-09-16

- Deshabilitar estos días para cada año: 03-08,09-16

- Sólo coincide el principio (útil si estás usando años cortos): ^03-08

- Deshabilitar cada día en Marzo 2006: 03-..-2006

- Deshabilitar cada día en cada Marzo: ^03

Nota que el formato de las fechas incluido en la lista deberá coincidir exáctamente el formato configurado.  De manera que se soporten expresiones regulares, si estás usando un formato de fecha que tienen un ".", tendrás que escapar el punto cuando restrinjas fechas.';
$_lang['disabled_days'] = 'Días Deshabilitados';
$_lang['disabled_days_desc'] = 'Una lista separada por comas de los días a deshabilitar, basado en 0 (el valor prefijado es null).  Algunos ejemplos:

- Deshabilitar Domingo y Sábado: 0,6

- Deshabilitar días de la semana: 1,2,3,4,5';
$_lang['dropdown'] = 'Lista Desplegable';
$_lang['earliest_date'] = 'Fecha Más Temprana';
$_lang['earliest_date_desc'] = 'La fecha más temprana permitida que puede ser seleccionada.';
$_lang['earliest_time'] = 'Hora Más Temprana';
$_lang['earliest_time_desc'] = 'La hora más temprana permitida que puede ser seleccionada.';
$_lang['email'] = 'Email';
$_lang['file'] = 'Archivo';
$_lang['height'] = 'Altura';
$_lang['hidden'] = 'Oculto';
$_lang['htmlarea'] = 'Area de HTML';
$_lang['htmltag'] = 'Etiqueta HTML';
$_lang['image'] = 'Imagen';
$_lang['image_align'] = 'Alinear';
$_lang['image_align_list'] = 'ninguna,base,arriba,centro,abajo,arribatexto,abscentro,absabajo,izquierda,derecha';
$_lang['image_alt'] = 'Texto Alterno';
$_lang['image_allowedfiletypes'] = 'Extensiones de Archivo Permitidas';
$_lang['image_allowedfiletypes_desc'] = 'Si está configurado, restringirá los archivos mostrados a sólo las extensiones especificádas.  Por favor especifíca en una lista separada por comas, sin el .';
$_lang['image_basepath'] = 'Ruta Base';
$_lang['image_basepath_desc'] = 'La ruta del archivo a la que apunta la VdP de Imagen.  Si no está configurada, usará la configuración en filemanager_path, o la ruta base de MODX.  Puedes usar [[++base_path]], [[++core_path]] y [[++assets_path]] en este valor.';
$_lang['image_basepath_relative'] = 'Ruta Base Relativa';
$_lang['image_basepath_relative_desc'] = 'Si la configuración de la Ruta Base de arriba no es relativa a la ruta de instalación de MODX, configura esto a Si.';
$_lang['image_baseurl'] = 'URL Base';
$_lang['image_baseurl_desc'] = 'El URL de archivo al que apunta la VdP de Imagen.  Si no testá configurada, usará la configuración en filemanager_url setting, o el URL base de MODX.   Puedes usar [[++base_url]], [[++core_url]] y [[++assets_url]] en este valor.';
$_lang['image_baseurl_relative'] = 'Url Base Relativo';
$_lang['image_baseurl_relative_desc'] = 'Si la configuración del URL Base de arriba no es relativo al URL de instalación de MODX, configura esto a Si.';
$_lang['image_border_size'] = 'Tamaño de Borde';
$_lang['image_hspace'] = 'Espacio H';
$_lang['image_vspace'] = 'Espacio V';
$_lang['latest_date'] = 'Última Fecha';
$_lang['latest_date_desc'] = 'La última fecha permitida que puede ser seleccionada.';
$_lang['latest_time'] = 'Última Hora';
$_lang['latest_time_desc'] = 'La última hora permitida que puede ser seleccionada.';
$_lang['listbox'] = 'Lista (Sel. Sencilla)';
$_lang['listbox-multiple'] = 'Lista  (Sel. Múltiple)';
$_lang['lower_case'] = 'Minúsculas';
$_lang['max_length'] = 'Longitud Máxima';
$_lang['min_length'] = 'Longitud Mínima';
$_lang['name'] = 'Nombre';
$_lang['number'] = 'Número';
$_lang['number_allowdecimals'] = 'Permitir Decimales';
$_lang['number_allownegative'] = 'Permitar Negativos';
$_lang['number_decimalprecision'] = 'Precisión Decimal';
$_lang['number_decimalprecision_desc'] = 'La precisión máxima después del separador decimal (el valor prefijado es 2).';
$_lang['number_decimalseparator'] = 'Separador Decimal';
$_lang['number_decimalseparator_desc'] = 'Caracter(es) permitidos como el separador decimal (el valor prefijado es ".")';
$_lang['number_maxvalue'] = 'Valor Máximo';
$_lang['number_minvalue'] = 'Valor Mínimo';
$_lang['option'] = 'Lista (Radio)';
$_lang['parent_resources'] = 'Recursos Padre';
$_lang['radio_columns'] = 'Columnas';
$_lang['radio_columns_desc'] = 'El número de columnas en las que las opciones de radio son mostradas.';
$_lang['rawtext'] = 'Texto (obsoleto)';
$_lang['rawtextarea'] = 'Area de Texto (obsoleto)';
$_lang['required'] = 'Permitir Vacío';
$_lang['required_desc'] = 'Si se configura a No, MODX no permitirá al usuario guardar el Recurso hasta que un valor válido, no vacío ha sido ingresado.';
$_lang['resourcelist'] = 'Lista de Recursos';
$_lang['resourcelist_depth'] = 'Profundidad';
$_lang['resourcelist_depth_desc'] = 'Los niveles de profundidad que serán interrogados por la consulta para obtener la lista de Recursos. El valor prefijado es 10.';
$_lang['resourcelist_includeparent'] = 'Incluir Padres';
$_lang['resourcelist_includeparent_desc'] = 'Si está configurado a Si, incluir+a los Recursos nombrados en el campo Padres en la lista.';
$_lang['resourcelist_limit'] = 'Límite';
$_lang['resourcelist_limit_desc'] = 'El número de Recursos en la lista.  0 o vacío significa infinito.';
$_lang['resourcelist_parents'] = 'Padres';
$_lang['resourcelist_parents_desc'] = 'Una lista de IDs de los hijos para la lista.';
$_lang['resourcelist_where'] = 'Condiciones WHERE';
$_lang['resourcelist_where_desc'] = 'Un objeto JSON con las condiciones WHERE para filtrar la consulta que obtiene los Recursos de la lista. (No soporta búsqueda en VdP.)';
$_lang['richtext'] = 'Texto Formateado';
$_lang['sentence_case'] = 'Oraciones Capitalizadas';
$_lang['shownone'] = 'Permitir Selección Vacía';
$_lang['shownone_desc'] = 'Permitir al usuario seleccionar una selección vacía la cual es un valor vacío.';
$_lang['start_day'] = 'Día de Comienzo';
$_lang['start_day_desc'] = 'Índice del día en el cual la semana deberá comenzar, basado en 0 (el valor prefijado es 0, que es el Domingo)';
$_lang['string'] = 'Cadena de Caracteres';
$_lang['string_format'] = 'Formato de Cadena de Caracteres';
$_lang['style'] = 'Estilo';
$_lang['tag_id'] = 'ID de Etiqueta';
$_lang['tag_name'] = 'Nombre de Etiqueta';
$_lang['target'] = 'Objetivo';
$_lang['text'] = 'Texto';
$_lang['textarea'] = 'Area de Texto';
$_lang['textareamini'] = 'Area de Texto (Mini)';
$_lang['textbox'] = 'Caja de Texto';
$_lang['time_increment'] = 'Incremento en Tiempo';
$_lang['time_increment_desc'] = 'El número de minutos entre cada valor de tiempo en la lista (el valor prefijado es 15).';
$_lang['title'] = 'Título';
$_lang['upper_case'] = 'Mayúsculas';
$_lang['url'] = 'URL';
$_lang['url_display_text'] = 'Mostrar Texto';
$_lang['width'] = 'Ancho';