text:
package com.opengamma.bbg.referencedata.cache;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.bbg.referencedata.ReferenceData;
import com.opengamma.bbg.referencedata.ReferenceDataError;
import com.opengamma.bbg.referencedata.ReferenceDataProvider;
import com.opengamma.bbg.referencedata.ReferenceDataProviderGetRequest;
import com.opengamma.bbg.referencedata.ReferenceDataProviderGetResult;
import com.opengamma.bbg.referencedata.impl.AbstractReferenceDataProvider;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;

/**
 * Abstract reference data provider decorator that caches field values.
 * <p>
 * It is recommended to use a cache over the underlying provider to avoid excess queries on Bloomberg.
 */
public abstract class AbstractValueCachingReferenceDataProvider extends AbstractReferenceDataProvider {

  /** Logger. */
  private static final Logger LOGGER = LoggerFactory.getLogger(AbstractValueCachingReferenceDataProvider.class);
  /**
   * Constant used when field not available.
   */
  private static final String FIELD_NOT_AVAILABLE_NAME = "NOT_AVAILABLE_FIELD";

  /**
   * The underlying provider.
   */
  private final ReferenceDataProvider _underlying;
  /**
   * The Fudge context.
   */
  private final FudgeContext _fudgeContext;

  /**
   * Creates an instance.
   *
   * @param underlying
   *          the underlying provider, not null
   */
  protected AbstractValueCachingReferenceDataProvider(final ReferenceDataProvider underlying) {
    this(underlying, OpenGammaFudgeContext.getInstance());
  }

  /**
   * Creates an instance.
   *
   * @param underlying
   *          the underlying provider, not null
   * @param fudgeContext
   *          the Fudge context, not null
   */
  protected AbstractValueCachingReferenceDataProvider(final ReferenceDataProvider underlying, final FudgeContext fudgeContext) {
    ArgumentChecker.notNull(underlying, "underlying");
    ArgumentChecker.notNull(fudgeContext, "fudgeContext");
    _underlying = underlying;
    _fudgeContext = fudgeContext;
  }

  // -------------------------------------------------------------------------
  /**
   * Gets the underlying provider.
   *
   * @return the underlying provider, not null
   */
  public ReferenceDataProvider getUnderlying() {
    return _underlying;
  }

  /**
   * Gets the Fudge context.
   *
   * @return the context, not null
   */
  protected FudgeContext getFudgeContext() {
    return _fudgeContext;
  }

  // -------------------------------------------------------------------------
  @Override
  protected ReferenceDataProviderGetResult doBulkGet(final ReferenceDataProviderGetRequest request) {
    // if use-cache is false, then do not cache
    if (!request.isUseCache()) {
      return getUnderlying().getReferenceData(request);
    }

    // load from cache
    final Map<String, ReferenceData> cachedResults = loadFieldValues(request.getIdentifiers());

    // filter the request removing known invalid fields
    final Map<Set<String>, Set<String>> identifiersByFields = buildUnderlyingRequestGroups(request, cachedResults);

    // process everything that remains
    ReferenceDataProviderGetResult resolvedResults = loadAndPersistUnknownFields(cachedResults, identifiersByFields);
    resolvedResults = stripUnwantedFields(resolvedResults, request.getFields());
    return resolvedResults;
  }

  protected ReferenceDataProviderGetResult stripUnwantedFields(final ReferenceDataProviderGetResult resolvedResults, final Set<String> fields) {
    final ReferenceDataProviderGetResult result = new ReferenceDataProviderGetResult();
    for (final ReferenceData unstippedDataResult : resolvedResults.getReferenceData()) {
      final String identifier = unstippedDataResult.getIdentifier();
      final ReferenceData strippedDataResult = new ReferenceData(identifier);
      strippedDataResult.getErrors().addAll(unstippedDataResult.getErrors());
      final MutableFudgeMsg strippedFields = getFudgeContext().newMessage();
      final FudgeMsg unstrippedFieldData = unstippedDataResult.getFieldValues();
      // check requested fields
      for (final String requestField : fields) {
        final List<FudgeField> fudgeFields = unstrippedFieldData.getAllByName(requestField);
        for (final FudgeField fudgeField : fudgeFields) {
          strippedFields.add(requestField, fudgeField.getValue());
        }
      }
      strippedDataResult.setFieldValues(strippedFields);
      result.addReferenceData(strippedDataResult);
    }
    return result;
  }

  protected ReferenceDataProviderGetResult loadAndPersistUnknownFields(
      final Map<String, ReferenceData> cachedResults,
      final Map<Set<String>, Set<String>> identifiersByFields) {

    // TODO kirk 2009-10-23 -- Also need to maintain securities we don't need to put back in the database.
    final ReferenceDataProviderGetResult result = new ReferenceDataProviderGetResult();
    // REVIEW kirk 2009-10-23 -- Candidate for scatter/gather.
    for (final Map.Entry<Set<String>, Set<String>> entry : identifiersByFields.entrySet()) {
      final Set<String> requestedIdentifiers = entry.getValue();
      final Set<String> requestedFields = entry.getKey();
      assert !requestedIdentifiers.isEmpty();
      if (entry.getKey().isEmpty()) {
        LOGGER.debug("Satisfied entire request for securities {} from cache", requestedIdentifiers);
        for (final String securityKey : requestedIdentifiers) {
          result.addReferenceData(cachedResults.get(securityKey));
        }
        continue;
      }
      LOGGER.info("Loading {} fields for {} securities from underlying", entry.getKey().size(), requestedIdentifiers.size());
      final ReferenceDataProviderGetRequest underlyingRequest = ReferenceDataProviderGetRequest.createGet(requestedIdentifiers, requestedFields, false);
      final ReferenceDataProviderGetResult loadedResult = getUnderlying().getReferenceData(underlyingRequest);
      for (final String identifier : requestedIdentifiers) {
        final ReferenceData cachedResult = cachedResults.get(identifier);
        ReferenceData freshResult = loadedResult.getReferenceDataOrNull(identifier);
        freshResult = freshResult != null ? freshResult : new ReferenceData(identifier);

        final ReferenceData resolvedResult = getCombinedResult(requestedFields, cachedResult, freshResult);
        saveFieldValues(resolvedResult);
        result.addReferenceData(resolvedResult);
      }
    }
    return result;
  }

  private ReferenceData getCombinedResult(final Set<String> requestedFields, final ReferenceData cachedResult, final ReferenceData freshResult) {
    MutableFudgeMsg unionFieldData = null;
    if (cachedResult == null) {
      unionFieldData = getFudgeContext().newMessage();
    } else {
      unionFieldData = getFudgeContext().newMessage(cachedResult.getFieldValues());
    }
    final Set<String> returnedFields = new HashSet<>();
    for (final FudgeField freshField : freshResult.getFieldValues().getAllFields()) {
      unionFieldData.add(freshField);
      returnedFields.add(freshField.getName());
    }

    // cache not available fields as well
    final Set<String> notAvaliableFields = Sets.newTreeSet(requestedFields);
    notAvaliableFields.removeAll(returnedFields);

    // add list of not available fields
    for (final String notAvailableField : notAvaliableFields) {
      unionFieldData.add(FIELD_NOT_AVAILABLE_NAME, notAvailableField);
    }

    // create combined result
    final ReferenceData resolvedResult = new ReferenceData(freshResult.getIdentifier(), unionFieldData);
    for (final ReferenceDataError error : freshResult.getErrors()) {
      if (!resolvedResult.getErrors().contains(error)) {
        resolvedResult.getErrors().add(error);
      }
    }
    return resolvedResult;
  }

  /**
   * Examines and groups the request using the known invalid fields.
   *
   * @param request
   *          the request, not null
   * @param cachedResults
   *          the cached results, keyed by identifier, not null
   * @return the map of field-set to identifier-set, not null
   */
  protected Map<Set<String>, Set<String>> buildUnderlyingRequestGroups(final ReferenceDataProviderGetRequest request,
      final Map<String, ReferenceData> cachedResults) {
    final Map<Set<String>, Set<String>> result = Maps.newHashMap();
    for (final String identifier : request.getIdentifiers()) {
      // select known invalid fields for the identifier
      final ReferenceData cachedResult = cachedResults.get(identifier);

      // calculate the missing fields that must be queried from the underlying
      Set<String> missingFields = null;
      if (cachedResult == null) {
        missingFields = Sets.newHashSet(request.getFields());
      } else {
        missingFields = Sets.newHashSet(Sets.difference(request.getFields(), cachedResult.getFieldValues().getAllFieldNames()));
        // remove known not available fields from missingFields
        final List<String> notAvailableFieldNames = getNotAvailableFields(cachedResult);
        for (final String field : notAvailableFieldNames) {
          missingFields.remove(field);
        }
      }

      // build the grouped result map, keyed from field-set to identifier-set
      Set<String> resultIdentifiers = result.get(missingFields);
      if (resultIdentifiers == null) {
        resultIdentifiers = Sets.newTreeSet();
        result.put(missingFields, resultIdentifiers);
      }
      resultIdentifiers.add(identifier);
    }
    return result;
  }

  private List<String> getNotAvailableFields(final ReferenceData cachedResult) {
    final List<FudgeField> notAvailableFields = cachedResult.getFieldValues().getAllByName(FIELD_NOT_AVAILABLE_NAME);
    final List<String> notAvailableFieldNames = new ArrayList<>(notAvailableFields.size());
    for (final FudgeField field : notAvailableFields) {
      notAvailableFieldNames.add((String) field.getValue());
    }
    return notAvailableFieldNames;
  }

  // -------------------------------------------------------------------------
  /**
   * Loads the field values from the cache.
   *
   * @param identifiers
   *          the identifiers to find errors for, not null
   * @return the map of reference data keyed by identifier, not null
   */
  protected abstract Map<String, ReferenceData> loadFieldValues(Set<String> identifiers);

  /**
   * Saves the field value into the cache.
   *
   * @param result
   *          the result to save, not null
   */
  protected abstract void saveFieldValues(ReferenceData result);

  // -------------------------------------------------------------------------
  /**
   * Refreshes the cache.
   *
   * @param identifiers
   *          the identifiers, not null
   */
  public void refresh(final Set<String> identifiers) {
    // TODO bulk queries
    final Map<String, ReferenceData> cachedResults = loadFieldValues(identifiers);

    final Map<Set<String>, Set<String>> identifiersByFields = Maps.newHashMap();

    for (final String identifier : identifiers) {
      final ReferenceData cachedResult = cachedResults.get(identifier);
      if (cachedResult == null) {
        continue; // nothing to refresh
      }
      final Set<String> fields = new HashSet<>();
      fields.addAll(cachedResult.getFieldValues().getAllFieldNames());
      fields.addAll(getNotAvailableFields(cachedResult));
      fields.remove(FIELD_NOT_AVAILABLE_NAME);
      Set<String> secsForTheseFields = identifiersByFields.get(fields);
      if (secsForTheseFields == null) {
        secsForTheseFields = new HashSet<>();
        identifiersByFields.put(fields, secsForTheseFields);
      }
      secsForTheseFields.add(identifier);
    }

    for (final Entry<Set<String>, Set<String>> entry : identifiersByFields.entrySet()) {
      final Set<String> identifiersForTheseFields = entry.getValue();
      final Set<String> fields = entry.getKey();

      final ReferenceDataProviderGetRequest underlyingRequest = ReferenceDataProviderGetRequest.createGet(identifiersForTheseFields, fields, false);
      final ReferenceDataProviderGetResult underlyingResult = _underlying.getReferenceData(underlyingRequest);
      for (final ReferenceData refData : underlyingResult.getReferenceData()) {
        final ReferenceData previousResult = cachedResults.get(refData.getIdentifier());
        final ReferenceData resolvedResult = getCombinedResult(fields, new ReferenceData(refData.getIdentifier()), refData);
        if (differentCachedResult(previousResult, resolvedResult)) {
          saveFieldValues(resolvedResult);
        }
      }
    }
  }

  private boolean differentCachedResult(final ReferenceData previousResult, final ReferenceData resolvedResult) {
    if (!previousResult.getIdentifier().equals(resolvedResult.getIdentifier())) {
      throw new OpenGammaRuntimeException("Attempting to compare two different securities " + previousResult + " " + resolvedResult);
    }
    // TODO better, non ordered comparison
    if (previousResult.getFieldValues().toString().equals(resolvedResult.getFieldValues().toString())) {
      return false;
    }
    return true;
  }

}


text:
A simple low-dependency nodejs module that downloads, installs and starts elasticsearch v5.x locally for integration testing. Please note that this module currently only supports elasticsearch v5.x i.e. older versions are not supported.

The module attempts to download and unzip the package from the [Official Elasticsearch artifacts source](https://artifacts.elastic.co/downloads), if not already downloaded, and starts elasticsearch as a detached nodejs background process listening on the specified port.

To get started, npm install this module as a dev dependency:

```javascript
npm install --save-dev node-es-local
```

This module has a single external dependency on the following module for unzipping:

* [adm-zip](https://github.com/cthackers/adm-zip) - a pure Javascript (no-dependency) implementation of zip for nodejs

Once installed, you can use the module in your mocha tests or within gulp tasks.

## Usage

To download and start a local instance of elasticsearch:

```javascript
const ElasticsearchLocal = require('node-es-local')

const elasticsearchVersion = '5.2.0'
const elasticsearchPort = 9500
const cacheDirectory = './.cache'
const targetDirectory = './.installs'

new ElasticsearchLocal(elasticsearchVersion, elasticsearchPort, {
  cacheDirectory: cacheDirectory,
  installationDirectory: targetDirectory
}).start()
```
*start()* returns a promise.

To stop a local instance of elasticsearch started by the previous script:

```javascript
const ElasticsearchLocal = require('node-es-local')

const elasticsearchVersion = '5.2.0'
const elasticsearchPort = 9500
const cacheDirectory = './.cache'
const targetDirectory = './.installs'

new ElasticsearchLocal(elasticsearchVersion, elasticsearchPort, {
  cacheDirectory: cacheDirectory,
  installationDirectory: targetDirectory
}).stop()
```
*stop()* returns a promise.

Port **9200** is the *default port* if not specified and **./.cachedArtifacts** and **./.installs** are the *default cache* and *default installation* directories. Hence, if you are ok with the defaults, the following script is all you need:

```javascript
const ElasticsearchLocal = require('node-es-local')
new ElasticsearchLocal('5.2.0').start()
```

Simples!

## Using es-node-local in integration tests

The following example shows how you can use node-es-local with mocha to start a local instance of elasticsearch for integration tests:

```javascript
const ElasticsearchLocal = require('node-es-local')

describe('Some feature eg search', () => {
  before('given an index with some entries', () => {
    return new ElasticsearchLocal('5.2.0').start()  // return the promise
      .then(() => {
        // Put some data in...
      })
  })

  after(() => {
    return new ElasticsearchLocal('5.2.0').stop() // return the promise
  })
```

redpajama_set_name: RedPajamaGithub


text:
"""Tests for manipulating EfficacyIndicator via the DB API"""

import freezegun

from watcher.common import exception
from watcher.common import utils as w_utils
from watcher import objects
from watcher.tests.db import base
from watcher.tests.db import utils

class TestDbEfficacyIndicatorFilters(base.DbTestCase):

    FAKE_OLDER_DATE = '2014-01-01T09:52:05.219414'
    FAKE_OLD_DATE = '2015-01-01T09:52:05.219414'
    FAKE_TODAY = '2016-02-24T09:52:05.219414'

    def setUp(self):
        super(TestDbEfficacyIndicatorFilters, self).setUp()
        self.context.show_deleted = True
        self._data_setup()

    def _data_setup(self):
        self.audit_template_name = "Audit Template"

        self.audit_template = utils.create_test_audit_template(
            name=self.audit_template_name, id=1, uuid=None)
        self.audit = utils.create_test_audit(
            audit_template_id=self.audit_template.id, id=1, uuid=None)
        self.action_plan = utils.create_test_action_plan(
            audit_id=self.audit.id, id=1, uuid=None)

        with freezegun.freeze_time(self.FAKE_TODAY):
            self.efficacy_indicator1 = utils.create_test_efficacy_indicator(
                action_plan_id=self.action_plan.id, id=1, uuid=None,
                name="efficacy_indicator1", description="Test Indicator 1")
        with freezegun.freeze_time(self.FAKE_OLD_DATE):
            self.efficacy_indicator2 = utils.create_test_efficacy_indicator(
                action_plan_id=self.action_plan.id, id=2, uuid=None,
                name="efficacy_indicator2", description="Test Indicator 2")
        with freezegun.freeze_time(self.FAKE_OLDER_DATE):
            self.efficacy_indicator3 = utils.create_test_efficacy_indicator(
                action_plan_id=self.action_plan.id, id=3, uuid=None,
                name="efficacy_indicator3", description="Test Indicator 3")

    def _soft_delete_efficacy_indicators(self):
        with freezegun.freeze_time(self.FAKE_TODAY):
            self.dbapi.soft_delete_efficacy_indicator(
                self.efficacy_indicator1.uuid)
        with freezegun.freeze_time(self.FAKE_OLD_DATE):
            self.dbapi.soft_delete_efficacy_indicator(
                self.efficacy_indicator2.uuid)
        with freezegun.freeze_time(self.FAKE_OLDER_DATE):
            self.dbapi.soft_delete_efficacy_indicator(
                self.efficacy_indicator3.uuid)

    def _update_efficacy_indicators(self):
        with freezegun.freeze_time(self.FAKE_TODAY):
            self.dbapi.update_efficacy_indicator(
                self.efficacy_indicator1.uuid,
                values={"description": "New description 1"})
        with freezegun.freeze_time(self.FAKE_OLD_DATE):
            self.dbapi.update_efficacy_indicator(
                self.efficacy_indicator2.uuid,
                values={"description": "New description 2"})
        with freezegun.freeze_time(self.FAKE_OLDER_DATE):
            self.dbapi.update_efficacy_indicator(
                self.efficacy_indicator3.uuid,
                values={"description": "New description 3"})

    def test_get_efficacy_indicator_filter_deleted_true(self):
        with freezegun.freeze_time(self.FAKE_TODAY):
            self.dbapi.soft_delete_efficacy_indicator(
                self.efficacy_indicator1.uuid)

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted': True})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_false(self):
        with freezegun.freeze_time(self.FAKE_TODAY):
            self.dbapi.soft_delete_efficacy_indicator(
                self.efficacy_indicator1.uuid)

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted': False})

        self.assertEqual([self.efficacy_indicator2['id'],
                          self.efficacy_indicator3['id']],
                         [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_at_eq(self):
        self._soft_delete_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted_at__eq': self.FAKE_TODAY})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_at_lt(self):
        self._soft_delete_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted_at__lt': self.FAKE_TODAY})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_at_lte(self):
        self._soft_delete_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted_at__lte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_at_gt(self):
        self._soft_delete_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted_at__gt': self.FAKE_OLD_DATE})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_deleted_at_gte(self):
        self._soft_delete_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'deleted_at__gte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator1['id'], self.efficacy_indicator2['id']],
            [r.id for r in res])

    # created_at #

    def test_get_efficacy_indicator_filter_created_at_eq(self):
        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'created_at__eq': self.FAKE_TODAY})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_created_at_lt(self):
        with freezegun.freeze_time(self.FAKE_TODAY):
            res = self.dbapi.get_efficacy_indicator_list(
                self.context, filters={'created_at__lt': self.FAKE_TODAY})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_created_at_lte(self):
        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'created_at__lte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_created_at_gt(self):
        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'created_at__gt': self.FAKE_OLD_DATE})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_created_at_gte(self):
        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'created_at__gte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator1['id'], self.efficacy_indicator2['id']],
            [r.id for r in res])

    # updated_at #

    def test_get_efficacy_indicator_filter_updated_at_eq(self):
        self._update_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'updated_at__eq': self.FAKE_TODAY})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_updated_at_lt(self):
        self._update_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'updated_at__lt': self.FAKE_TODAY})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_updated_at_lte(self):
        self._update_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'updated_at__lte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator2['id'], self.efficacy_indicator3['id']],
            [r.id for r in res])

    def test_get_efficacy_indicator_filter_updated_at_gt(self):
        self._update_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'updated_at__gt': self.FAKE_OLD_DATE})

        self.assertEqual([self.efficacy_indicator1['id']], [r.id for r in res])

    def test_get_efficacy_indicator_filter_updated_at_gte(self):
        self._update_efficacy_indicators()

        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'updated_at__gte': self.FAKE_OLD_DATE})

        self.assertEqual(
            [self.efficacy_indicator1['id'], self.efficacy_indicator2['id']],
            [r.id for r in res])

class DbEfficacyIndicatorTestCase(base.DbTestCase):

    def test_get_efficacy_indicator_list(self):
        uuids = []
        action_plan = utils.create_test_action_plan()
        for id_ in range(1, 4):
            efficacy_indicator = utils.create_test_efficacy_indicator(
                action_plan_id=action_plan.id, id=id_, uuid=None,
                name="efficacy_indicator", description="Test Indicator ")
            uuids.append(str(efficacy_indicator['uuid']))
        efficacy_indicators = self.dbapi.get_efficacy_indicator_list(
            self.context)
        efficacy_indicator_uuids = [ei.uuid for ei in efficacy_indicators]
        self.assertEqual(sorted(uuids), sorted(efficacy_indicator_uuids))
        for efficacy_indicator in efficacy_indicators:
            self.assertIsNone(efficacy_indicator.action_plan)

    def test_get_efficacy_indicator_list_eager(self):
        _action_plan = utils.get_test_action_plan()
        action_plan = self.dbapi.create_action_plan(_action_plan)

        uuids = []
        for i in range(1, 4):
            efficacy_indicator = utils.create_test_efficacy_indicator(
                id=i, uuid=w_utils.generate_uuid(),
                action_plan_id=action_plan.id)
            uuids.append(str(efficacy_indicator['uuid']))
        efficacy_indicators = self.dbapi.get_efficacy_indicator_list(
            self.context, eager=True)
        efficacy_indicator_map = {a.uuid: a for a in efficacy_indicators}
        self.assertEqual(sorted(uuids), sorted(efficacy_indicator_map.keys()))
        eager_efficacy_indicator = efficacy_indicator_map[
            efficacy_indicator.uuid]
        self.assertEqual(
            action_plan.as_dict(),
            eager_efficacy_indicator.action_plan.as_dict())

    def test_get_efficacy_indicator_list_with_filters(self):
        audit = utils.create_test_audit(uuid=w_utils.generate_uuid())
        action_plan = utils.create_test_action_plan(
            id=1,
            uuid=w_utils.generate_uuid(),
            audit_id=audit.id,
            first_efficacy_indicator_id=None,
            state=objects.action_plan.State.RECOMMENDED)

        efficacy_indicator1 = utils.create_test_efficacy_indicator(
            id=1,
            name='indicator_1',
            uuid=w_utils.generate_uuid(),
            action_plan_id=action_plan['id'],
            description='Description efficacy indicator 1',
            unit='%')
        efficacy_indicator2 = utils.create_test_efficacy_indicator(
            id=2,
            name='indicator_2',
            uuid=w_utils.generate_uuid(),
            action_plan_id=2,
            description='Description efficacy indicator 2',
            unit='%')
        efficacy_indicator3 = utils.create_test_efficacy_indicator(
            id=3,
            name='indicator_3',
            uuid=w_utils.generate_uuid(),
            action_plan_id=action_plan['id'],
            description='Description efficacy indicator 3',
            unit='%')
        efficacy_indicator4 = utils.create_test_efficacy_indicator(
            id=4,
            name='indicator_4',
            uuid=w_utils.generate_uuid(),
            action_plan_id=action_plan['id'],
            description='Description efficacy indicator 4',
            unit='%')

        self.dbapi.soft_delete_efficacy_indicator(efficacy_indicator4['uuid'])

        res = self.dbapi.get_efficacy_indicator_list(
            self.context,
            filters={'name': 'indicator_3'})
        self.assertEqual([efficacy_indicator3['id']], [r.id for r in res])

        res = self.dbapi.get_efficacy_indicator_list(
            self.context,
            filters={'unit': 'kWh'})
        self.assertEqual([], [r.id for r in res])

        res = self.dbapi.get_efficacy_indicator_list(
            self.context,
            filters={'action_plan_id': 2})
        self.assertEqual([efficacy_indicator2['id']], [r.id for r in res])

        res = self.dbapi.get_efficacy_indicator_list(
            self.context,
            filters={'action_plan_uuid': action_plan['uuid']})
        self.assertEqual(
            sorted([efficacy_indicator1['id'], efficacy_indicator3['id']]),
            sorted([r.id for r in res]))

    def test_get_efficacy_indicator_list_with_filter_by_uuid(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        res = self.dbapi.get_efficacy_indicator_list(
            self.context, filters={'uuid': efficacy_indicator.uuid})

        self.assertEqual(len(res), 1)
        self.assertEqual(efficacy_indicator.uuid, res[0].uuid)

    def test_get_efficacy_indicator_by_id(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        efficacy_indicator = self.dbapi.get_efficacy_indicator_by_id(
            self.context, efficacy_indicator.id)
        self.assertEqual(efficacy_indicator.uuid, efficacy_indicator.uuid)

    def test_get_efficacy_indicator_by_uuid(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        efficacy_indicator = self.dbapi.get_efficacy_indicator_by_uuid(
            self.context, efficacy_indicator.uuid)
        self.assertEqual(efficacy_indicator['id'], efficacy_indicator.id)

    def test_get_efficacy_indicator_that_does_not_exist(self):
        self.assertRaises(
            exception.EfficacyIndicatorNotFound,
            self.dbapi.get_efficacy_indicator_by_id, self.context, 1234)

    def test_update_efficacy_indicator(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        res = self.dbapi.update_efficacy_indicator(
            efficacy_indicator.id,
            {'state': objects.action_plan.State.CANCELLED})
        self.assertEqual('CANCELLED', res.state)

    def test_update_efficacy_indicator_that_does_not_exist(self):
        self.assertRaises(
            exception.EfficacyIndicatorNotFound,
            self.dbapi.update_efficacy_indicator, 1234, {'state': ''})

    def test_update_efficacy_indicator_uuid(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        self.assertRaises(
            exception.Invalid,
            self.dbapi.update_efficacy_indicator, efficacy_indicator.id,
            {'uuid': 'hello'})

    def test_destroy_efficacy_indicator(self):
        efficacy_indicator = utils.create_test_efficacy_indicator()
        self.dbapi.destroy_efficacy_indicator(efficacy_indicator['id'])
        self.assertRaises(exception.EfficacyIndicatorNotFound,
                          self.dbapi.get_efficacy_indicator_by_id,
                          self.context, efficacy_indicator['id'])

    def test_destroy_efficacy_indicator_by_uuid(self):
        uuid = w_utils.generate_uuid()
        utils.create_test_efficacy_indicator(uuid=uuid)
        self.assertIsNotNone(self.dbapi.get_efficacy_indicator_by_uuid(
            self.context, uuid))
        self.dbapi.destroy_efficacy_indicator(uuid)
        self.assertRaises(
            exception.EfficacyIndicatorNotFound,
            self.dbapi.get_efficacy_indicator_by_uuid, self.context, uuid)

    def test_destroy_efficacy_indicator_that_does_not_exist(self):
        self.assertRaises(exception.EfficacyIndicatorNotFound,
                          self.dbapi.destroy_efficacy_indicator, 1234)

    def test_create_efficacy_indicator_already_exists(self):
        uuid = w_utils.generate_uuid()
        utils.create_test_efficacy_indicator(id=1, uuid=uuid)
        self.assertRaises(exception.EfficacyIndicatorAlreadyExists,
                          utils.create_test_efficacy_indicator,
                          id=2, uuid=uuid)


text:
<?php

namespace Application\Model;

use Application\Model\AbstractAppointment;
use Application\Model\AbstractInteraction;
use Application\Model\AbstractNote;
use Application\Model\AbstractTask;
use Application\Model\CampaignActivityStatus;
use Application\Model\CampaignActivityType;
use Application\Model\ChannelType;
use Application\Model\MarketingList;
use Application\Model\Regarding;
use Application\Model\SalesLiterature;
use Application\Model\TrackedActivity;
use Application\Service\OrderClosedActivitiesRequest;
use Application\Service\OrderOpenActivitiesRequest;
use Application\Service\OrderResponse;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * A campaign may include different marketing activities. Some activities, such as
 * tasks, are assigned to team members to perform specific tasks, for example,
 * preparing a marketing list or printing sales literature. Other activities, such
 * as emails, faxes, or letters are distributed through multiple campaign
 * activities represented by the campaign activity entity (CampaignActivity). Each
 * campaign activity is used to distribute one type of activity that specifies a
 * recipient: phone call, appointment, letter, letter vial mail merge, fax, fax
 * via mail merge, email, email via mail merge. The activities can be distributed
 * over a period of time and at different times.
 *
 * @package     Application\Model\Activity
 * @author		Blair <blair@kaaterskil.com>
 * @copyright	Copyright (c) 2009-2013 Kaaterskil Management, LLC
 * @version		SVN $Revision: 13 $
 *
 * @ORM\Entity
 */
class CampaignActivity extends TrackedActivity implements Regarding {

	/**
	 * The communication method for the campaign activity
	 * @ORM\Column(type="string", name="channel_type")
	 * @var ChannelType
	 */
	private $channelType;

	/**
	 * A campaign activity category
	 * @ORM\Column(type="string")
	 * @var CampaignActivityType
	 */
	private $type;

	/* ---------- One-to-Many Associations ---------- */

	/**
	 * Bidirectional One-to-Many: INVERSE SIDE
	 * @ORM\OneToMany(targetEntity="AbstractNote", mappedBy="campaignActivity", cascade={"persist"})
	 * @var ArrayCollection
	 */
	private $annotations;

	/**
	 * Bidirectional One-to-Many: INVERSE SIDE
	 * @ORM\OneToMany(targetEntity="AbstractAppointment", mappedBy="campaignActivity", cascade={"persist"})
	 * @var ArrayCollection
	 */
	private $appointments;

	/**
	 * Bidirectional One-to-Many: INVERSE SIDE
	 * @ORM\OneToMany(targetEntity="BulkOperation", mappedBy="campaignActivity", cascade={"persist"})
	 * @var ArrayCollection
	 */
	private $bulkOperations;

	/**
	 * Bidirectional One-to-Many: INVERSE SIDE
	 * @ORM\OneToMany(targetEntity="AbstractInteraction", mappedBy="campaignActivity", cascade={"persist"})
	 * @var ArrayCollection
	 */
	private $interactions;

	/**
	 * Bidirectional One-to-Many: INVERSE SIDE
	 * @ORM\OneToMany(targetEntity="AbstractTask", mappedBy="campaignActivity", cascade={"persist"})
	 * @var ArrayCollection
	 */
	private $tasks;

	/* ---------- Many-to-Many Associations ---------- */

	/**
	 * OWNING SIDE
	 * @ORM\ManyToMany(targetEntity="MarketingList")
	 * @ORM\JoinTable(name="crm_activity_list_association",
	 * 		joinColumns={@ORM\JoinColumn(name="campaign_activity_id", referencedColumnName="id")},
	 * 		inverseJoinColumns={@ORM\JoinColumn(name="list_id", referencedColumnName="id")})
	 * @var ArrayCollection
	 */
	private $lists;

	/**
	 * OWNING SIDE
	 * @ORM\ManyToMany(targetEntity="SalesLiterature")
	 * @ORM\JoinTable(name="crm_activity_literature_association",
	 * 		joinColumns={@ORM\JoinColumn(name="campaign_activity_id", referencedColumnName="id")},
	 * 		inverseJoinColumns={@ORM\JoinColumn(name="sales_literature_id", referencedColumnName="id")})
	 * @var ArrayCollection
	 */
	private $salesLiterature;

	/* ---------- Constructor ---------- */
	public function __construct() {
		parent::__construct();
		$this->annotations = new ArrayCollection();
		$this->appointments = new ArrayCollection();
		$this->bulkOperations = new ArrayCollection();
		$this->interactions = new ArrayCollection();
		$this->tasks = new ArrayCollection();
		$this->lists = new ArrayCollection();
		$this->salesLiterature = new ArrayCollection();
	}

	/* ---------- Getter/Setters ---------- */

	/**
	 * @return \Application\Model\ChannelType
	 */
	public function getChannelType() {
		return $this->channelType;
	}

	public function setChannelType($channelType = null) {
		if ($channelType instanceof ChannelType) {
			$this->channelType = $channelType;
		} elseif ($channelType != null) {
			$this->channelType = ChannelType::instance( $channelType );
		} else {
			$this->channelType = null;
		}
	}

	/**
	 * @return string
	 */
	public function getDiscriminator() {
		if($this->discriminator == null) {
			$this->discriminator = 'CampaignActivity';
		}
		return $this->discriminator;
	}

	/**
	 * @return CampaignActivityStatus
	 * @see \Application\Model\StatefulActivity::getStatus()
	 */
	public function getStatus() {
		if(($this->status != null) && (!$this->status instanceof CampaignActivityStatus)) {
			$this->status = CampaignActivityStatus::instance($this->status);
		}
		return $this->status;
	}

	public function setStatus($status = null) {
		if($status instanceof CampaignActivityStatus) {
			$this->status = $status;
		} elseif($status != null) {
			$this->status = CampaignActivityStatus::instance($status);
		} else {
			$this->status = null;
		}
	}

	/**
	 * @return \Application\Model\CampaignActivityType
	 */
	public function getType() {
		return $this->type;
	}

	public function setType($type = null) {
		if ($type instanceof CampaignActivityType) {
			$this->type = $type;
		} elseif ($type != null) {
			$this->type = CampaignActivityType::instance( $type );
		} else {
			$this->type = null;
		}
	}

	/* ---------- One-to-Many Association Getter/Setters ---------- */

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getAnnotations() {
		return $this->annotations;
	}

	public function setAnnotations(ArrayCollection $annotations) {
		$this->annotations = $annotations;
	}

	/**
	 * @param AbstractNote $note
	 */
	public function addAnnotation(AbstractNote $annotation) {
		$annotation->setCampaignActivity( $this );
		$this->annotations->add( $annotation );
	}

	/**
	 * @param AbstractNote $note
	 */
	public function removeAnnotation(AbstractNote $annotation) {
		$annotation->setCampaignActivity( null );
		$this->annotations->removeElement( $annotation );
	}

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getAppointments() {
		return $this->appointments;
	}

	public function setAppointments(ArrayCollection $appointments) {
		$this->appointments = $appointments;
	}

	/**
	 * @param AbstractAppointment $appointment
	 */
	public function addAppointment(AbstractAppointment $appointment) {
		$appointment->setCampaignActivity( $this );
		$this->appointments->add( $appointment );
	}

	/**
	 * @param AbstractAppointment $appointment
	 */
	public function removeAppointment(AbstractAppointment $appointment) {
		$appointment->setCampaignActivity( null );
		$this->appointments->removeElement( $appointment );
	}

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getBulkOperations() {
		return $this->bulkOperations;
	}

	/**
	 * @param ArrayCollection $bulkOperations
	 */
	public function setBulkOperations(ArrayCollection $bulkOperations) {
		$this->bulkOperations = $bulkOperations;
	}

	/**
	 * @param BulkOperation $bulkOperation
	 */
	public function addBulkOperation(BulkOperation $bulkOperation) {
		$bulkOperation->setCampaignActivity($this);
		$this->bulkOperations->add($bulkOperation);
	}

	/**
	 * @param BulkOperation $bulkOperation
	 */
	public function removeBulkOperation(BulkOperation $bulkOperation) {
		$bulkOperation->setCampaignActivity(null);
		$this->bulkOperations->removeElement($bulkOperation);
	}

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getInteractions() {
		return $this->interactions;
	}

	public function setInteractions(ArrayCollection $interactions) {
		$this->interactions = $interactions;
	}

	/**
	 * @param AbstractInteraction $interaction
	 */
	public function addInteraction(AbstractInteraction $interaction) {
		$interaction->setCampaignActivity( $this );
		$this->interactions->add( $interaction );
	}

	/**
	 * @param AbstractInteraction $interaction
	 */
	public function removeInteraction(AbstractInteraction $interaction) {
		$interaction->setCampaignActivity( null );
		$this->interactions->removeElement( $interaction );
	}

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getTasks() {
		return $this->tasks;
	}

	public function setTasks(ArrayCollection $tasks) {
		$this->tasks = $tasks;
	}

	/**
	 * @param AbstractTask $task
	 */
	public function addTask(AbstractTask $task) {
		$task->setCampaignActivity( $this );
		$this->tasks->add( $task );
	}

	/**
	 * @param AbstractTask $task
	 */
	public function removeTask(AbstractTask $task) {
		$task->setCampaignActivity( null );
		$this->tasks->removeElement( $task );
	}

	/* ---------- Many-to-Many Association Getter/Setters ---------- */

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getLists() {
		return $this->lists;
	}

	/**
	 * @return array
	 */
	public function getListsAsArray() {
		return $this->lists->toArray();
	}

	public function setLists(ArrayCollection $lists) {
		$this->lists = $lists;
	}

	/**
	 * @param MarketingList $list
	 */
	public function addList(MarketingList $list) {
		$list->addCampaignActivity($this);
		$this->lists->add($list);
	}

	/**
	 * @param MarketingList $list
	 */
	public function removeList(MarketingList $list) {
		$list->removeCampaignActivity($this);
		$this->lists->removeElement($list);
	}

	/**
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getSalesLiterature() {
		return $this->salesLiterature;
	}

	public function setSalesLiterature(ArrayCollection $salesLiterature) {
		$this->salesLiterature = $salesLiterature;
	}

	/**
	 * @param SalesLiterature $salesLiterature
	 */
	public function addSalesLiterature(SalesLiterature $salesLiterature) {
		$salesLiterature->addCampaignActivity($this);
		$this->salesLiterature->add($salesLiterature);
	}

	/**
	 * @param SalesLiterature $salesLiterature
	 */
	public function removeSalesLiterature(SalesLiterature $salesLiterature) {
		$salesLiterature->removeCampaignActivity($this);
		$this->salesLiterature->removeElement($salesLiterature);
	}

	/* ---------- Methods ---------- */

	/**
	 * Returns an array of closed activities
	 *
	 * @return array
	 */
	public function getClosedActivities() {
		$result = array();
		foreach ($this->getAppointments()->getValues() as $activity) {
			if(!$this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}
		foreach ($this->getInteractions()->getValues() as $activity) {
			if(!$this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}
		foreach ($this->getAnnotations()->getValues() as $activity) {
			$result[] = $activity;
		}
		foreach ($this->getTasks()->getValues() as $activity) {
			if(!$this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}

		$comparator = new OrderClosedActivitiesRequest($result);
		$response = $comparator->execute();
		if($response->getResult()) {
			$result = $response->getCollection();
		}
		return $result;
	}

	/**
	 * @param boolean $includeLink
	 * @return string
	 * @see \Application\Model\Regarding::getDisplayName()
	 */
	public function getDisplayName($includeLink = false) {
		$result = $this->getSubject();
		if(strlen($result > 25)) {
			$result = substr($result, 0, 25) . '...';
		}
		if($includeLink) {
			$campaignId = $this->getCampaign()->getId();
			$result = 'getId() . '/campaignActivity/' . $campaignId . '/campaign">' . $result . '';
		}
		return $result;
	}

	/**
	 * Returns an array of open activities
	 *
	 * @return array
	 */
	public function getOpenActivities() {
		$result = array();
		foreach ($this->getAppointments()->getValues() as $activity) {
			if($this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}
		foreach ($this->getInteractions()->getValues() as $activity) {
			if($this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}
		foreach ($this->getTasks()->getValues() as $activity) {
			if($this->isOpenActivity($activity)) {
				$result[] = $activity;
			}
		}

		$comparator = new OrderOpenActivitiesRequest($result);
		$response = $comparator->execute();
		if($response->getResult()) {
			$result = $response->getCollection();
		}
		return $result;
	}

	/**
	 * Removes any matching marketing list from the given array
	 *
	 * @param array $candidates
	 * @return array
	 */
	public function removeMatchedCandidates(array $candidates) {
		$result = array();
		foreach ($candidates as $list) {
			if(!$this->lists->contains($list)) {
				$result[] = $list;
			}
		}
		return $result;
	}

	/**
	 * @return string
	 * @see \Application\Model\AbstractActivity::__toString()
	 */
	public function __toString() {
		$result = parent::__toString();
		return $result
		. ',actualStart=' . $this->getFormattedActualStart( 'Y-m-d h:i:s' )
		. ',actualEnd=' . $this->getFormattedActualEnd( 'Y-m-d h:i:s' )
		. ',channelType=' . $this->getChannelType()
		. ',priority=' . $this->getPriority()
		. ',scheduledStart=' . $this->getFormattedScheduledStart( 'Y-m-d h:i:s' )
		. ',scheduledEnd=' . $this->getFormattedScheduledEnd( 'Y-m-d h:i:s' )
		. ',state=' . $this->getState()
		. ',status=' . $this->getStatus()
		. ',type=' . $this->getType()
		. ']';
	}

	/**
	 * Tests if the given activity is OPEN
	 *
	 * @param AbstractActivity $activity
	 * @return boolean
	 */
	private function isOpenActivity(AbstractActivity $activity) {
		if($activity instanceof StatefulActivity) {
			if(is_object($activity->getState())) {
				return ($activity->getState()->getName() == ActivityState::OPEN ? true : false);
			}
			return ($activity->getState() == ActivityState::OPEN ? true : false);
		}
		return false;
	}
}
?>


text:
#ifndef PIANO_H
#define PIANO_H

#include "Note.h"
#include "Model.h"

class InstrumentTrack;
class MidiEventProcessor;

class Piano : public Model
{
public:
	enum KeyTypes
	{
		WhiteKey,
		BlackKey
	} ;

	Piano( InstrumentTrack* track );
	virtual ~Piano();

	void setKeyState( int key, bool state );

	bool isKeyPressed( int key ) const
	{
		return m_pressedKeys[key];
	}

	void handleKeyPress( int key, int midiVelocity = -1 );
	void handleKeyRelease( int key );

	InstrumentTrack* instrumentTrack() const
	{
		return m_instrumentTrack;
	}

	MidiEventProcessor* midiEventProcessor() const
	{
		return m_midiEvProc;
	}

	static bool isWhiteKey(int key);
	static bool isBlackKey(int key);

private:
	static bool isValidKey( int key )
	{
		return key >= 0 && key < NumKeys;
	}

	InstrumentTrack* m_instrumentTrack;
	MidiEventProcessor* m_midiEvProc;
	bool m_pressedKeys[NumKeys];

} ;

#endif


text:
package mfi.filejuggler.maps;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import mfi.filejuggler.helper.StringHelper;
import mfi.filejuggler.io.FileJugglerFile;
import mfi.filejuggler.logic.Crypto;

public class FileMap {

	private static FileMap instance;

	private static final String FILE_ENCODING = "UTF-8";

	private static final Object monitor = new Object();

	private static Map<String, String> map;

	private static boolean initialized;

	private static FileJugglerFile dbFile;

	private static Logger logger = LoggerFactory.getLogger(FileMap.class);

	static {
		instance = new FileMap();
	}

	private Map<String, String> buildNewMap() {
		return Collections.synchronizedMap(new TreeMap<String, String>());
	}

	private FileMap() {
		map = buildNewMap();
		initialized = false;
		dbFile = null;
	}

	public boolean isInitialized() {
		return initialized;
	}

	public static FileMap getInstance() {
		if (instance == null) {
			synchronized (monitor) {
				if (instance == null) {
					instance = new FileMap();
					logger.info("RE-Initializing FileMap Singleton");
				}
			}
		}
		return instance;
	}

	public void reset() {
		synchronized (monitor) {
			map = buildNewMap();

		}
	}

	public boolean load(FileJugglerFile permanent) throws IOException {
		synchronized (monitor) {
			map = buildNewMap();
			boolean successPerm = loadInternal(permanent);
			if (successPerm) {
				dbFile = permanent;
				initialized = true;
			}
			return successPerm;
		}
	}

	public boolean save() throws IOException {
		synchronized (monitor) {
			saveInternal();
			return true;
		}
	}

	private boolean loadInternal(FileJugglerFile file) throws IOException {

		boolean success = true;
		List<String> lines = null;

		if (file == null) {
			logger.warn("No FileMap file to load defined.");
			return success;
		}

		if (!file.exists()) {
			file.createNewFile();
			return success;
		}

		try {
			lines = FileUtils.readLines(file, FILE_ENCODING);
		} catch (IOException e) {
			lines = new LinkedList<String>();
			success = false;
			throw new IOException("Error loading FileMap:", e);
		}

		Iterator<String> iter = lines.listIterator();
		while (iter.hasNext()) {
			map.put(iter.next(), iter.hasNext() ? iter.next() : null);
		}

		return success;
	}

	private void saveInternal() throws IOException {

		if (dbFile == null) {
			logger.error("No FileMap file to save defined.");
			return;
		}

		if (!dbFile.exists()) {
			dbFile.createNewFile();
		}

		List<String> linesToWritePermanent = new LinkedList<String>();
		Object[] keys = map.keySet().toArray();
		for (Object key : keys) {
			linesToWritePermanent.add(StringUtils.trimToEmpty((String) key));
			linesToWritePermanent.add(StringUtils.trimToEmpty(readEditor(new File((String) key))));
		}

		String currentSavedFileHash = Crypto.hashString(StringHelper.stringFromList(dbFile.readIntoLines()));
		String currentWorkingMapHash = Crypto.hashString(StringHelper.stringFromList(linesToWritePermanent));

		if (!StringUtils.equals(currentSavedFileHash, currentWorkingMapHash)) {
			logger.info("save()");
			FileUtils.writeLines(dbFile, FILE_ENCODING, linesToWritePermanent);
			dbFile.backupFile(null);
		}

	}

	private boolean containsKey(String key) {
		return map.containsKey(key);
	}

	public String updateEditor(File file, String user) {
		return map.put(file.getAbsolutePath(), user);
	}

	public String readEditor(File file) {
		if (containsKey(file.getAbsolutePath())) {
			return StringUtils.trimToNull(map.get(file.getAbsolutePath()));
		} else {
			return null;
		}
	}

	public void updateList(Collection<FileJugglerFile> list) {
		synchronized (monitor) {
			for (FileJugglerFile file : list) {
				if (!containsKey(file.getAbsolutePath())) {
					logger.info("update " + file.getAbsolutePath());
					updateEditor(file, null);
				}
			}
		}
	}

	public void deleteOrphans() {
		synchronized (monitor) {
			Object[] keys = map.keySet().toArray();
			for (Object key : keys) {
				File file = new File((String) key);
				if (!file.exists()) {
					logger.info("remove " + key);
					map.remove(key);
				}
			}
		}
	}

}


text:
RSpec.describe ROM::HTTP::Commands::Update do
  include_context "setup"

  let(:relation_class) do
    Class.new(ROM::HTTP::Relation) do
      schema(:users) do
        attribute :id, ROM::Types::Integer
        attribute :first_name, ROM::Types::String
        attribute :last_name, ROM::Types::String
      end

      def by_id(id)
        with_query_params(id: id)
      end
    end
  end

  let(:relation) { container.relations[:users] }

  context "with single tuple" do
    let(:response) { double }

    let(:attributes) { {first_name: "John", last_name: "Jackson"} }

    let(:tuple) { attributes.merge(id: 1) }

    let(:command) { relation.command(:update) }

    let(:dataset) do
      ROM::HTTP::Dataset.new(
        uri: uri,
        base_path: :users,
        headers: headers,
        request_handler: request_handler,
        response_handler: response_handler,
        request_method: :put,
        body_params: attributes
      )
    end

    before do
      configuration.register_relation(relation_class)

      allow(request_handler).to receive(:call).and_return(response)
      allow(response_handler).to receive(:call).and_return(tuple)
    end

    subject! { command.call(attributes) }

    it do
      is_expected.to eq(tuple)

      expect(request_handler).to have_received(:call).with(dataset)
      expect(response_handler).to have_received(:call).with(response, dataset)
    end
  end

  context "with a collection" do
    let(:response_1) { double }

    let(:response_2) { double }

    let(:attributes_1) { {first_name: "John", last_name: "Jackson"} }

    let(:attributes_2) { {first_name: "Jill", last_name: "Smith"} }

    let(:tuple_1) { attributes_1.merge(id: 1) }

    let(:tuple_2) { attributes_2.merge(id: 2) }

    let(:attributes) { [attributes_1, attributes_2] }

    let(:command) { relation.command(:update, result: :many) }

    let(:dataset_1) do
      ROM::HTTP::Dataset.new(
        uri: uri,
        headers: headers,
        request_handler: request_handler,
        response_handler: response_handler,
        base_path: :users,
        request_method: :put,
        body_params: attributes_1
      )
    end

    let(:dataset_2) do
      ROM::HTTP::Dataset.new(
        uri: uri,
        headers: headers,
        request_handler: request_handler,
        response_handler: response_handler,
        base_path: :users,
        request_method: :put,
        body_params: attributes_2
      )
    end

    before do
      configuration.register_relation(relation_class)

      allow(request_handler).to receive(:call).and_return(response_1, response_2)
      allow(response_handler).to receive(:call).and_return(tuple_1, tuple_2)
    end

    subject! { command.call(attributes) }

    it do
      expect(request_handler).to have_received(:call).with(dataset_1)
      expect(response_handler).to have_received(:call).with(response_1, dataset_1)
      expect(request_handler).to have_received(:call).with(dataset_2)
      expect(response_handler).to have_received(:call).with(response_2, dataset_2)
      is_expected.to eq([tuple_1, tuple_2])
    end
  end
end


text:
@implementation IFPropertyInfo

- (id)init {
    self = [super init];
    if (self) {
        _propertyClass = [NSObject class];
        _propertyType = [NSString stringWithUTF8String:@encode(id)];
    }
    return self;
}

- (id)initAsWriteable {
    self = [self init];
    if (self) {
        _isWriteable = YES;
    }
    return self;
}

- (id)initWithProperty:(objc_property_t)property {
    self = [super init];
    if (self) {
        _propertyClass = nil;

        // Read property attributes.
        const char * chattr = property_getAttributes( property );

        // Convert to nsstring and tokenize
        NSString *nsattr = [NSString stringWithUTF8String:chattr];
        NSArray *attrs = [nsattr componentsSeparatedByString:@","];

        // Get the property type.
        NSString *typeAttr = [attrs firstObject];
        _propertyType = [typeAttr substringFromIndex:1];

        // Try extracting class info.
        if ([typeAttr hasPrefix:@"T@"] && [typeAttr length] > 4) {
            // The type specifies a property type name in the form e.g. T@"NSData"
            // Note that if no class info is available then the attr will be just 'T@'
            NSRange range = NSMakeRange(3, [typeAttr length] - (1 + 3));
            NSString *className = [typeAttr substringWithRange:range];
            _propertyClass = NSClassFromString(className);
        }

        // Try extracting protocol info, assuming format @"<ProtocolName>"
        _propertyProtocol = nil;
        if ([_propertyType hasPrefix:@"@\"<"]) {
            NSRange range = NSMakeRange(3, [_propertyType length] - (2 + 3));
            NSString *protocolName = [_propertyType substringWithRange:range];
            _propertyProtocol = NSProtocolFromString(protocolName);
        }

        // Check for read-only flag.
        _isWriteable = ![attrs containsObject:@"R"];
    }
    return self;
}

- (id)initAsWriteableWithClass:(__unsafe_unretained Class)classObj {
    self = [super init];
    if (self) {
        _propertyClass = classObj;
        _propertyType = @"";
        _isWriteable = YES;
    }
    return self;
}

- (id)initAsWriteableWithProtocol:(Protocol *)protocol {
    self = [super init];
    if (self) {
        _propertyClass = NULL;
        _propertyType = @"";
        _propertyProtocol = protocol;
        _isWriteable = YES;
    }
    return self;
}

- (BOOL)isBoolean {
    return strcmp(_propertyType.UTF8String, @encode(BOOL)) == 0 || strcmp(_propertyType.UTF8String, @encode(Boolean)) == 0;
}

- (BOOL)isInteger {
    return strcmp(_propertyType.UTF8String, @encode(int)) == 0 || strcmp(_propertyType.UTF8String, @encode(NSInteger)) == 0;
}

- (BOOL)isFloat {
    return strcmp(_propertyType.UTF8String, @encode(float)) == 0 || strcmp(_propertyType.UTF8String, @encode(CGFloat)) == 0;
}

- (BOOL)isDouble {
    return strcmp(_propertyType.UTF8String, @encode(double)) == 0;
}

- (BOOL)isId {
    return strcmp(_propertyType.UTF8String, @encode(id)) == 0;
}

- (BOOL)isAssignableFrom:(__unsafe_unretained Class)classObj {
    if ([self isId]) {
        return YES;
    }
    if (_propertyClass) {
        return [classObj isSubclassOfClass:_propertyClass];
    }
    if (_propertyProtocol) {
        return [classObj conformsToProtocol:_propertyProtocol];
    }
    // Numeric types will have no property class info, but NSNumber can be assigned to them.
    if ([classObj isSubclassOfClass:[NSNumber class]]) {
        return [self isBoolean] || [self isInteger] || [self isFloat] || [self isDouble];
    }
    return NO;
}

- (BOOL)isMemberOrSubclassOf:(__unsafe_unretained Class)classObj {
    return [_propertyClass isSubclassOfClass:classObj];
}

- (__unsafe_unretained Class)getPropertyClass {
    return _propertyClass;
}

- (BOOL)isWriteable {
    return _isWriteable;
}

@end

@implementation IFTypeInfo

// Cache of class property sets, keyed by class name.
static NSMutableDictionary *SCTypeInfo_propertiesByClassName;
// Cache of type info instances, keyed by class name.
static NSMutableDictionary *SCTypeInfo_typeInfoCache;

+ (void)initialize {
    SCTypeInfo_propertiesByClassName = [NSMutableDictionary new];
    SCTypeInfo_typeInfoCache = [NSMutableDictionary new];
}

// TODO: Define a protocol that allows this class to directly interrogate an object for a list of
// configurable properties. The following can potentially be expensive (e.g. a table view having
// 150+ properties) and whilst chaching of type info objects by class name would avoid any performance
// issues, the full set of properties is not needed and having a protocol for declaring configurable
// properties would also help document the supported properties. Note that the protocol should define
// static methods on the class, and should be optional i.e. this class reverts to its original mode
// of operation if the object doesn't implement the protocol.
- (id)initWithObject:(id)object {
    self = [super init];
    if (self) {
        Class class = [object class];
        NSString *className = NSStringFromClass(class);
        // Check for cached properties for the current object's class name.
        _properties = [SCTypeInfo_propertiesByClassName objectForKey:className];

        if (_properties == nil) {

            // No cached properties found, so start building a property set for the class hierarchy.
            _properties = [[NSMutableDictionary alloc] init];

            // Build an array of classes representing the class hierarchy, from sub-class to super-class.
            NSMutableArray *hierarchy = [NSMutableArray new];
            while (class) {
                [hierarchy addObject:class];
                class = [class superclass];
            }

            // See if cached properties exists for any class in the hierarchy, and if so then use the
            // result for the lowest (i.e. closest to the sub-class) class in the hierarchy with a cached
            // result.
            NSArray *classes = hierarchy; // The list of classes to later resolve properties for.
            for (NSInteger i = 0; i < [hierarchy count]; i++) {
                class = [hierarchy objectAtIndex:i];
                className = NSStringFromClass(class);
                // Check in the cache...
                NSDictionary *classProperties = [SCTypeInfo_propertiesByClassName objectForKey:className];
                // ...if cached properties found...
                if (classProperties) {
                    // ...then add the cached property set to the set of properties for this class...
                    [_properties addEntriesFromDictionary:classProperties];
                    // ...and remove the classes further up the hierarchy from the property search.
                    // This means that the property search below will only look for properties on the
                    // classes which inherit from the current class.
                    NSRange subrange = NSMakeRange(0, i);
                    classes = [hierarchy subarrayWithRange:subrange];
                    break;
                }
            }

            // Search for properties on the remaining classes in the class hierarchy.
            unsigned int propCount;
            // Property sets for each intermediate class remaining in the hierarchy are cached,
            // so process the classes in reverse order (i.e. super-class to sub-class order).
            for (Class class in [classes reverseObjectEnumerator]) {
                objc_property_t * props = class_copyPropertyList(class, &propCount);
                for (NSInteger i = 0; i < propCount; i++) {
                    objc_property_t prop = props[i];

                    NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];

                    // Skip nil property names.
                    if (propName == nil) continue;

                    // Skip properties beginning with '_'; there are quite a lot of these on iOS core classes,
                    // and the presumably indicate private properties.
                    if ([propName hasPrefix:@"_"]) continue;

                    // Otherwise map the property.
                    IFPropertyInfo *propInfo = [[IFPropertyInfo alloc] initWithProperty:prop];
                    [_properties setObject:propInfo forKey:propName];
                }

                // Add a copy of the property set to the cache.
                className = NSStringFromClass(class);
                [SCTypeInfo_propertiesByClassName setObject:[_properties copy] forKey:className];
            }
        }
    }
    return self;
}

- (IFPropertyInfo *)infoForProperty:(NSString *)propName {
    return [_properties valueForKey:propName];
}

+ (IFTypeInfo *)typeInfoForObject:(id)object {
    NSString *className = NSStringFromClass([object class]);
    IFTypeInfo *typeInfo = [SCTypeInfo_typeInfoCache objectForKey:className];
    if (typeInfo == nil) {
        typeInfo = [[IFTypeInfo alloc] initWithObject:object];
        [SCTypeInfo_typeInfoCache setObject:typeInfo forKey:className];
    }
    return typeInfo;
}

+ (void)clearCache {
    [SCTypeInfo_propertiesByClassName removeAllObjects];
    [SCTypeInfo_typeInfoCache removeAllObjects];
}

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Bad Philophobia: pkg_game.UserInterface Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Bad Philophobia

Main Page

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Namespaces Files Functions Variables

pkg_game

UserInterface

Public Member Functions |
List of all members

pkg_game.UserInterface Class Reference

Class handling the game's user interface.
 More...

Inheritance diagram for pkg_game.UserInterface:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Collaboration diagram for pkg_game.UserInterface:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Public Member Functions

 	UserInterface (GameEngine gameEngine)

 	UserInterface class constructor.  More...

void 	setCommandsLeft (int commandsLeft)

 	Change the text for the commands left JLabel.  More...

void 	print (String text)

 	Print the given text in the text area.  More...

void 	println (String text)

 	Print the given text plus a newline in the text area.  More...

void 	showImage (String imageName)

 	Show the image corresponding to the path of the image.  More...

void 	enable (boolean on)

 	Enable or disable the input field.  More...

void 	actionPerformed (ActionEvent e)

 	Actionlistener for the textfield.  More...

Detailed Description

Class handling the game's user interface.

Author

Rémi NICOLE

Definition at line 15 of file UserInterface.java.

Constructor & Destructor Documentation

          pkg_game.UserInterface.UserInterface
          (
          GameEngine
          gameEngine	)

UserInterface class constructor.

Parameters

gameEngine	The gameplay GameEngine object.

Definition at line 56 of file UserInterface.java.

   56                                                 {

   57         engine = gameEngine;

   58         buttons = new HashMap<JButton, String>();

   59         createGUI();

   60     }

Member Function Documentation

          void pkg_game.UserInterface.actionPerformed
          (
          ActionEvent
          e	)

Actionlistener for the textfield.

Parameters

e	Event

Definition at line 214 of file UserInterface.java.

  214                                                {

  215

  216         if(e.getSource() == entryField) {

  217             processCommand();

  218             return;

  219         }

  220

  221         String command = buttons.get(((JButton)e.getSource()));

  222

  223         if(command == null)

  224             processCommand();

  225         else if(command.equals(""))

  226             processCommand();

  227         else

  228             engine.processCommand(command);

  229     }

          void pkg_game.UserInterface.enable
          (
          boolean
          on	)

Enable or disable the input field.

Parameters

on	True to activate, False to deactivate

Definition at line 107 of file UserInterface.java.

  107                                    {

  108         entryField.setEditable(on);

  109         entryField.setEnabled(on);

  110         if(!on)

  111             entryField.getCaret().setBlinkRate(0);

  112

  113         for (JButton button : buttons.keySet()) {

  114             button.setEnabled(on);

  115         }

  116

  117         commandsLeftLabel.setEnabled(on);

  118     }

          void pkg_game.UserInterface.print
          (
          String
          text	)

Print the given text in the text area.

Parameters

text	Text to display

Definition at line 74 of file UserInterface.java.

   74                                    {

   75         log.append(text);

   76         log.setCaretPosition(log.getDocument().getLength());

   77     }

          void pkg_game.UserInterface.println
          (
          String
          text	)

Print the given text plus a newline in the text area.

Parameters

text	Text to display

Definition at line 83 of file UserInterface.java.

Referenced by pkg_game.GameEngine.processCommand().

   83                                      {

   84         log.append(text + "\n");

   85         log.setCaretPosition(log.getDocument().getLength());

   86     }

Here is the caller graph for this function:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

          void pkg_game.UserInterface.setCommandsLeft
          (
          int
          commandsLeft	)

Change the text for the commands left JLabel.

Parameters

commandsLeft	The number of commands left

Definition at line 66 of file UserInterface.java.

   66                                                   {

   67         commandsLeftLabel.setText(" Commands left: " + commandsLeft + "  ");

   68     }

          void pkg_game.UserInterface.showImage
          (
          String
          imageName	)

Show the image corresponding to the path of the image.

Parameters

imageName	The path of the image

Definition at line 92 of file UserInterface.java.

   92                                             {

   93         URL imageURL = this.getClass().getClassLoader().getResource(imageName);

   94         if(imageURL == null)

   95             System.out.println("image not found");

   96         else {

   97             ImageIcon icon = new ImageIcon(imageURL);

   98             image.setIcon(icon);

   99             myFrame.pack();

  100         }

  101     }

The documentation for this class was generated from the following file:

pkg_game/UserInterface.java

<address class="footer">
Generated on Mon Jun 9 2014 21:28:30 for Bad Philophobia by

 1.8.6
</address>


text:
'use strict';

module.exports = require.requireActual('callsToGraphQL');


text:
layout: default
class: home
hide_breadcrumbs: true
title: Choose an open source license
permalink: /
---

  {
  Which of the following best describes your situation?
  }

I want it simple and permissive.

      The MIT License is a permissive license that is short and to the point. It lets people do anything they want with your code as long as they provide attribution back to you and don't hold you liable.

      {% include using-sentence.html license-id="mit" %}

I'm concerned about patents.

      The Apache License 2.0 is a permissive license similar to the MIT License, but also provides an express grant of patent rights from contributors to users.

      {% include using-sentence.html license-id="apache-2.0" %}

I care about sharing improvements.

      The GNU GPLv3 is a copyleft license that requires anyone who distributes your code or a derivative work to make the source available under the same terms, and also provides an express grant of patent rights from contributors to users.

      {% include using-sentence.html license-id="gpl-3.0" %}

  {
  What if none of these work for me?
  }

My project isn't software.

      There are licenses for that.

I want more choices.

      More licenses are available.

I don't want to choose a license.

      You don't have to.


text:
// ==UserScript==

// @name          Udacity Plus

// @namespace     https://udacityplus.appspot.com

// @description   Enhances Udacity lessons

// @match       http*://udacityplus.appspot.com/*
// @match       http*://*.udacity.com/*
// @match       http*://udacity.com/*

// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

// @download      https://udacityplus.appspot.com/static/udacityplus.user.js

// @version       0.1.1351

// ==/UserScript==

// Looking at the udacity.com html code there is already a bunch of material there
// that was removed for launch

/*div.uplus-article{ border-bottom: 1px solid gray; }*/
/*To do:
  - Fix caching of materials
  - Have notes go somewhere reasonable
  - Provide a proper article feed
  - Create somewhere to easily edit materials and articles
  - Make stuff look good
  - Change article to be of format {"link": link, "author": author, "description": description}.
    That way all article formatting can be done in-script straight from datastore feed.
  - Consider removing the course subcategory from materials to bring it in line with notes.
    Will mean more bandwidth used when pulling materials from server, so prefer not to.
  - Add a version check function
*/

var path = String(window.location); // full url
var host = window.location.host; // subdomain.domain.tld

if (host.indexOf("udacity.com") != -1) {
    // Create an overlay for articles
    var article_overlay_html = '

';
    GM_addStyle("div.uplus#article-overlay {"+
        "padding: 5px !important;"+
        "display:none; "+
        "position: absolute; "+ // absoulte creates an overlay
        "margin-left: 250px; margin-top: 22px; z-index:100; "+
        "background: #FFFFFF; border: solid 1px #1C78AA; "+
        "font-size: 12px; "+
        "color: black; "+
        "width: 500px; height: auto;} "+//height: 600px;} "+
        "span.uplus-score {color: #1C78AA; font-weight:bold;} "+
        "div.uplus-article {border: 1px solid gray; padding: 5px !important;} "+
        "a.uplus-link {color: #1C78AA; font-weight:bold;} ");
    // Set style of upvote buttons
    GM_addStyle("a.uplus-upvote {"+
        "font-size: 18px;"+
        "border:2px solid #1C78AA;"+
        "background: #FFF no-repeat 4px 5px;"+
        "text-decoration: none;"+
        "border-radius: 5px;"+
        "}\n"+
        "a.uplus-upvote:hover, a.uplus-upvote:focus, a.uplus-upvote.selected {"+
        //"border:2px solid #000000;"+
        "background: #00FF00;}");

    // Function to set the content, both in the overlay, if already created,
    // and in the overlay filler html
    function setContent(content) {
        if (typeof content !== "string") {
            content = "
An error occurred retrieving the articles."+
            "Please try again or contact the Udacity Plus author
";
        }
        article_overlay_html = '
'+content+'
';
        jQuery("div.uplus#article-overlay").html(content);
    }

    // Articles should be cached for an hour
    // Get content (via ajax or from storage) and put it into the article overlay
    var retrieval = GM_getValue('udacity plus articles', false);
    if (retrieval) {
        try {
            var asJSON = JSON.parse(retrieval);
            if ((asJSON["timestamp"] + 3600*1000) < new Date().getTime()) {
                // Cache expires after 1 hour
                retrieval = false;
            } else {
                setContent(asJSON["content"]);
            }
        } catch(e) {
            // In case **** happens, e.g. corrupted cache
            retrieval = false;
        }
    }

    // Retrieve user token and settings, if stored
    var local_data = GM_getValue("udacity plus settings", false);
    var settings = false;
    var token = false;
    if (local_data) {
        local_data = JSON.parse(local_data);
        if ("settings" in local_data) {
            settings = local_data["settings"];
        } else {
            settings = {};
        }
        if ("token" in local_data) {
            token = local_data["token"];
        }
    } else {
        settings = {};
    }

    function updateSettings() {
        // Makes use of globals (token, settings)
        var storage = {"token": token, "settings": settings};
        GM_setValue('udacity plus settings', JSON.stringify(storage));
    }

    function upvote(link){
        settings[link] = true;
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://udacityplus.appspot.com/api/articles/upvote",
            data: "link="+encodeURIComponent(link)+"&token="+encodeURIComponent(token),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload: function(response) {
                response = JSON.parse(response.responseText); // Check that it worked
                //console.log("Upvoted: "+link);
                updateSettings();
            }
        });
    }

    function devote(link){
        settings[link] = false;
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://udacityplus.appspot.com/api/articles/devote",
            data: "link="+encodeURIComponent(link)+"&token="+encodeURIComponent(token),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload: function(response) {
                response = JSON.parse(response.responseText);
                //console.log(response["content"]); // Check that it worked
                updateSettings();
            }
        });
    }

    function isSelected(link){
        if (link in settings && settings[link]) {
            return true;
        } else {
            return false;
        }
    }

    retrieval = false; // Testing only

    // Retrieve articles from server
    if (!retrieval && host.indexOf("udacity.com") != -1) {
        // Retrieve data via XHR
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://udacityplus.appspot.com/api/articles/get",
            data: "token="+encodeURIComponent(token),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload: function(response) {
                //console.log(response.responseText); // For testing
                var response = JSON.parse(response.responseText);
                var articles = response["content"]; // articles is an array
                var content = "";
                for (index in articles) {
                    content += '
'+
                        articles[index]+'
\n';
                }
                //console.log(content);
                if (!token || token !== response["token"]) {
                    token = response["token"];
                    updateSettings();
                }
                var storage = {"content": content, "timestamp": new Date().getTime()};
                GM_setValue('udacity plus articles', JSON.stringify(storage));
                setContent(content);
            }
        });
    }

    // If clicking outside the article overlay, hide it
    jQuery(document).mouseup(function (event) {
        var container = jQuery("div.uplus#article-overlay");
        if (container.has(event.target).length === 0) {
            container.hide();
        }
    });

    // MATERIALS section
    var materialCache = GM_getValue('udacity plus materials', { });
    var courseMaterial = { }; // associative array of notes for this course
    var course = jQuery("span#top-course-title").text().trim();
    /* Need to find a better way to obtain the course */
    course = window.location.hash.substr(8, 5); // "#Course/cs253/"

    //materialCache = { }; // Clears cache for testing

    // Materials should be cached for an hour
    // If cache empty or stale, retrieve via AJAX
    if (materialCache !== { }) {
        try {
            materialCache = JSON.parse(materialCache);
            if (course in materialCache) {
                courseMaterial = asJSON[course];
                if ((courseMaterial["timestamp"] + 3600*1000) < new Date().getTime()) {
                    // Cache expires after 1 hour
                    courseMaterial = false;
                }
            } else {
                courseMaterial = false;
            }
        } catch(e) {
            // In case **** happens, e.g. corrupted cache, or format change
            courseMaterial = false;
        }
    }

    // Retrieve materials from server
    if (!courseMaterial && host.indexOf("udacity.com") != -1) {
        // Retrieve data via XHR
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://udacityplus.appspot.com/api/coursematerials/get",
            data: "token="+encodeURIComponent(token)+"&course="+encodeURIComponent(course),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload: function(response) {
                var response = JSON.parse(response.responseText);
                courseMaterial = response["content"]
                if (!token || token !== response["token"]) { // Update token
                    token = response["token"];
                    updateSettings();
                }
                // Cache material for this course
                courseMaterial["timestamp"] = new Date().getTime();
                materialCache[course] = courseMaterial
                GM_setValue("udacity plus materials", JSON.stringify(materialCache));
                // Add text to field by manually calling hashChanged();
                hashChanged();
            }
        });
    }

    // Update material panel with content for this lesson
    function setMaterialPanel(hashLink) {
        var content = "
No extra material available for this lesson, why not add some using the U+ Notes feature?
";
        if (typeof courseMaterial !== "object") {
            content = "
An error was encountered while loading U+ Materials, please try again.
";
        } else if (hashLink in courseMaterial) {
            content = courseMaterial[hashLink];
        }
        jQuery("div#tab-uplus-materials").html(content);
    }

    // NOTES section
    var allNotes = JSON.parse(GM_getValue("udacity plus notes", "{ }")); // This collects notes for every course

    // Save the notes
    function saveNotes() {
        // Get the current notes
        var currentNotes = jQuery("textarea#uplus-notes").val();
        // Get the link these notes are for
        var oldHash = jQuery("textarea#uplus-notes").attr("name");
        if (oldHash) {
            if (oldHash in allNotes && allNotes[oldHash] != currentNotes) {
                // New notes overwrite existing notes
                allNotes[oldHash] = currentNotes;
                // Store notes dict locally
                GM_setValue("udacity plus notes", JSON.stringify(allNotes));
            } else if (currentNotes.length > 0) {
                // Create new (nonblank) entry in allNotes
                allNotes[oldHash] = currentNotes;
                // Store notes dict locally
                GM_setValue("udacity plus notes", JSON.stringify(allNotes));
            } // The checks above prevent unneccessary storing
        }
    }

    // Clear saved notes for a given hash
    function clearNotes() {
        var currentHash = jQuery("textarea#uplus-notes").attr("name");
        // Ensure hash is currently in notes (otherwise we get an error)
        if (currentHash in allNotes) {
            delete allNotes[currentHash];
            GM_setValue("udacity plus notes", JSON.stringify(allNotes));
        }
        jQuery("textarea#uplus-notes").val("");
    }

    // The hash (#) url changed, so try to load new nugget's materials
    function hashChanged() {
        var localHash = window.location.hash;
        // Update materials
        setMaterialPanel(localHash);
        // Save any notes made
        saveNotes();
        // Update the notes from cache for the new hash
        if (localHash in allNotes) {
            jQuery("textarea#uplus-notes").val(allNotes[localHash]);
        } else {
            jQuery("textarea#uplus-notes").val(""); // Default text
        }
        // Store the new hash in the textarea as the name for future reference
        jQuery("textarea#uplus-notes").attr("name", localHash);
    }

    // Ensure notes are saved when leaving the page
    jQuery(window).unload(function(event) {
        saveNotes();
    });

} // End Udacity-only section

// Wait for everything to be loaded
window.addEventListener("load", function(e) {
    // Site is udacityplus.appspot.com:
    if (host.indexOf("udacityplus.appspot.com") != -1) {
        jQuery("a.install_button").html("Udacity Plus is already installed!");
        jQuery("div#install_script").removeAttr("id");
    }

    // Site is udacity.com:
    if (host.indexOf("udacity.com") != -1) {
        // Detect if the local hash address has changed
        window.onhashchange = hashChanged;

        // Make the U+ additions more obvious
        GM_addStyle("li.uplus {border: solid 1px #1C78AA;}");

        // SECTION articles
        var progress_link = jQuery("li.topnav").last();
        // Clicking default tabs must remove the active state from U+ tabs
        jQuery("a", jQuery("li.topnav")).click(function(event){
            jQuery("li.topnav.uplus").removeClass("selected");
        });
        // Create new topnav for articles
        var article_link = progress_link.clone();
        article_link.html('Articles');//article_link.html('Articles');
        article_link.addClass("uplus");
        progress_link.after(article_link);
        article_link.after(article_overlay_html);
        article_overlay = jQuery("div.uplus#article-overlay");

        // Add click events:
        article_link.click(function(event){
            article_overlay.show();
            return false;
        });

        // Add U+ upvote functionality
        if (host.indexOf("forums.udacity.com") != -1) {
            var insert = ' +

';
            var questionUpVote = jQuery(insert); // Create a new DOM element
            jQuery("div#favorite-count").after(questionUpVote);
            if (isSelected(path)) {
                jQuery(questionUpVote).addClass("selected");
            }
            questionUpVote.click(function(event){
                event.preventDefault();
                if (jQuery(this).hasClass("selected")) {
                    jQuery(this).removeClass("selected");
                    devote(path);
                } else {
                    jQuery(this).addClass("selected");
                    upvote(path);
                }
                this.blur();
            });

            jQuery("div.answer").each(function(index){
                var answerUpVote = jQuery(insert);
                jQuery("a.post-vote.down", this).after(answerUpVote);
                var answerID = jQuery(this).prev("a").attr("name");
                var link = path+"#"+answerID
                if (isSelected(link)) {
                    answerUpVote.addClass("selected");
                }
                answerUpVote.click(function(event){
                    event.preventDefault();
                    if (jQuery(this).hasClass("selected")) {
                        jQuery(this).removeClass("selected");
                        devote(link);
                    } else {
                        jQuery(this).addClass("selected");
                        upvote(link);
                    }
                    this.blur();
                });
            });
        }

        // MATERIALS section
        var tab_supplementary = jQuery('a[href="#tab-follow"]');
        // Create a
 for Udacity Plus Materials
        var uplus_materials_tab = tab_supplementary.parent().clone();
        uplus_materials_tab.addClass("uplus");
        var uplus_notes_tab = uplus_materials_tab.clone();

        // Clicking default tabs must remove the active state from U+ tabs
        // and also hide U+ panels
        jQuery("a", jQuery("li.ui-state-default")).click(function(event){
            jQuery("li.ui-state-default.uplus").removeClass(
                "ui-tabs-selected ui-state-active");
            jQuery("div.uplus.ui-tabs-panel").addClass("ui-tabs-hide");
        });

        // Change text and link binding for U+ Materials
        jQuery("a", uplus_materials_tab).html("U+ Materials");
        jQuery("a", uplus_materials_tab).attr("href", "#tab-uplus-materials");
        // Add tab:
        tab_supplementary.parent().after(uplus_materials_tab);
        // Create a div area for the content
        jQuery("div#tab-follow").after('
\n'+
                '
\n'+
                    '
Some sample materials here
\n'+
                '
\n'+
            '
\n')
        // Add click events:
        jQuery("a", uplus_materials_tab).click(function(event){
            event.preventDefault();
            jQuery("li.ui-tabs-selected.ui-state-active"). // Deselects current active tab
                removeClass("ui-tabs-selected ui-state-active");
            jQuery("div.ui-tabs-panel").addClass("ui-tabs-hide"); // Hide all panels
            jQuery(uplus_materials_tab).addClass("ui-tabs-selected ui-state-active");
            jQuery("div#tab-uplus-materials").removeClass("ui-tabs-hide"); // Show materials panel
        });
        // Add text to field by manually calling hashChanged();
        hashChanged();

        // NOTES section
        // Change text and link binding for U+ Notes
        jQuery("a", uplus_notes_tab).html("U+ Notes");
        jQuery("a", uplus_notes_tab).attr("href", "#tab-uplus-notes");
        // Add tab:
        jQuery(uplus_materials_tab).after(uplus_notes_tab);
        // Create a div area for the content
        jQuery("div#tab-uplus-materials").after('
\n'+
                '
\n'+
                    '
<textarea id="uplus-notes" rows="8" cols="120"></textarea>
'+//'
Enter notes here
\n'+
                    '
Send to U+
\n'+//Testing/populating only
                    '
Clear notes
'+
                '
\n'+
            '
\n')
        // Add click events to tab:
        jQuery("a", uplus_notes_tab).click(function(event){
            event.preventDefault();
            jQuery("li.ui-tabs-selected.ui-state-active"). // Deselects current active tab
                removeClass("ui-tabs-selected ui-state-active");
            jQuery("div.ui-tabs-panel").addClass("ui-tabs-hide"); // Hide all panels
            jQuery(uplus_notes_tab).addClass("ui-tabs-selected ui-state-active");
            jQuery("div#tab-uplus-notes").removeClass("ui-tabs-hide"); // Show notes panel
        });
        // Add submit option for button
        /*currently used for testing*/
        jQuery("div#uplus-notes-submit").click(function(event){
            event.preventDefault();
            var content = jQuery("textarea#uplus-notes").val();
            GM_xmlhttpRequest({
                method: "POST",
                url: "https://udacityplus.appspot.com/api/coursematerials/set",
                data: "token="+encodeURIComponent(token)+"&course="+encodeURIComponent(course)+"&content="+encodeURIComponent(content)+
                "&hash_link="+encodeURIComponent(window.location.hash),
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                onload: function(response) {
                    console.log("Sent notes to server: "+response.responseText);
                }
            });
        });
        // Enable clearing of notes
        jQuery("div#uplus-notes-clear").click(function(event){
            clearNotes();
        });
    }
}, false);


text:
@interface NSString (BJCFVersion)

-(BOOL)BJCF_isOlderThanVersion:(NSString *)version;
-(BOOL)BJCF_isNewerThanVersion:(NSString *)version;
-(BOOL)BJCF_isEqualToVersion:(NSString *)version;
-(BOOL)BJCF_isEqualOrOlderThanVersion:(NSString *)version;
-(BOOL)BJCF_isEqualOrNewerThanVersion:(NSString *)version;

@end


text:
namespace Boring32::Compression
{
	class Decompressor
	{
		public:
			virtual ~Decompressor();
			Decompressor();

			Decompressor(const Decompressor& other);
			virtual Decompressor& operator=(const Decompressor& other);

			Decompressor(Decompressor&& other) noexcept;
			virtual Decompressor& operator=(Decompressor&& other) noexcept;

			Decompressor(const CompressionType type);

		public:
			virtual void Close();

			/// <summary>
			///		Returns the type of algorithm of this decompressor.
			/// </summary>
			/// <returns>The algorithm used by this decompressor.</returns>
			[[nodiscard]] virtual CompressionType GetType() const;

			/// <summary>
			///		Returns the uncompressed size, in bytes, of the compressed buffer specified in the parameter.
			/// </summary>
			/// <param name="buffer">The buffer to determine the uncompressed size of.</param>
			/// <returns>The uncompressed size, in bytes, of the compressed buffer specified in the parameter</returns>
			[[nodiscard]] virtual size_t GetDecompressedSize(const std::vector<std::byte>& compressedBuffer) const;

			/// <summary>
			///		Returns a buffer that is the decompressed data of the input argument, buffer.
			/// </summary>
			/// <param name="buffer">The buffer to decompress.</param>
			/// <returns>The decompressed buffer.</returns>
			[[nodiscard]] virtual std::vector<std::byte> DecompressBuffer(const std::vector<std::byte>& compressedBuffer);

		protected:
			virtual void Create();
			virtual void Copy(const Decompressor& other);
			virtual void Move(Decompressor& other) noexcept;

		protected:
			CompressionType m_type;
			DECOMPRESSOR_HANDLE m_decompressor;
	};
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.addthis.hydra.data.filter.bundle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.addthis.bundle.core.Bundle;
import com.addthis.bundle.core.BundleField;
import com.addthis.bundle.util.AutoField;
import com.addthis.codec.annotations.FieldConfig;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * This {@link BundleFilter BundleFilter} randomly selects an input field and copies it to an output field.
 *

 *
The possible input fields are specified with {@link #inFields inFields}. Of the possible
 * input fields only those with non-null values are considered. One of the eligible values
 * is randomly selected and copied into the output field.

 *

 *
Example:

 *

 *   {random-field {inFields: ["INPUT1", "INPUT2", "INPUT3"], out: "OUTPUT"}}
 *

 *
 * @user-reference
 */
public class BundleFilterRandomField implements BundleFilter {

    /**
     * The possible input bundle fields from which one will be selected. This field is required.
     */
    private AutoField[] inFields;
    /**
     * The name of the output bundle field. This field is required.
     */
    private AutoField out;

    @JsonCreator
    public BundleFilterRandomField(@JsonProperty(value = "inFields", required = true) AutoField[] inFields,
                                   @JsonProperty(value = "out", required = true) AutoField out) {
        this.inFields = inFields;
        this.out = out;
    }

    @Override
    public boolean filter(Bundle bundle) {
        List<AutoField> inFieldsShuffle = new ArrayList<>(Arrays.asList(inFields));
        Collections.shuffle(inFieldsShuffle);

        for (AutoField bf : inFieldsShuffle) {
            if (bf != null && bf.getValue(bundle) != null) {
                out.setValue(bundle, bf.getValue(bundle));
                break;
            }
        }

        return true;
    }
}


text:
namespace handy {

struct Daemon {
    //exit in parent
    static int daemonStart(const char* pidfile);
    //exit in parent
    static int daemonRestart(const char* pidfile);
    static int daemonStop(const char* pidfile);
    static int getPidFromFile(const char* pidfile);

    // cmd: start stop restart
    // exit(1) when error
    // exit(0) when start or restart in parent
    // return when start or restart in child
    static void daemonProcess(const char* cmd, const char* pidfile);
    //fork; wait for parent to exit; exec argv
    //you may use it to implement restart in program
    static void changeTo(const char* argv[]);
};

struct Signal {
    static void signal(int sig, const std::function<void()>& handler);
};
}