text:
#include <string.h>

#include "cec.h"
#include "test_util.h"

struct overflow_msg {
	struct cec_msg_transfer transfer;
	uint8_t overflow_detector;
} overflow_msg;
/* Ensure the overflow detector is located directly after the buffer */
BUILD_ASSERT(offsetof(struct overflow_msg, overflow_detector) ==
	     offsetof(struct cec_msg_transfer, buf) + MAX_CEC_MSG_LEN);

struct overflow_queue {
	struct cec_rx_queue queue;
	uint8_t overflow_detector[CEC_RX_BUFFER_SIZE];
} overflow_queue;
/* Ensure the overflow detector is located directly after the buffer */
BUILD_ASSERT(offsetof(struct overflow_queue, overflow_detector) ==
	     offsetof(struct cec_rx_queue, buf) + CEC_RX_BUFFER_SIZE);

static struct cec_rx_queue *queue;

/* Tests */
static int test_msg_overflow(void)
{
	int i;

	/* Overwrite the buffer by 1 byte */
	for (i = 0; i < (MAX_CEC_MSG_LEN + 1) * 8; i++) {
		cec_transfer_set_bit(&overflow_msg.transfer, 1);
		cec_transfer_inc_bit(&overflow_msg.transfer);
	}

	/* Make sure we actually wrote the whole buffer with ones */
	for (i = 0; i < MAX_CEC_MSG_LEN; i++)
		TEST_ASSERT(overflow_msg.transfer.buf[i] == 0xff);

	/* Verify that the attempt to overflow the buffer did not succeed */
	TEST_ASSERT(overflow_msg.overflow_detector == 0);

	/* The full indicator is when byte reaches MAX_CEC_MSG_LEN */
	TEST_ASSERT(overflow_msg.transfer.byte == MAX_CEC_MSG_LEN);

	/* Check that the indicator stays the same if we write another byte */
	for (i = 0; i < 8; i++) {
		cec_transfer_set_bit(&overflow_msg.transfer, 1);
		cec_transfer_inc_bit(&overflow_msg.transfer);
	}
	TEST_ASSERT(overflow_msg.transfer.byte == MAX_CEC_MSG_LEN);

	return EC_SUCCESS;
}

static int verify_no_queue_overflow(void)
{
	int i;

	for (i = 0; i < CEC_RX_BUFFER_SIZE; i++) {
		if (overflow_queue.overflow_detector[i] != 0)
			return EC_ERROR_OVERFLOW;
	}
	return EC_SUCCESS;
}

static void clear_queue(void)
{
	memset(queue, 0, sizeof(struct cec_rx_queue));
}

static int fill_queue(uint8_t *msg, int msg_size)
{
	int i;

	/*
	 * Fill the queue. Every push adds the message and one extra byte for
	 * the length field. The maximum data we can add is one less than
	 * CEC_RX_BUFFER_SIZE since write_pointer==read_pointer is used to
	 * indicate an empty buffer
	 */
	clear_queue();

	for (i = 0; i < (CEC_RX_BUFFER_SIZE - 1) / (msg_size + 1); i++)
		TEST_ASSERT(cec_rx_queue_push(queue, msg, msg_size) == 0);

	/* Now the queue should be full */
	TEST_ASSERT(cec_rx_queue_push(queue, msg, msg_size) ==
		    EC_ERROR_OVERFLOW);

	/* Verify nothing was written outside of the queue */
	TEST_ASSERT(verify_no_queue_overflow() == EC_SUCCESS);

	return EC_SUCCESS;
}

static int test_queue_overflow(void)
{
	uint8_t msg[CEC_RX_BUFFER_SIZE];

	memset(msg, 0xff, sizeof(msg));

	TEST_ASSERT(fill_queue(msg, 1) == EC_SUCCESS);
	TEST_ASSERT(fill_queue(msg, 2) == EC_SUCCESS);
	TEST_ASSERT(fill_queue(msg, 3) == EC_SUCCESS);
	TEST_ASSERT(fill_queue(msg, MAX_CEC_MSG_LEN) == EC_SUCCESS);

	return EC_SUCCESS;
}

void run_test(int argc, const char **argv)
{
	queue = &overflow_queue.queue;

	RUN_TEST(test_msg_overflow);

	RUN_TEST(test_queue_overflow);

	test_print_result();
}


text:
title: Spring Plugin
layout: default
summary: Analyzes spring files and adds any discovered classes to the imported packages.
---

redpajama_set_name: RedPajamaGithub


text:
goog.provide('foo.Example');

goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.classes');

/**
 * An example class of the Googkit project template.
 * @constructor
 */
foo.Example = function() {
};

/**
 * Shows a message 'it works'.
 */
foo.Example.prototype.showItWorks = function() {
  // Add 'works' css class if Closure Library works correctly
  goog.dom.classes.set(document.body, 'works');
};

/**
 * Shows a simple demo.
 */
foo.Example.prototype.demonstrate = function() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var expression = nums.join(' + ');
  var total = goog.array.reduce(nums, function(before, current) {
    return before + current;
  }, 0);

  var welcomeElem = goog.dom.getElementByClass('welcome');
  var text = expression + ' = ' + String(total);
  var newElem = goog.dom.createDom('pre', null, text);
  goog.dom.insertSiblingAfter(newElem, welcomeElem);
};

/**
 * Sample method.
 */
foo.Example.prototype.doSomething = function() {
  this.showItWorks();
  this.demonstrate();
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.intel.hibench</groupId>
    <artifactId>hadoopbench</artifactId>
    <version>6.1-SNAPSHOT</version>
  </parent>

  <groupId>com.intel.hibench.hadoopbench</groupId>
  <artifactId>mahout</artifactId>
  <packaging>jar</packaging>

  <properties>
    <repo1>http://archive.apache.org</repo1>
    <file1>dist/mahout/0.11.0/apache-mahout-distribution-0.11.0.tar.gz</file1>
    <checksum1>32bb8d9429671c651ff8233676739f1f</checksum1>
    <repo2>http://archive.cloudera.com</repo2>
    <file2>cdh5/cdh/5/mahout-0.9-cdh5.1.0.tar.gz</file2>
    <checksum2>aa953e0353ac104a22d314d15c88d78f</checksum2>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>com.googlecode.maven-download-plugin</groupId>
        <artifactId>download-maven-plugin</artifactId>
        <version>${download-maven-plugin.version}</version>
        <executions>
          <execution>
            <phase>process-sources</phase>
            <goals>
              <goal>wget</goal>
            </goals>
            <configuration>
              <url>${repo1}/${file1}</url>
              <md5>${checksum1}</md5>
            </configuration>
          </execution>
          <execution>
            <id>extra-download-execution</id>
            <phase>process-sources</phase>
            <goals>
              <goal>wget</goal>
            </goals>
            <configuration>
              <url>${repo2}/${file2}</url>
              <md5>${checksum2}</md5>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
namespace v8_inspector {
namespace {
using ::v8_inspector_protocol_encoding::span;
using ::v8_inspector_protocol_encoding::SpanFrom;
using IPEStatus = ::v8_inspector_protocol_encoding::Status;

bool IsCBORMessage(const StringView& msg) {
  return msg.is8Bit() && msg.length() >= 2 && msg.characters8()[0] == 0xd8 &&
         msg.characters8()[1] == 0x5a;
}

IPEStatus ConvertToCBOR(const StringView& state, std::vector<uint8_t>* cbor) {
  return state.is8Bit()
             ? ConvertJSONToCBOR(
                   span<uint8_t>(state.characters8(), state.length()), cbor)
             : ConvertJSONToCBOR(
                   span<uint16_t>(state.characters16(), state.length()), cbor);
}

std::unique_ptr<protocol::DictionaryValue> ParseState(const StringView& state) {
  std::vector<uint8_t> converted;
  span<uint8_t> cbor;
  if (IsCBORMessage(state))
    cbor = span<uint8_t>(state.characters8(), state.length());
  else if (ConvertToCBOR(state, &converted).ok())
    cbor = SpanFrom(converted);
  if (!cbor.empty()) {
    std::unique_ptr<protocol::Value> value =
        protocol::Value::parseBinary(cbor.data(), cbor.size());
    if (value) return protocol::DictionaryValue::cast(std::move(value));
  }
  return protocol::DictionaryValue::create();
}
}  // namespace

// static
bool V8InspectorSession::canDispatchMethod(const StringView& method) {
  return stringViewStartsWith(method,
                              protocol::Runtime::Metainfo::commandPrefix) ||
         stringViewStartsWith(method,
                              protocol::Debugger::Metainfo::commandPrefix) ||
         stringViewStartsWith(method,
                              protocol::Profiler::Metainfo::commandPrefix) ||
         stringViewStartsWith(
             method, protocol::HeapProfiler::Metainfo::commandPrefix) ||
         stringViewStartsWith(method,
                              protocol::Console::Metainfo::commandPrefix) ||
         stringViewStartsWith(method,
                              protocol::Schema::Metainfo::commandPrefix);
}

// static
int V8ContextInfo::executionContextId(v8::Local<v8::Context> context) {
  return InspectedContext::contextId(context);
}

std::unique_ptr<V8InspectorSessionImpl> V8InspectorSessionImpl::create(
    V8InspectorImpl* inspector, int contextGroupId, int sessionId,
    V8Inspector::Channel* channel, const StringView& state) {
  return std::unique_ptr<V8InspectorSessionImpl>(new V8InspectorSessionImpl(
      inspector, contextGroupId, sessionId, channel, state));
}

V8InspectorSessionImpl::V8InspectorSessionImpl(V8InspectorImpl* inspector,
                                               int contextGroupId,
                                               int sessionId,
                                               V8Inspector::Channel* channel,
                                               const StringView& savedState)
    : m_contextGroupId(contextGroupId),
      m_sessionId(sessionId),
      m_inspector(inspector),
      m_channel(channel),
      m_customObjectFormatterEnabled(false),
      m_dispatcher(this),
      m_state(ParseState(savedState)),
      m_runtimeAgent(nullptr),
      m_debuggerAgent(nullptr),
      m_heapProfilerAgent(nullptr),
      m_profilerAgent(nullptr),
      m_consoleAgent(nullptr),
      m_schemaAgent(nullptr) {
  m_state->getBoolean("use_binary_protocol", &use_binary_protocol_);

  m_runtimeAgent.reset(new V8RuntimeAgentImpl(
      this, this, agentState(protocol::Runtime::Metainfo::domainName)));
  protocol::Runtime::Dispatcher::wire(&m_dispatcher, m_runtimeAgent.get());

  m_debuggerAgent.reset(new V8DebuggerAgentImpl(
      this, this, agentState(protocol::Debugger::Metainfo::domainName)));
  protocol::Debugger::Dispatcher::wire(&m_dispatcher, m_debuggerAgent.get());

  m_profilerAgent.reset(new V8ProfilerAgentImpl(
      this, this, agentState(protocol::Profiler::Metainfo::domainName)));
  protocol::Profiler::Dispatcher::wire(&m_dispatcher, m_profilerAgent.get());

  m_heapProfilerAgent.reset(new V8HeapProfilerAgentImpl(
      this, this, agentState(protocol::HeapProfiler::Metainfo::domainName)));
  protocol::HeapProfiler::Dispatcher::wire(&m_dispatcher,
                                           m_heapProfilerAgent.get());

  m_consoleAgent.reset(new V8ConsoleAgentImpl(
      this, this, agentState(protocol::Console::Metainfo::domainName)));
  protocol::Console::Dispatcher::wire(&m_dispatcher, m_consoleAgent.get());

  m_schemaAgent.reset(new V8SchemaAgentImpl(
      this, this, agentState(protocol::Schema::Metainfo::domainName)));
  protocol::Schema::Dispatcher::wire(&m_dispatcher, m_schemaAgent.get());

  if (savedState.length()) {
    m_runtimeAgent->restore();
    m_debuggerAgent->restore();
    m_heapProfilerAgent->restore();
    m_profilerAgent->restore();
    m_consoleAgent->restore();
  }
}

V8InspectorSessionImpl::~V8InspectorSessionImpl() {
  discardInjectedScripts();
  m_consoleAgent->disable();
  m_profilerAgent->disable();
  m_heapProfilerAgent->disable();
  m_debuggerAgent->disable();
  m_runtimeAgent->disable();
  m_inspector->disconnect(this);
}

protocol::DictionaryValue* V8InspectorSessionImpl::agentState(
    const String16& name) {
  protocol::DictionaryValue* state = m_state->getObject(name);
  if (!state) {
    std::unique_ptr<protocol::DictionaryValue> newState =
        protocol::DictionaryValue::create();
    state = newState.get();
    m_state->setObject(name, std::move(newState));
  }
  return state;
}

std::unique_ptr<StringBuffer> V8InspectorSessionImpl::serializeForFrontend(
    std::unique_ptr<protocol::Serializable> message) {
  std::vector<uint8_t> cbor = message->serializeToBinary();
  if (use_binary_protocol_)
    return std::unique_ptr<StringBuffer>(
        new BinaryStringBuffer(std::move(cbor)));
  std::vector<uint8_t> json;
  IPEStatus status = ConvertCBORToJSON(SpanFrom(cbor), &json);
  DCHECK(status.ok());
  USE(status);
  String16 string16(reinterpret_cast<const char*>(json.data()), json.size());
  return StringBufferImpl::adopt(string16);
}

void V8InspectorSessionImpl::sendProtocolResponse(
    int callId, std::unique_ptr<protocol::Serializable> message) {
  m_channel->sendResponse(callId, serializeForFrontend(std::move(message)));
}

void V8InspectorSessionImpl::sendProtocolNotification(
    std::unique_ptr<protocol::Serializable> message) {
  m_channel->sendNotification(serializeForFrontend(std::move(message)));
}

void V8InspectorSessionImpl::fallThrough(
    int callId, const String16& method,
    const protocol::ProtocolMessage& message) {
  // There's no other layer to handle the command.
  UNREACHABLE();
}

void V8InspectorSessionImpl::flushProtocolNotifications() {
  m_channel->flushProtocolNotifications();
}

void V8InspectorSessionImpl::reset() {
  m_debuggerAgent->reset();
  m_runtimeAgent->reset();
  discardInjectedScripts();
}

void V8InspectorSessionImpl::discardInjectedScripts() {
  m_inspectedObjects.clear();
  int sessionId = m_sessionId;
  m_inspector->forEachContext(m_contextGroupId,
                              [&sessionId](InspectedContext* context) {
                                context->discardInjectedScript(sessionId);
                              });
}

Response V8InspectorSessionImpl::findInjectedScript(
    int contextId, InjectedScript*& injectedScript) {
  injectedScript = nullptr;
  InspectedContext* context =
      m_inspector->getContext(m_contextGroupId, contextId);
  if (!context) return Response::Error("Cannot find context with specified id");
  injectedScript = context->getInjectedScript(m_sessionId);
  if (!injectedScript) {
    injectedScript = context->createInjectedScript(m_sessionId);
    if (m_customObjectFormatterEnabled)
      injectedScript->setCustomObjectFormatterEnabled(true);
  }
  return Response::OK();
}

Response V8InspectorSessionImpl::findInjectedScript(
    RemoteObjectIdBase* objectId, InjectedScript*& injectedScript) {
  return findInjectedScript(objectId->contextId(), injectedScript);
}

void V8InspectorSessionImpl::releaseObjectGroup(const StringView& objectGroup) {
  releaseObjectGroup(toString16(objectGroup));
}

void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
  int sessionId = m_sessionId;
  m_inspector->forEachContext(
      m_contextGroupId, [&objectGroup, &sessionId](InspectedContext* context) {
        InjectedScript* injectedScript = context->getInjectedScript(sessionId);
        if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
      });
}

bool V8InspectorSessionImpl::unwrapObject(
    std::unique_ptr<StringBuffer>* error, const StringView& objectId,
    v8::Local<v8::Value>* object, v8::Local<v8::Context>* context,
    std::unique_ptr<StringBuffer>* objectGroup) {
  String16 objectGroupString;
  Response response = unwrapObject(toString16(objectId), object, context,
                                   objectGroup ? &objectGroupString : nullptr);
  if (!response.isSuccess()) {
    if (error) {
      String16 errorMessage = response.errorMessage();
      *error = StringBufferImpl::adopt(errorMessage);
    }
    return false;
  }
  if (objectGroup) *objectGroup = StringBufferImpl::adopt(objectGroupString);
  return true;
}

Response V8InspectorSessionImpl::unwrapObject(const String16& objectId,
                                              v8::Local<v8::Value>* object,
                                              v8::Local<v8::Context>* context,
                                              String16* objectGroup) {
  std::unique_ptr<RemoteObjectId> remoteId;
  Response response = RemoteObjectId::parse(objectId, &remoteId);
  if (!response.isSuccess()) return response;
  InjectedScript* injectedScript = nullptr;
  response = findInjectedScript(remoteId.get(), injectedScript);
  if (!response.isSuccess()) return response;
  response = injectedScript->findObject(*remoteId, object);
  if (!response.isSuccess()) return response;
  *context = injectedScript->context()->context();
  if (objectGroup) *objectGroup = injectedScript->objectGroupName(*remoteId);
  return Response::OK();
}

std::unique_ptr<protocol::Runtime::API::RemoteObject>
V8InspectorSessionImpl::wrapObject(v8::Local<v8::Context> context,
                                   v8::Local<v8::Value> value,
                                   const StringView& groupName,
                                   bool generatePreview) {
  return wrapObject(context, value, toString16(groupName), generatePreview);
}

std::unique_ptr<protocol::Runtime::RemoteObject>
V8InspectorSessionImpl::wrapObject(v8::Local<v8::Context> context,
                                   v8::Local<v8::Value> value,
                                   const String16& groupName,
                                   bool generatePreview) {
  InjectedScript* injectedScript = nullptr;
  findInjectedScript(InspectedContext::contextId(context), injectedScript);
  if (!injectedScript) return nullptr;
  std::unique_ptr<protocol::Runtime::RemoteObject> result;
  injectedScript->wrapObject(
      value, groupName,
      generatePreview ? WrapMode::kWithPreview : WrapMode::kNoPreview, &result);
  return result;
}

std::unique_ptr<protocol::Runtime::RemoteObject>
V8InspectorSessionImpl::wrapTable(v8::Local<v8::Context> context,
                                  v8::Local<v8::Object> table,
                                  v8::MaybeLocal<v8::Array> columns) {
  InjectedScript* injectedScript = nullptr;
  findInjectedScript(InspectedContext::contextId(context), injectedScript);
  if (!injectedScript) return nullptr;
  return injectedScript->wrapTable(table, columns);
}

void V8InspectorSessionImpl::setCustomObjectFormatterEnabled(bool enabled) {
  m_customObjectFormatterEnabled = enabled;
  int sessionId = m_sessionId;
  m_inspector->forEachContext(
      m_contextGroupId, [&enabled, &sessionId](InspectedContext* context) {
        InjectedScript* injectedScript = context->getInjectedScript(sessionId);
        if (injectedScript)
          injectedScript->setCustomObjectFormatterEnabled(enabled);
      });
}

void V8InspectorSessionImpl::reportAllContexts(V8RuntimeAgentImpl* agent) {
  m_inspector->forEachContext(m_contextGroupId,
                              [&agent](InspectedContext* context) {
                                agent->reportExecutionContextCreated(context);
                              });
}

void V8InspectorSessionImpl::dispatchProtocolMessage(
    const StringView& message) {
  using ::v8_inspector_protocol_encoding::span;
  using ::v8_inspector_protocol_encoding::SpanFrom;
  span<uint8_t> cbor;
  std::vector<uint8_t> converted_cbor;
  if (IsCBORMessage(message)) {
    use_binary_protocol_ = true;
    m_state->setBoolean("use_binary_protocol", true);
    cbor = span<uint8_t>(message.characters8(), message.length());
  } else {
    if (message.is8Bit()) {
      // We're ignoring the return value of these conversion functions
      // intentionally. It means the |parsed_message| below will be nullptr.
      ConvertJSONToCBOR(span<uint8_t>(message.characters8(), message.length()),
                        &converted_cbor);
    } else {
      ConvertJSONToCBOR(
          span<uint16_t>(message.characters16(), message.length()),
          &converted_cbor);
    }
    cbor = SpanFrom(converted_cbor);
  }
  int callId;
  std::unique_ptr<protocol::Value> parsed_message =
      protocol::Value::parseBinary(cbor.data(), cbor.size());
  String16 method;
  if (m_dispatcher.parseCommand(parsed_message.get(), &callId, &method)) {
    // Pass empty string instead of the actual message to save on a conversion.
    // We're allowed to do so because fall-through is not implemented.
    m_dispatcher.dispatch(callId, method, std::move(parsed_message),
                          protocol::ProtocolMessage());
  }
}

std::vector<uint8_t> V8InspectorSessionImpl::state() {
  std::vector<uint8_t> out;
  m_state->writeBinary(&out);
  return out;
}

std::vector<std::unique_ptr<protocol::Schema::API::Domain>>
V8InspectorSessionImpl::supportedDomains() {
  std::vector<std::unique_ptr<protocol::Schema::Domain>> domains =
      supportedDomainsImpl();
  std::vector<std::unique_ptr<protocol::Schema::API::Domain>> result;
  for (size_t i = 0; i < domains.size(); ++i)
    result.push_back(std::move(domains[i]));
  return result;
}

std::vector<std::unique_ptr<protocol::Schema::Domain>>
V8InspectorSessionImpl::supportedDomainsImpl() {
  std::vector<std::unique_ptr<protocol::Schema::Domain>> result;
  result.push_back(protocol::Schema::Domain::create()
                       .setName(protocol::Runtime::Metainfo::domainName)
                       .setVersion(protocol::Runtime::Metainfo::version)
                       .build());
  result.push_back(protocol::Schema::Domain::create()
                       .setName(protocol::Debugger::Metainfo::domainName)
                       .setVersion(protocol::Debugger::Metainfo::version)
                       .build());
  result.push_back(protocol::Schema::Domain::create()
                       .setName(protocol::Profiler::Metainfo::domainName)
                       .setVersion(protocol::Profiler::Metainfo::version)
                       .build());
  result.push_back(protocol::Schema::Domain::create()
                       .setName(protocol::HeapProfiler::Metainfo::domainName)
                       .setVersion(protocol::HeapProfiler::Metainfo::version)
                       .build());
  result.push_back(protocol::Schema::Domain::create()
                       .setName(protocol::Schema::Metainfo::domainName)
                       .setVersion(protocol::Schema::Metainfo::version)
                       .build());
  return result;
}

void V8InspectorSessionImpl::addInspectedObject(
    std::unique_ptr<V8InspectorSession::Inspectable> inspectable) {
  m_inspectedObjects.insert(m_inspectedObjects.begin(), std::move(inspectable));
  if (m_inspectedObjects.size() > kInspectedObjectBufferSize)
    m_inspectedObjects.resize(kInspectedObjectBufferSize);
}

V8InspectorSession::Inspectable* V8InspectorSessionImpl::inspectedObject(
    unsigned num) {
  if (num >= m_inspectedObjects.size()) return nullptr;
  return m_inspectedObjects[num].get();
}

void V8InspectorSessionImpl::schedulePauseOnNextStatement(
    const StringView& breakReason, const StringView& breakDetails) {
  m_debuggerAgent->schedulePauseOnNextStatement(
      toString16(breakReason),
      protocol::DictionaryValue::cast(
          protocol::StringUtil::parseJSON(breakDetails)));
}

void V8InspectorSessionImpl::cancelPauseOnNextStatement() {
  m_debuggerAgent->cancelPauseOnNextStatement();
}

void V8InspectorSessionImpl::breakProgram(const StringView& breakReason,
                                          const StringView& breakDetails) {
  m_debuggerAgent->breakProgram(
      toString16(breakReason),
      protocol::DictionaryValue::cast(
          protocol::StringUtil::parseJSON(breakDetails)));
}

void V8InspectorSessionImpl::setSkipAllPauses(bool skip) {
  m_debuggerAgent->setSkipAllPauses(skip);
}

void V8InspectorSessionImpl::resume() { m_debuggerAgent->resume(); }

void V8InspectorSessionImpl::stepOver() { m_debuggerAgent->stepOver(); }

std::vector<std::unique_ptr<protocol::Debugger::API::SearchMatch>>
V8InspectorSessionImpl::searchInTextByLines(const StringView& text,
                                            const StringView& query,
                                            bool caseSensitive, bool isRegex) {
  // TODO(dgozman): search may operate on StringView and avoid copying |text|.
  std::vector<std::unique_ptr<protocol::Debugger::SearchMatch>> matches =
      searchInTextByLinesImpl(this, toString16(text), toString16(query),
                              caseSensitive, isRegex);
  std::vector<std::unique_ptr<protocol::Debugger::API::SearchMatch>> result;
  for (size_t i = 0; i < matches.size(); ++i)
    result.push_back(std::move(matches[i]));
  return result;
}

}  // namespace v8_inspector


text:
Before do
  default_url_options[:protocol] = 'https'
end

Before do
  Location.create!(code: 'GB', name: 'United Kingdom')
end

Before do
  stub_api_request_for("SW1A1AA").to_return(api_response(:ok, "london_and_westminster"))
  stub_api_request_for("SW149RQ").to_return(api_response(:ok, "no_results"))
end

Before do
  RateLimit.create!(
    burst_rate: 10, burst_period: 60,
    sustained_rate: 20, sustained_period: 300,
    allowed_domains: "example.com", allowed_ips: "127.0.0.1"
  )
end

After do
  Site.reload
  Parliament.reload
end

Before('@admin') do
  Capybara.app_host = 'https://moderate.petition.parliament.uk'
  Capybara.default_host = 'https://moderate.petition.parliament.uk'
end

Before('~@admin') do
  Capybara.app_host = 'https://petition.parliament.uk'
  Capybara.default_host = 'https://petition.parliament.uk'
end


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using car_management.Common;
using car_management.View;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;

namespace car_management.ViewModel
{
    public class CarSelectionViewModel : ViewModelBase
    {
        public CarSelectionViewModel()
        {
            if (IsInDesignMode)
            {

            }
            else
            {

            }
        }
        public void RaisePropertyChanged()
        {
            RaisePropertyChanged(() => CarViewModels);
        }

        public ObservableCollection<CarViewModel> CarViewModels
        {
            get
            {
                if (IsInDesignMode)
                {
                    return new ObservableCollection<CarViewModel>() { new CarViewModel(null, this), new CarViewModel(null, this) };
                }
                else
                {
                    ObservableCollection<CarViewModel> cars = new ObservableCollection<CarViewModel>();
                    DataManager.Instance.Cars.Cars.ForEach(c => cars.Add(new CarViewModel(c, this)));
                    return cars;
                }
            }
        }

        public ICommand LoadCarsCommand
        {
            get
            {
                return new RelayCommand(LoadCars);
            }
        }

        void LoadCars()
        {
            string filePath = DataManager.Instance.GetXmlDataFilePath();
            if (!string.IsNullOrEmpty(filePath))
            {
                Project project = DataManager.Instance.LoadProject();
                project.XmlDatabaseFilePath = filePath;
                DataManager.Instance.SaveProject(project);
                DataManager.Instance.LoadCars();
                RaisePropertyChanged(() => CarViewModels);
            }

        }

        public ICommand AddCarCommand
        {
            get
            {
                return new RelayCommand(AddCar);
            }
        }

        void AddCar()
        {
            NameWindow window = new NameWindow();
            window.Owner = Application.Current.MainWindow;
            List<string> notvalid = DataManager.Instance.Cars.Cars.Select(c => c.Name).ToList();
            string startname = "newCar";
            int i = 1;
            string name = startname;
            while(notvalid.Contains(name))
            {
                name = startname + i;
                i++;
            }
            NameWindowModel nameVM = new NameWindowModel(notvalid,name);
            window.DataContext = nameVM;
            if ((bool)window.ShowDialog())
            {
                DataManager.Instance.Cars.Cars.Add(new Car() { Name = nameVM.Name });
                RaisePropertyChanged(() => CarViewModels);
                DataManager.Instance.SaveCars();
            }
        }

    }
}


text:
var quarter = function(number) {
  return number / 4;
}

if (!process.argv[2]) {
  console.log("Usage: quarterIT #");
} else {
  input = process.argv[2];
  console.log(quarter(input));
}


text:
import ApiClient from './ApiClient'
import {
    ORGANIZE_ADD,
    ORGANIZE_EDIT,
    ORGANIZE_List,
    ORGANIZE_GET,
    ORGANIZE_INFO
} from '../constants/api'

export function get(params) {
    return ApiClient.get(ORGANIZE_GET, params)
}

export function info(params) {
    return ApiClient.get(ORGANIZE_INFO, params)
}

export function edit(params) {
    return ApiClient.post(ORGANIZE_EDIT, params, { needAuth: true })
}

export function list(params) {
    return ApiClient.get(ORGANIZE_List, params)
}

export function add(params) {
    return ApiClient.post(ORGANIZE_ADD, params, { needAuth: true })
}


text:
#include <bl_common.h>
#include <console.h>
#include <debug.h>
#include <platform_tsp.h>
#include <xlat_tables.h>
#include <plat_arm.h>
#include "../zynqmp_def.h"
#include "../zynqmp_private.h"

/*
 * The next 3 constants identify the extents of the code & RO data region and
 * the limit of the BL32 image. These addresses are used by the MMU setup code
 * and therefore they must be page-aligned.  It is the responsibility of the
 * linker script to ensure that __RO_START__, __RO_END__ & & __BL32_END__
 * linker symbols refer to page-aligned addresses.
 */
#define BL32_RO_BASE (unsigned long)(&__RO_START__)
#define BL32_RO_LIMIT (unsigned long)(&__RO_END__)
#define BL32_END (unsigned long)(&__BL32_END__)

#if USE_COHERENT_MEM
/*
 * The next 2 constants identify the extents of the coherent memory region.
 * These addresses are used by the MMU setup code and therefore they must be
 * page-aligned.  It is the responsibility of the linker script to ensure that
 * __COHERENT_RAM_START__ and __COHERENT_RAM_END__ linker symbols refer to
 * page-aligned addresses.
 */
#define BL32_COHERENT_RAM_BASE (unsigned long)(&__COHERENT_RAM_START__)
#define BL32_COHERENT_RAM_LIMIT (unsigned long)(&__COHERENT_RAM_END__)
#endif

/*******************************************************************************
 * Initialize the UART
 ******************************************************************************/
void tsp_early_platform_setup(void)
{
	/*
	 * Initialize a different console than already in use to display
	 * messages from TSP
	 */
	console_init(ZYNQMP_UART0_BASE, zynqmp_get_uart_clk(),
		     ZYNQMP_UART_BAUDRATE);

	/* Initialize the platform config for future decision making */
	zynqmp_config_setup();
}

/*******************************************************************************
 * Perform platform specific setup placeholder
 ******************************************************************************/
void tsp_platform_setup(void)
{
	plat_arm_gic_driver_init();
	plat_arm_gic_init();
}

/*******************************************************************************
 * Perform the very early platform specific architectural setup here. At the
 * moment this is only intializes the MMU
 ******************************************************************************/
void tsp_plat_arch_setup(void)
{
	arm_configure_mmu_el1(BL32_RO_BASE,
			      (BL32_END - BL32_RO_BASE),
			      BL32_RO_BASE,
			      BL32_RO_LIMIT
#if USE_COHERENT_MEM
			      , BL32_COHERENT_RAM_BASE,
			      BL32_COHERENT_RAM_LIMIT
#endif
			      );
}


text:
import logging

class HtmlSource:

    def __init__(self, src, manualDependecy=""):
        self._src = src
        self.indentation = 0
        self.fileExtension = src.split(".")[-1]
        self.manualDependency = manualDependecy
        self.hasRendered = False

    def setSource(self, src):
        self._src = src
        self.hasRendered = False

    def render(self):

        self.hasRendered = True

        if self.manualDependency == "":

            if self.fileExtension == "css":
                return "rel=\"stylesheet\" type=\"text/css\" href=\"" + self._src + "\">"
            elif self.fileExtension == "js":
                return "<script src=\"" + self._src + "\"></script>"
            else:
                self.hasRendered = False
                raise Exception("This generator is still quite stupid and doesn't know about the " + self.fileExtension + ". "
                                "Feel free to add your own syntax to the code for your own "
                                "type of dependency.\nIf you just want to add a dependency the quick and dirty way, add it to "
                                "manualDependency like this:\nweirdDependency = HtmlDependency(None, '<script src=\"file.js\"></script>')\n"
                                "Then call dependency.render()")
        else:
            return self.manualDependency


text:
package ai.subut.kurjun.metadata.storage.nosql;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.datastax.driver.core.Session;

import ai.subut.kurjun.common.service.KurjunContext;

import static org.junit.Assert.*;
import static org.mockito.Mockito.when;

@RunWith( MockitoJUnitRunner.class )
public class NoSqlPackageMetadataStoreFactoryImplTest
{
    private NoSqlPackageMetadataStoreFactoryImpl storeFactory;

    @Mock
    CassandraSessionProvider sessionProvider;

    @Mock
    KurjunContext kurjunContext;

    @Mock
    Session session;

    @Before
    public void setUp() throws Exception
    {
        storeFactory = new NoSqlPackageMetadataStoreFactoryImpl( sessionProvider );
    }

    @Test
    public void create() throws Exception
    {
        // mock
        when( sessionProvider.get() ).thenReturn( session );
        when( kurjunContext.getName() ).thenReturn( "public" );

        assertNotNull( storeFactory.create( kurjunContext ) );
    }
}


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;

/**
 * DescribeImportSnapshotTasksRequest Marshaller
 */

public class DescribeImportSnapshotTasksRequestMarshaller
        implements
        Marshaller<Request<DescribeImportSnapshotTasksRequest>, DescribeImportSnapshotTasksRequest> {

    public Request<DescribeImportSnapshotTasksRequest> marshall(
            DescribeImportSnapshotTasksRequest describeImportSnapshotTasksRequest) {

        if (describeImportSnapshotTasksRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<DescribeImportSnapshotTasksRequest> request = new DefaultRequest<DescribeImportSnapshotTasksRequest>(
                describeImportSnapshotTasksRequest, "AmazonEC2");
        request.addParameter("Action", "DescribeImportSnapshotTasks");
        request.addParameter("Version", "2015-10-01");
        request.setHttpMethod(HttpMethodName.POST);

        com.amazonaws.internal.SdkInternalList<String> importTaskIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeImportSnapshotTasksRequest
                .getImportTaskIds();
        if (!importTaskIdsList.isEmpty()
                || !importTaskIdsList.isAutoConstruct()) {
            int importTaskIdsListIndex = 1;

            for (String importTaskIdsListValue : importTaskIdsList) {
                if (importTaskIdsListValue != null) {
                    request.addParameter("ImportTaskId."
                            + importTaskIdsListIndex,
                            StringUtils.fromString(importTaskIdsListValue));
                }
                importTaskIdsListIndex++;
            }
        }

        if (describeImportSnapshotTasksRequest.getNextToken() != null) {
            request.addParameter("NextToken", StringUtils
                    .fromString(describeImportSnapshotTasksRequest
                            .getNextToken()));
        }

        if (describeImportSnapshotTasksRequest.getMaxResults() != null) {
            request.addParameter("MaxResults", StringUtils
                    .fromInteger(describeImportSnapshotTasksRequest
                            .getMaxResults()));
        }

        com.amazonaws.internal.SdkInternalList<Filter> filtersList = (com.amazonaws.internal.SdkInternalList<Filter>) describeImportSnapshotTasksRequest
                .getFilters();
        if (!filtersList.isEmpty() || !filtersList.isAutoConstruct()) {
            int filtersListIndex = 1;

            for (Filter filtersListValue : filtersList) {

                if (filtersListValue.getName() != null) {
                    request.addParameter("Filters." + filtersListIndex
                            + ".Name",
                            StringUtils.fromString(filtersListValue.getName()));
                }

                com.amazonaws.internal.SdkInternalList<String> valuesList = (com.amazonaws.internal.SdkInternalList<String>) filtersListValue
                        .getValues();
                if (!valuesList.isEmpty() || !valuesList.isAutoConstruct()) {
                    int valuesListIndex = 1;

                    for (String valuesListValue : valuesList) {
                        if (valuesListValue != null) {
                            request.addParameter("Filters." + filtersListIndex
                                    + ".Value." + valuesListIndex,
                                    StringUtils.fromString(valuesListValue));
                        }
                        valuesListIndex++;
                    }
                }
                filtersListIndex++;
            }
        }

        return request;
    }

}


text:
{% extends "events/event_base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% load tiny_hands_pac_utils %}

{% block event_content %}
{% include "utils/includes/social_share.html" %}

{{ self.title }}

                 {% if self.image_items %}
                    {% image image_items width-200 %}
                 {% endif %}

Starts on: {{ self.date_from|date:"j F Y" }}

                 {% if self.date_to %}

Ends on: {{ self.date_to|date:"j F Y" }}

                 {% endif %}

                 {% if self.time_from %}

Time: {{ self.time_from|time_display }}
                 {% endif %}

                 {% if self.time_to %}
                    to {{ self.time_to|time_display }}

                 {% endif %}

                 {% if self.location %}

Location: {{ self.location }}

                 {% endif %}

{% include "events/includes/events_body.html" with body=self.body only %}

                 {% if self.audience %}

Audience:
                 {{ self.get_audience_display }}

                 {% endif %}

                 {% if self.cost %}

Cost: {{ self.cost|safe }}

                 {% endif %}

                 {% if self.signup_link %}

Sign up: {{ self.signup_link }}

                 {% endif %}

                 {% with self.speakers.all as speakers %}
                 {% if speakers %}

Speaker

                 {% for speaker in speakers %}
                 {% cycle '
' '' '' %} {# Open row div before first speaker then every 3 loops #}

                         {% if speaker.link %}

                             {% endif %}

                             {% if speaker.image %}
                             {% image speaker.image height-140 %}
                             {% endif %}

{{ speaker.name_display }}

                             {% if speaker.link %}

                         {% endif %}

                     {% cycle '' '' '
' %} {# Close row div before every 3rd speaker #}
                 {% endfor %}
                 {% if not speakers|length|divisibleby:'3' %}
{% endif %} {# Last close of row div if speakers list not exactly divisble by 3 #}
             {% endif %}
             {% endwith %}

  Add to calendar

{% endblock %}


text:
package org.springframework.boot.convert;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;

/**
 * Annotation that can be used to change the default unit used when converting a
 * {@link DataSize}.
 *
 * @author Stephane Nicoll
 * @since 2.1.0
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSizeUnit {

	/**
	 * The {@link DataUnit} to use if one is not specified.
	 * @return the data unit
	 */
	DataUnit value();

}


text:
local SoftMin, parent = torch.class('nn.SoftMin', 'nn.Module')

function SoftMin:updateOutput(input)
   self.mininput = self.mininput or input.new()
   self.mininput:resizeAs(input):copy(input):mul(-1)
   input.THNN.SoftMax_updateOutput(
      self.mininput:cdata(),
      self.output:cdata()
   )
   return self.output
end

function SoftMin:updateGradInput(input, gradOutput)
   self.mininput = self.mininput or input.new()
   self.mininput:resizeAs(input):copy(input):mul(-1)

   input.THNN.SoftMax_updateGradInput(
      self.mininput:cdata(),
      gradOutput:cdata(),
      self.gradInput:cdata(),
      self.output:cdata()
   )

   self.gradInput:mul(-1)
   return self.gradInput
end

function SoftMin:clearState()
   if self.mininput then self.mininput:set() end
   return parent.clearState(self)
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Sys
    {
        internal enum AccessMode : int
        {
            F_OK = 0,   /* Check for existence */
            X_OK = 1,   /* Check for execute */
            W_OK = 2,   /* Check for write */
            R_OK = 4,   /* Check for read */
        }

        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Access", SetLastError = true)]
        internal static extern int Access(string path, AccessMode mode);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ml.shifu</groupId>
    <artifactId>shifu</artifactId>
    <version>0.2.6</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.platform>2.0.0</version.platform>
        <siteRoot>site</siteRoot>
        <siteDeployUrl>siteAssets</siteDeployUrl>
        <rpmDisabled>true</rpmDisabled>
        <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
        <powermock.version>1.5.1</powermock.version>
    </properties>
    <scm>
        <developerConnection>scm:git:https://github.com/shifuml/shifu.git</developerConnection>
        <connection>scm:git:https://github.com/shifuml/shifu.git</connection>
        <url>https://github.com/shifuml/shifu.git</url>
        <tag>shifu-0.2.6</tag>
    </scm>
    <dependencies>
        <dependency>
            <groupId>jline</groupId>
            <artifactId>jline</artifactId>
            <version>0.9.9</version>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr-runtime</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.encog</groupId>
            <artifactId>encog-core</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-actor_2.10</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>de.bwaldvogel</groupId>
            <artifactId>liblinear</artifactId>
            <version>1.92</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-jexl</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>com.clearspring.analytics</groupId>
            <artifactId>stream</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-testng</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-easymock</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
            <scope>test</scope>
        </dependency>
        <!-- pmml related jars -->
        <dependency>
            <groupId>org.jpmml</groupId>
            <artifactId>pmml-model</artifactId>
            <version>1.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.jpmml</groupId>
            <artifactId>pmml-schema</artifactId>
            <version>1.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.jpmml</groupId>
            <artifactId>pmml-evaluator</artifactId>
            <version>1.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.6</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifest>
                            <mainClass>ml.shifu.shifu.util.ShifuCLI</mainClass>
                        </manifest>
                        <manifestEntries>
                            <vendor>PayPal</vendor>
                            <title>Shifu</title>
                            <version>${project.version}</version>
                            <timestamp>${maven.build.timestamp}</timestamp>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <configuration>
                    <releaseProfiles>release-sign-artifacts</releaseProfiles>
                </configuration>
                <version>2.5</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <configuration>
                    <show>protected</show>
                    <locale>en_US</locale>
                    <docencoding>UTF-8</docencoding>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>site</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.7</version>
                <executions>
                    <execution>
                        <id>default-deploy</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>rpm-maven-plugin</artifactId>
                <version>2.1-alpha-3</version>
                <executions>
                    <execution>
                        <id>attach-rpm</id>
                        <goals>
                            <goal>attached-rpm</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <disabled>${rpmDisabled}</disabled>
                    <copyright>2014 PayPal</copyright>
                    <distribution>PayPal 2014</distribution>
                    <group>Development/Tools</group>
                    <packager>Paypal</packager>
                    <prefix>/usr/local</prefix>
                    <changelogFile>src/changelog</changelogFile>
                    <defineStatements>
                        <defineStatement>_unpackaged_files_terminate_build 0</defineStatement>
                    </defineStatements>
                    <mappings>
                        <mapping>
                            <directory>/usr/local/bin/shifu/bin</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <source>
                                    <location>src/main/bash</location>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin/shifu/lib</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <dependency />
                            <sources>
                                <source>
                                    <location>target</location>
                                    <includes>
                                        <include>*.jar</include>
                                    </includes>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin/shifu/scripts</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <source>
                                    <location>src/main/pig</location>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin/shifu/common</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <source>
                                    <location>src/test/resources/common</location>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin/shifu/example</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <source>
                                    <location>src/test/resources/example</location>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin/shifu/conf</directory>
                            <configuration>true</configuration>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <source>
                                    <location>src/main/resources/conf</location>
                                </source>
                            </sources>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/log/shifu</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                        </mapping>
                        <mapping>
                            <directory>/usr/local/bin</directory>
                            <filemode>777</filemode>
                            <username>root</username>
                            <groupname>root</groupname>
                            <sources>
                                <softlinkSource>
                                    <location>/usr/local/bin/shifu/bin/shifu</location>
                                    <destination>shifu</destination>
                                </softlinkSource>
                            </sources>
                        </mapping>
                    </mappings>
                    <preinstallScriptlet>
                        <script>echo "shifu installing now"</script>
                    </preinstallScriptlet>
                    <postinstallScriptlet>
                        <script>echo "shifu installed"</script>
                    </postinstallScriptlet>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <distributionManagement>
        <repository>
            <id>libs-releases</id>
            <url>${releaseUrl}</url>
        </repository>
        <snapshotRepository>
            <uniqueVersion>false</uniqueVersion>
            <id>libs-snapshots</id>
            <url>${snapshotUrl}</url>
        </snapshotRepository>
        <site>
            <id>${project.artifactId}.site</id>
            <name>${project.name} Website</name>
            <url>${siteDeployUrl}</url>
        </site>
    </distributionManagement>
    <profiles>
        <!-- For hadoop 0.20.2 cloudera version -->
        <profile>
            <id>cdh-20</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <platform.version>cdh-20</platform.version>
            </properties>
            <repositories>
                <repository>
                    <id>Cloudera CDH</id>
                    <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
                </repository>
            </repositories>
            <dependencies>
                <dependency>
                    <groupId>org.apache.pig</groupId>
                    <artifactId>pig</artifactId>
                    <version>0.10.0</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-core</artifactId>
                    <version>0.20.2-cdh3u5</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.apache.hadoop.thirdparty.guava</groupId>
                            <artifactId>guava</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>ml.shifu</groupId>
                    <artifactId>guagua-mapreduce</artifactId>
                    <version>0.7.1</version>
                    <classifier>hadoop1</classifier>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.3</version>
                        <executions>
                            <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptors>
                                        <descriptor>assembly-hadoop1.xml</descriptor>
                                    </descriptors>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <!-- Release and Sign -->
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <property>
                    <name>performRelease</name>
                    <value>false</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.1</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.3</version>
                        <executions>
                            <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptors>
                                        <descriptor>assembly-hadoop1.xml</descriptor>
                                    </descriptors>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <repositories>
                <repository>
                    <id>Cloudera CDH</id>
                    <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
                </repository>
            </repositories>
            <dependencies>
                <dependency>
                    <groupId>org.apache.pig</groupId>
                    <artifactId>pig</artifactId>
                    <version>0.10.0</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-core</artifactId>
                    <version>0.20.2-cdh3u5</version>
                </dependency>
                <dependency>
                    <groupId>ml.shifu</groupId>
                    <artifactId>guagua-mapreduce</artifactId>
                    <version>0.7.1</version>
                    <classifier>hadoop1</classifier>
                </dependency>
            </dependencies>
            <properties>
                <maven.test.skip>true</maven.test.skip>
            </properties>
        </profile>
        <!-- For hadoop 2.2.0 cluster -->
        <profile>
            <id>hdp-yarn</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <platform.version>hdp-yarn</platform.version>
            </properties>
            <repositories>
                <repository>
                    <id>HortonWorks HDP Local</id>
                    <url>http://repo.hortonworks.com/service/local/repositories/releases/content/</url>
                </repository>
                <repository>
                    <id>HortonWorks HDP</id>
                    <url>http://repo.hortonworks.com/nexus/content/repositories/releases</url>
                </repository>
            </repositories>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.3</version>
                        <executions>
                            <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptors>
                                        <descriptor>assembly-hadoop2.xml</descriptor>
                                    </descriptors>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-hdfs</artifactId>
                    <version>2.4.0.2.1.2.0-402</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-common</artifactId>
                    <version>2.4.0.2.1.2.0-402</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-mapreduce-client-core</artifactId>
                    <version>2.4.0.2.1.2.0-402</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.pig</groupId>
                    <artifactId>pig</artifactId>
                    <version>0.12.1.2.1.2.0-402</version>
                </dependency>
                <dependency>
                    <groupId>joda-time</groupId>
                    <artifactId>joda-time</artifactId>
                    <version>2.3</version>
                </dependency>
                <dependency>
                    <groupId>dk.brics.automaton</groupId>
                    <artifactId>automaton</artifactId>
                    <version>1.11-8</version>
                </dependency>
                <dependency>
                    <groupId>ml.shifu</groupId>
                    <artifactId>guagua-mapreduce</artifactId>
                    <version>0.7.1</version>
                    <classifier>hadoop2</classifier>
                </dependency>
                <dependency>
                    <groupId>io.netty</groupId>
                    <artifactId>netty</artifactId>
                    <version>3.6.2.Final</version>
                </dependency>
            </dependencies>
        </profile>
        <!-- For hadoop 2.2.4 cluster -->
        <profile>
            <id>hdp-yarn-2.2.4</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <platform.version>hdp-yarn-2.2.4</platform.version>
            </properties>
            <repositories>
                <repository>
                    <id>HortonWorks HDP Local</id>
                    <url>http://repo.hortonworks.com/service/local/repositories/releases/content/</url>
                </repository>
                <repository>
                    <id>HortonWorks HDP</id>
                    <url>http://repo.hortonworks.com/nexus/content/repositories/releases</url>
                </repository>
            </repositories>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.3</version>
                        <executions>
                            <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptors>
                                        <descriptor>assembly-hadoop2.xml</descriptor>
                                    </descriptors>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-hdfs</artifactId>
                    <version>2.6.0.2.2.4.0-2633</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty</artifactId>
                        </exclusion>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty-util</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-common</artifactId>
                    <version>2.6.0.2.2.4.0-2633</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty</artifactId>
                        </exclusion>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty-util</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-mapreduce-client-core</artifactId>
                    <version>2.6.0.2.2.4.0-2633</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty</artifactId>
                        </exclusion>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty-util</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.apache.pig</groupId>
                    <artifactId>pig</artifactId>
                    <version>0.14.0.2.2.4.0-2633</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty</artifactId>
                        </exclusion>
                        <exclusion>
                            <groupId>org.mortbay.jetty</groupId>
                            <artifactId>jetty-util</artifactId>
                        </exclusion>
                    </exclusions>
                    <classifier>h2</classifier>
                </dependency>
                <dependency>
                    <groupId>joda-time</groupId>
                    <artifactId>joda-time</artifactId>
                    <version>2.3</version>
                </dependency>
                <dependency>
                    <groupId>dk.brics.automaton</groupId>
                    <artifactId>automaton</artifactId>
                    <version>1.11-8</version>
                </dependency>
                <dependency>
                    <groupId>ml.shifu</groupId>
                    <artifactId>guagua-mapreduce</artifactId>
                    <version>0.7.1</version>
                    <classifier>hadoop2</classifier>
                </dependency>
                <dependency>
                    <groupId>io.netty</groupId>
                    <artifactId>netty</artifactId>
                    <version>3.6.2.Final</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
</project>


text:
"""
Model-Managers for radonCMS

"""

import datetime

from django.db import models
from django.db.models import Q
from django.http import Http404

class PageManager(models.Manager):
    """
    Builds common querysets on page-objects and can find the homepage.

    """

    def get_homepage(self):
        """
        Returns the top-level page-object with the lowest sibling_id.
        Calling this method hits the database.

        """
        try:
            return self.filter_toplevel_pages()[0]
        except IndexError:
            # this can happen at first startup.
            raise Http404("no top-level object found")

    def filter_toplevel_pages(self, publish=True, only_nav_items=True):
        """
        Returns a queryset of all objects without a parent_page. The
        returned queryset is ordered by 'sibling_id'.

        """
        queryset = self.filter(parent_page=None)
        return self._refine_queryset(queryset, publish, only_nav_items)

    def filter_childpages(self, page, publish=True, only_nav_items=True):
        """
        Returns a queryset with the pages having 'page' as parent_page.
        If 'publish' is True, only pages free for publishing will be in
        the queryset. Otherwise all childpages regardless of their
        publish status will be in the returned queryset.

        """
        queryset = self.filter(parent_page=page)
        return self._refine_queryset(queryset, publish, only_nav_items)

    def filter_siblings(self, page, publish=True, only_nav_items=True):
        """
        Returns a queryset with the pages having the same parent_page as
        'page'. If 'publish' is True, only pages free for publishing
        will be in the queryset. Otherwise all siblingpages regardless
        of their publish status will be in the returned queryset.

        """
        queryset = self.filter(parent_page=page.parent_page)
        return self._refine_queryset(queryset, publish, only_nav_items)

    def _refine_queryset(self, queryset, publish, only_nav_items):
        """
        Returns a refined queryset with regard to the published status
        of objects and ordered by the sibling_id attribute.
        if only_nav_items is True only pages with this flag set to True
        are returned.

        """
        if publish is True:
            queryset = self._filter_published_items(queryset)
        if only_nav_items is True:
            queryset = queryset.filter(nav_item=True)
        return queryset.order_by('sibling_id')

    def _filter_published_items(self, queryset=None):
        """
        Returns a queryset of page-objects that are free for publishing,
        i.e. where the flag 'publish' is true and the publish date range
        falls into the current date. The parameter 'queryset' is not
        None it should be a queryset of page-objects.

        """
        if queryset is None:
            queryset = self.all()
        today = datetime.date.today()
        return queryset.filter(
                                Q(publish=True),
                                Q(start_publish_date__isnull=True)|
                                Q(start_publish_date__lte=today),
                                Q(stop_publish_date__isnull=True)|
                                Q(stop_publish_date__gt=today)
                              )


text:
import path from 'path';
import plugins from '../../src/api/plugins';
import { PLUGIN_PATH } from '../../src/utils/paths';

jest.mock('fs');

describe('plugins', () => {
  it('should retrieve all plugins from the file system', async () => {
    require('fs').__setFiles([
      `${PLUGIN_PATH}/foo-plugin`,
      `${PLUGIN_PATH}/bar-plugin`,
      `${PLUGIN_PATH}/baz-plugin`,
    ]);
    expect(await plugins.fetchPlugins()).toEqual([
      `${PLUGIN_PATH}/foo-plugin`,
      `${PLUGIN_PATH}/bar-plugin`,
      `${PLUGIN_PATH}/baz-plugin`,
    ]);
  });

  it('should return no plugins', async () => {
    require('fs').__setError('NO_PLUGINS_FOUND');
    try {
      await plugins.fetchPlugins();
    } catch (err) {
      expect(err).toEqual('NO_PLUGINS_FOUND');
    }
  });

  it('should check if a plugin is installed', () => {
    require('fs').__setFiles([path.resolve(PLUGIN_PATH, 'foobar')]);
    expect(plugins.isInstalled('foobar')).toBeTruthy();
    expect(plugins.isInstalled('bazqux')).toBeFalsy();
  });
});


text:
#define Q_TEST_QPIXMAPCACHE
#include "qpixmapcache.h"
#include "qobject.h"
#include "qdebug.h"
#include "qpixmapcache_p.h"

QT_BEGIN_NAMESPACE

/*!
    \class QPixmapCache

    \brief The QPixmapCache class provides an application-wide cache for pixmaps.

    \ingroup painting

    This class is a tool for optimized drawing with QPixmap. You can
    use it to store temporary pixmaps that are expensive to generate
    without using more storage space than cacheLimit(). Use insert()
    to insert pixmaps, find() to find them, and clear() to empty the
    cache.

    QPixmapCache contains no member data, only static functions to
    access the global pixmap cache. It creates an internal QCache
    object for caching the pixmaps.

    The cache associates a pixmap with a user-provided string as a key,
    or with a QPixmapCache::Key that the cache generates.
    Using QPixmapCache::Key for keys is faster than using strings. The string API is
    very convenient for complex keys but the QPixmapCache::Key API will be very
    efficient and convenient for a one-to-one object-to-pixmap mapping \mdash in
    this case, you can store the keys as members of an object.

    If two pixmaps are inserted into the cache using equal keys then the
    last pixmap will replace the first pixmap in the cache. This follows the
    behavior of the QHash and QCache classes.

    The cache becomes full when the total size of all pixmaps in the
    cache exceeds cacheLimit(). The initial cache limit is
    2048 KB (2 MB) on embedded platforms, 10240 KB (10 MB) on desktop
    platforms; you can change this by calling setCacheLimit() with the
    required value.
    A pixmap takes roughly (\e{width} * \e{height} * \e{depth})/8 bytes of
    memory.

    The \e{Qt Quarterly} article
    \l{http://qt.nokia.com/doc/qq/qq12-qpixmapcache.html}{Optimizing
    with QPixmapCache} explains how to use QPixmapCache to speed up
    applications by caching the results of painting.

    \sa QCache, QPixmap
*/

#if defined(Q_WS_QWS) || defined(Q_WS_WINCE)
static int cache_limit = 2048; // 2048 KB cache limit for embedded
#else
static int cache_limit = 10240; // 10 MB cache limit for desktop
#endif

/*!
    \class QPixmapCache::Key
    \brief The QPixmapCache::Key class can be used for efficient access
    to the QPixmapCache.
    \since 4.6

    Use QPixmapCache::insert() to receive an instance of Key generated
    by the pixmap cache. You can store the key in your own objects for
    a very efficient one-to-one object-to-pixmap mapping.
*/

/*!
    Constructs an empty Key object.
*/
QPixmapCache::Key::Key() : d(0)
{
}

/*!
   \internal
    Constructs a copy of \a other.
*/
QPixmapCache::Key::Key(const Key &other)
{
    if (other.d)
        ++(other.d->ref);
    d = other.d;
}

/*!
    Destroys the key.
*/
QPixmapCache::Key::~Key()
{
    if (d && --(d->ref) == 0)
        delete d;
}

/*!
    \internal

    Returns true if this key is the same as the given \a key; otherwise returns
    false.
*/
bool QPixmapCache::Key::operator ==(const Key &key) const
{
    return (d == key.d);
}

/*!
    \fn bool QPixmapCache::Key::operator !=(const Key &key) const
    \internal
*/

/*!
    \internal
*/
QPixmapCache::Key &QPixmapCache::Key::operator =(const Key &other)
{
    if (d != other.d) {
        if (other.d)
            ++(other.d->ref);
        if (d && --(d->ref) == 0)
            delete d;
        d = other.d;
    }
    return *this;
}

class QPMCache : public QObject, public QCache<QPixmapCache::Key, QPixmapCacheEntry>
{
    Q_OBJECT
public:
    QPMCache();
    ~QPMCache();

    void timerEvent(QTimerEvent *);
    bool insert(const QString& key, const QPixmap &pixmap, int cost);
    QPixmapCache::Key insert(const QPixmap &pixmap, int cost);
    bool replace(const QPixmapCache::Key &key, const QPixmap &pixmap, int cost);
    bool remove(const QString &key);
    bool remove(const QPixmapCache::Key &key);

    void resizeKeyArray(int size);
    QPixmapCache::Key createKey();
    void releaseKey(const QPixmapCache::Key &key);
    void clear();

    QPixmap *object(const QString &key) const;
    QPixmap *object(const QPixmapCache::Key &key) const;

    static inline QPixmapCache::KeyData *get(const QPixmapCache::Key &key)
    {return key.d;}

    static QPixmapCache::KeyData* getKeyData(QPixmapCache::Key *key);

    QList< QPair<QString,QPixmap> > allPixmaps() const;
    bool flushDetachedPixmaps(bool nt);

private:
    enum { soon_time = 10000, flush_time = 30000 };
    int *keyArray;
    int theid;
    int ps;
    int keyArraySize;
    int freeKey;
    QHash<QString, QPixmapCache::Key> cacheKeys;
    bool t;
};

QT_BEGIN_INCLUDE_NAMESPACE
#include "qpixmapcache.moc"
QT_END_INCLUDE_NAMESPACE

uint qHash(const QPixmapCache::Key &k)
{
    return qHash(QPMCache::get(k)->key);
}

QPMCache::QPMCache()
    : QObject(0),
      QCache<QPixmapCache::Key, QPixmapCacheEntry>(cache_limit * 1024),
      keyArray(0), theid(0), ps(0), keyArraySize(0), freeKey(0), t(false)
{
}
QPMCache::~QPMCache()
{
    clear();
    free(keyArray);
}

/*
  This is supposed to cut the cache size down by about 25% in a
  minute once the application becomes idle, to let any inserted pixmap
  remain in the cache for some time before it becomes a candidate for
  cleaning-up, and to not cut down the size of the cache while the
  cache is in active use.

  When the last detached pixmap has been deleted from the cache, kill the
  timer so Qt won't keep the CPU from going into sleep mode. Currently
  the timer is not restarted when the pixmap becomes unused, but it does
  restart once something else is added (i.e. the cache space is actually needed).

  Returns true if any were removed.
*/
bool QPMCache::flushDetachedPixmaps(bool nt)
{
    int mc = maxCost();
    setMaxCost(nt ? totalCost() * 3 / 4 : totalCost() -1);
    setMaxCost(mc);
    ps = totalCost();

    bool any = false;
    QHash<QString, QPixmapCache::Key>::iterator it = cacheKeys.begin();
    while (it != cacheKeys.end()) {
        if (!contains(it.value())) {
            releaseKey(it.value());
            it = cacheKeys.erase(it);
            any = true;
        } else {
            ++it;
        }
    }

    return any;
}

void QPMCache::timerEvent(QTimerEvent *)
{
    bool nt = totalCost() == ps;
    if (!flushDetachedPixmaps(nt)) {
        killTimer(theid);
        theid = 0;
    } else if (nt != t) {
        killTimer(theid);
        theid = startTimer(nt ? soon_time : flush_time);
        t = nt;
    }
}

QPixmap *QPMCache::object(const QString &key) const
{
    QPixmapCache::Key cacheKey = cacheKeys.value(key);
    if (!cacheKey.d || !cacheKey.d->isValid) {
        const_cast<QPMCache *>(this)->cacheKeys.remove(key);
        return 0;
    }
    QPixmap *ptr = QCache<QPixmapCache::Key, QPixmapCacheEntry>::object(cacheKey);
     //We didn't find the pixmap in the cache, the key is not valid anymore
    if (!ptr) {
        const_cast<QPMCache *>(this)->cacheKeys.remove(key);
    }
    return ptr;
}

QPixmap *QPMCache::object(const QPixmapCache::Key &key) const
{
    Q_ASSERT(key.d->isValid);
    QPixmap *ptr = QCache<QPixmapCache::Key, QPixmapCacheEntry>::object(key);
    //We didn't find the pixmap in the cache, the key is not valid anymore
    if (!ptr)
        const_cast<QPMCache *>(this)->releaseKey(key);
    return ptr;
}

bool QPMCache::insert(const QString& key, const QPixmap &pixmap, int cost)
{
    QPixmapCache::Key cacheKey;
    QPixmapCache::Key oldCacheKey = cacheKeys.value(key);
    //If for the same key we add already a pixmap we should delete it
    if (oldCacheKey.d) {
        QCache<QPixmapCache::Key, QPixmapCacheEntry>::remove(oldCacheKey);
        cacheKeys.remove(key);
    }

    //we create a new key the old one has been removed
    cacheKey = createKey();

    bool success = QCache<QPixmapCache::Key, QPixmapCacheEntry>::insert(cacheKey, new QPixmapCacheEntry(cacheKey, pixmap), cost);
    if (success) {
        cacheKeys.insert(key, cacheKey);
        if (!theid) {
            theid = startTimer(flush_time);
            t = false;
        }
    } else {
        //Insertion failed we released the new allocated key
        releaseKey(cacheKey);
    }
    return success;
}

QPixmapCache::Key QPMCache::insert(const QPixmap &pixmap, int cost)
{
    QPixmapCache::Key cacheKey = createKey();
    bool success = QCache<QPixmapCache::Key, QPixmapCacheEntry>::insert(cacheKey, new QPixmapCacheEntry(cacheKey, pixmap), cost);
    if (success) {
        if (!theid) {
            theid = startTimer(flush_time);
            t = false;
        }
    } else {
        //Insertion failed we released the key and return an invalid one
        releaseKey(cacheKey);
    }
    return cacheKey;
}

bool QPMCache::replace(const QPixmapCache::Key &key, const QPixmap &pixmap, int cost)
{
    Q_ASSERT(key.d->isValid);
    //If for the same key we had already an entry so we should delete the pixmap and use the new one
    QCache<QPixmapCache::Key, QPixmapCacheEntry>::remove(key);

    QPixmapCache::Key cacheKey = createKey();

    bool success = QCache<QPixmapCache::Key, QPixmapCacheEntry>::insert(cacheKey, new QPixmapCacheEntry(cacheKey, pixmap), cost);
    if (success) {
        if(!theid) {
            theid = startTimer(flush_time);
            t = false;
        }
        const_cast<QPixmapCache::Key&>(key) = cacheKey;
    } else {
        //Insertion failed we released the key
        releaseKey(cacheKey);
    }
    return success;
}

bool QPMCache::remove(const QString &key)
{
    QPixmapCache::Key cacheKey = cacheKeys.value(key);
    //The key was not in the cache
    if (!cacheKey.d)
        return false;
    cacheKeys.remove(key);
    return QCache<QPixmapCache::Key, QPixmapCacheEntry>::remove(cacheKey);
}

bool QPMCache::remove(const QPixmapCache::Key &key)
{
    return QCache<QPixmapCache::Key, QPixmapCacheEntry>::remove(key);
}

void QPMCache::resizeKeyArray(int size)
{
    if (size <= keyArraySize || size == 0)
        return;
    keyArray = q_check_ptr(reinterpret_cast<int *>(realloc(keyArray,
                    size * sizeof(int))));
    for (int i = keyArraySize; i != size; ++i)
        keyArray[i] = i + 1;
    keyArraySize = size;
}

QPixmapCache::Key QPMCache::createKey()
{
    if (freeKey == keyArraySize)
        resizeKeyArray(keyArraySize ? keyArraySize << 1 : 2);
    int id = freeKey;
    freeKey = keyArray[id];
    QPixmapCache::Key key;
    QPixmapCache::KeyData *d = QPMCache::getKeyData(&key);
    d->key = ++id;
    return key;
}

void QPMCache::releaseKey(const QPixmapCache::Key &key)
{
    if (key.d->key > keyArraySize || key.d->key <= 0)
        return;
    key.d->key--;
    keyArray[key.d->key] = freeKey;
    freeKey = key.d->key;
    key.d->isValid = false;
    key.d->key = 0;
}

void QPMCache::clear()
{
    free(keyArray);
    keyArray = 0;
    freeKey = 0;
    keyArraySize = 0;
    //Mark all keys as invalid
    QList<QPixmapCache::Key> keys = QCache<QPixmapCache::Key, QPixmapCacheEntry>::keys();
    for (int i = 0; i < keys.size(); ++i)
        keys.at(i).d->isValid = false;
    QCache<QPixmapCache::Key, QPixmapCacheEntry>::clear();
}

QPixmapCache::KeyData* QPMCache::getKeyData(QPixmapCache::Key *key)
{
    if (!key->d)
        key->d = new QPixmapCache::KeyData;
    return key->d;
}

QList< QPair<QString,QPixmap> > QPMCache::allPixmaps() const
{
    QList< QPair<QString,QPixmap> > r;
    QHash<QString, QPixmapCache::Key>::const_iterator it = cacheKeys.begin();
    while (it != cacheKeys.end()) {
        QPixmap *ptr = QCache<QPixmapCache::Key, QPixmapCacheEntry>::object(it.value());
        if (ptr)
            r.append(QPair<QString,QPixmap>(it.key(),*ptr));
        ++it;
    }
    return r;
}

Q_GLOBAL_STATIC(QPMCache, pm_cache)

int Q_AUTOTEST_EXPORT q_QPixmapCache_keyHashSize()
{
    return pm_cache()->size();
}

QPixmapCacheEntry::~QPixmapCacheEntry()
{
    pm_cache()->releaseKey(key);
}

/*!
    \obsolete
    \overload

    Returns the pixmap associated with the \a key in the cache, or
    null if there is no such pixmap.

    \warning If valid, you should copy the pixmap immediately (this is
    fast). Subsequent insertions into the cache could cause the
    pointer to become invalid. For this reason, we recommend you use
    bool find(const QString&, QPixmap*) instead.

    Example:
    \snippet doc/src/snippets/code/src_gui_image_qpixmapcache.cpp 0
*/

QPixmap *QPixmapCache::find(const QString &key)
{
    return pm_cache()->object(key);
}

/*!
    \obsolete

    Use bool find(const QString&, QPixmap*) instead.
*/

bool QPixmapCache::find(const QString &key, QPixmap& pixmap)
{
    return find(key, &pixmap);
}

/*!
    Looks for a cached pixmap associated with the given \a key in the cache.
    If the pixmap is found, the function sets \a pixmap to that pixmap and
    returns true; otherwise it leaves \a pixmap alone and returns false.

    \since 4.6

    Example:
    \snippet doc/src/snippets/code/src_gui_image_qpixmapcache.cpp 1
*/

bool QPixmapCache::find(const QString &key, QPixmap* pixmap)
{
    QPixmap *ptr = pm_cache()->object(key);
    if (ptr && pixmap)
        *pixmap = *ptr;
    return ptr != 0;
}

/*!
    Looks for a cached pixmap associated with the given \a key in the cache.
    If the pixmap is found, the function sets \a pixmap to that pixmap and
    returns true; otherwise it leaves \a pixmap alone and returns false. If
    the pixmap is not found, it means that the \a key is no longer valid,
    so it will be released for the next insertion.

    \since 4.6
*/
bool QPixmapCache::find(const Key &key, QPixmap* pixmap)
{
    //The key is not valid anymore, a flush happened before probably
    if (!key.d || !key.d->isValid)
        return false;
    QPixmap *ptr = pm_cache()->object(key);
    if (ptr && pixmap)
        *pixmap = *ptr;
    return ptr != 0;
}

/*!
    Inserts a copy of the pixmap \a pixmap associated with the \a key into
    the cache.

    All pixmaps inserted by the Qt library have a key starting with
    "$qt", so your own pixmap keys should never begin "$qt".

    When a pixmap is inserted and the cache is about to exceed its
    limit, it removes pixmaps until there is enough room for the
    pixmap to be inserted.

    The oldest pixmaps (least recently accessed in the cache) are
    deleted when more space is needed.

    The function returns true if the object was inserted into the
    cache; otherwise it returns false.

    \sa setCacheLimit()
*/

bool QPixmapCache::insert(const QString &key, const QPixmap &pixmap)
{
    return pm_cache()->insert(key, pixmap, pixmap.width() * pixmap.height() * pixmap.depth() / 8);
}

/*!
    Inserts a copy of the given \a pixmap into the cache and returns a key
    that can be used to retrieve it.

    When a pixmap is inserted and the cache is about to exceed its
    limit, it removes pixmaps until there is enough room for the
    pixmap to be inserted.

    The oldest pixmaps (least recently accessed in the cache) are
    deleted when more space is needed.

    \sa setCacheLimit(), replace()

    \since 4.6
*/
QPixmapCache::Key QPixmapCache::insert(const QPixmap &pixmap)
{
    return pm_cache()->insert(pixmap, pixmap.width() * pixmap.height() * pixmap.depth() / 8);
}

/*!
    Replaces the pixmap associated with the given \a key with the \a pixmap
    specified. Returns true if the \a pixmap has been correctly inserted into
    the cache; otherwise returns false.

    \sa setCacheLimit(), insert()

    \since 4.6
*/
bool QPixmapCache::replace(const Key &key, const QPixmap &pixmap)
{
    //The key is not valid anymore, a flush happened before probably
    if (!key.d || !key.d->isValid)
        return false;
    return pm_cache()->replace(key, pixmap, pixmap.width() * pixmap.height() * pixmap.depth() / 8);
}

/*!
    Returns the cache limit (in kilobytes).

    The default cache limit is 2048 KB on embedded platforms, 10240 KB on
    desktop platforms.

    \sa setCacheLimit()
*/

int QPixmapCache::cacheLimit()
{
    return cache_limit;
}

/*!
    Sets the cache limit to \a n kilobytes.

    The default setting is 2048 KB on embedded platforms, 10240 KB on
    desktop platforms.

    \sa cacheLimit()
*/

void QPixmapCache::setCacheLimit(int n)
{
    cache_limit = n;
    pm_cache()->setMaxCost(1024 * cache_limit);
}

/*!
  Removes the pixmap associated with \a key from the cache.
*/
void QPixmapCache::remove(const QString &key)
{
    pm_cache()->remove(key);
}

/*!
  Removes the pixmap associated with \a key from the cache and releases
  the key for a future insertion.

  \since 4.6
*/
void QPixmapCache::remove(const Key &key)
{
    //The key is not valid anymore, a flush happened before probably
    if (!key.d || !key.d->isValid)
        return;
    pm_cache()->remove(key);
}

/*!
    Removes all pixmaps from the cache.
*/

void QPixmapCache::clear()
{
    QT_TRY {
        pm_cache()->clear();
    } QT_CATCH(const std::bad_alloc &) {
        // if we ran out of memory during pm_cache(), it's no leak,
        // so just ignore it.
    }
}

void QPixmapCache::flushDetachedPixmaps()
{
    pm_cache()->flushDetachedPixmaps(true);
}

int QPixmapCache::totalUsed()
{
    return (pm_cache()->totalCost()+1023) / 1024;
}

QList< QPair<QString,QPixmap> > QPixmapCache::allPixmaps()
{
    return pm_cache()->allPixmaps();
}

QT_END_NAMESPACE