text:
namespace mesos {
namespace internal {
namespace scheduler {

class Flags : public virtual logging::Flags
{
public:
  Flags()
  {
    add(&Flags::authentication_backoff_factor,
        "authentication_backoff_factor",
        "Scheduler driver authentication retries are exponentially backed\n"
        "off based on 'b', the authentication backoff factor (e.g., 1st retry\n"
        "uses a random value between `[0, b * 2^1]`, 2nd retry between\n"
        "`[0, b * 2^2]`, 3rd retry between `[0, b * 2^3]`, etc up to a\n"
        "maximum of " + stringify(AUTHENTICATION_RETRY_INTERVAL_MAX),
        DEFAULT_AUTHENTICATION_BACKOFF_FACTOR);

    add(&Flags::registration_backoff_factor,
        "registration_backoff_factor",
        "Scheduler driver (re-)registration retries are exponentially backed\n"
        "off based on 'b', the registration backoff factor (e.g., 1st retry\n"
        "uses a random value between [0, b], 2nd retry between [0, b * 2^1],\n"
        "3rd retry between [0, b * 2^2]...) up to a maximum of (framework\n"
        "failover timeout/10, if failover timeout is specified) or " +
        stringify(REGISTRATION_RETRY_INTERVAL_MAX) + ", whichever is smaller",
        DEFAULT_REGISTRATION_BACKOFF_FACTOR);

    // This help message for --modules flag is the same for
    // {master,slave,sched,tests}/flags.[ch]pp and should always be kept in
    // in sync.
    // TODO(karya): Remove the JSON example and add reference to the
    // doc file explaining the --modules flag.
    add(&Flags::modules,
        "modules",
        "List of modules to be loaded and be available to the internal\n"
        "subsystems.\n"
        "\n"
        "Use --modules=filepath to specify the list of modules via a\n"
        "file containing a JSON formatted string. 'filepath' can be\n"
        "of the form 'file:///path/to/file' or '/path/to/file'.\n"
        "\n"
        "Use --modules=\"{...}\" to specify the list of modules inline.\n"
        "\n"
        "Example:\n"
        "{\n"
        "  \"libraries\": [\n"
        "    {\n"
        "      \"file\": \"/path/to/libfoo.so\",\n"
        "      \"modules\": [\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_bar\",\n"
        "          \"parameters\": [\n"
        "            {\n"
        "              \"key\": \"X\",\n"
        "              \"value\": \"Y\"\n"
        "            }\n"
        "          ]\n"
        "        },\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_baz\"\n"
        "        }\n"
        "      ]\n"
        "    },\n"
        "    {\n"
        "      \"name\": \"qux\",\n"
        "      \"modules\": [\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_norf\"\n"
        "        }\n"
        "      ]\n"
        "    }\n"
        "  ]\n"
        "}");

    // This help message for --modules_dir flag is the same for
    // {master,slave,sched,tests}/flags.[ch]pp and should always be kept in
    // sync.
    add(&Flags::modulesDir,
        "modules_dir",
        "Directory path of the module manifest files.\n"
        "The manifest files are processed in alphabetical order.\n"
        "(See --modules for more information on module manifest files)\n"
        "Cannot be used in conjunction with --modules.\n");

    add(&Flags::authenticatee,
        "authenticatee",
        "Authenticatee implementation to use when authenticating against the\n"
        "master. Use the default '" + std::string(DEFAULT_AUTHENTICATEE) + "'\n"
        "or load an alternate authenticatee module using MESOS_MODULES.",
        DEFAULT_AUTHENTICATEE);

    add(&Flags::authentication_timeout,
        "authentication_timeout",
        "Timeout after which authentication will be retried.",
        DEFAULT_AUTHENTICATION_TIMEOUT);
  }

  Duration authentication_backoff_factor;
  Duration registration_backoff_factor;
  Option<Modules> modules;
  Option<std::string> modulesDir;
  std::string authenticatee;
  Duration authentication_timeout;
};

} // namespace scheduler {
} // namespace internal {
} // namespace mesos {

#endif // __SCHED_FLAGS_HPP__

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Finding\Enums;

class SortOrderType
{
    const C_BEST_MATCH = 'BestMatch';
    const C_BID_COUNT_FEWEST = 'BidCountFewest';
    const C_BID_COUNT_MOST = 'BidCountMost';
    const C_COUNTRY_ASCENDING = 'CountryAscending';
    const C_COUNTRY_DESCENDING = 'CountryDescending';
    const C_CURRENT_PRICE_HIGHEST = 'CurrentPriceHighest';
    const C_DISTANCE_NEAREST = 'DistanceNearest';
    const C_END_TIME_SOONEST = 'EndTimeSoonest';
    const C_PRICE_PLUS_SHIPPING_HIGHEST = 'PricePlusShippingHighest';
    const C_PRICE_PLUS_SHIPPING_LOWEST = 'PricePlusShippingLowest';
    const C_START_TIME_NEWEST = 'StartTimeNewest';
    const C_WATCH_COUNT_DECREASE_SORT = 'WatchCountDecreaseSort';
}


text:
<?php

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\Bundle\AsseticBundle\Tests\Factory\Resource;

use Symfony\Bundle\AsseticBundle\Factory\Resource\FileResource;

class FileResourceTest extends \PHPUnit_Framework_TestCase
{
    private $loader;

    protected function setUp()
    {
        $this->loader = $this->getMock('Symfony\\Component\\Templating\\Loader\\LoaderInterface');
    }

    public function testCastAsString()
    {
        $baseDir = '/path/to/MyBundle/Resources/views/';
        $resource = new FileResource($this->loader, 'MyBundle', $baseDir, $baseDir.'Section/template.html.twig');
        $this->assertEquals('MyBundle:Section:template.html.twig', (string) $resource);
    }
}


text:
package org.cocos2d.box2d;

import org.box2d.common.BBVec2;
import org.box2d.dynamics.BBFixture;

public class ContactPoint {
    BBFixture fixtureA;
    BBFixture fixtureB;
    BBVec2 normal;
    BBVec2 position;
//    BBPointState state;
}


text:
package com.orientechnologies.orient.core.db.record.ridbag.sbtree;

import com.orientechnologies.DatabaseAbstractTest;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.intent.OIntentMassiveInsert;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Test
public class ORidBagAtomicUpdateTest extends DatabaseAbstractTest {
  private int topThreshold;
  private int bottomThreshold;

  private final class LevelKey {
    private final ORID rid;
    private final int  level;

    private LevelKey(ORID rid, int level) {
      this.rid = rid;
      this.level = level;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o)
        return true;
      if (o == null || getClass() != o.getClass())
        return false;

      LevelKey levelKey = (LevelKey) o;

      if (level != levelKey.level)
        return false;
      if (!rid.equals(levelKey.rid))
        return false;

      return true;
    }

    @Override
    public int hashCode() {
      int result = rid.hashCode();
      result = 31 * result + level;
      return result;
    }
  }

  @BeforeClass
  public void setUp() throws Exception {
    database.declareIntent(new OIntentMassiveInsert());
  }

  @BeforeMethod
  public void beforeMethod() {
    topThreshold = OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.getValueAsInteger();
    bottomThreshold = OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.getValueAsInteger();

    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(-1);
  }

  @AfterMethod
  public void afterMethod() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(topThreshold);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(bottomThreshold);
  }

  public void testAddTwoNewDocuments() {
    database.begin();
    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    rootDoc.save();
    database.commit();

    database.begin();

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.rollback();

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 0);
  }

  public void testAddTwoNewDocumentsWithCME() {
    final ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    database.begin();
    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    rootDoc.save();
    database.commit();

    database.getLocalCache().clear();
    ODocument staleCMEDoc = database.load(cmeDoc.getIdentity());
    Assert.assertNotSame(staleCMEDoc, cmeDoc);
    cmeDoc.field("v", "v");
    cmeDoc.save();

    database.begin();

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    staleCMEDoc.field("v", "v1");
    staleCMEDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 0);
  }

  public void testAddTwoAdditionalNewDocuments() {
    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.begin();

    ODocument docThree = new ODocument();
    ODocument docFour = new ODocument();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    database.rollback();

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 2);

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  public void testAddingDocsDontUpdateVersion() {
    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();

    ridBag.add(docOne);

    rootDoc.save();

    final int version = rootDoc.getVersion();

    ODocument docTwo = new ODocument();
    ridBag.add(docTwo);

    rootDoc.save();

    Assert.assertEquals(ridBag.size(), 2);
    Assert.assertEquals(rootDoc.getVersion(), version);

    rootDoc = (ODocument) rootDoc.reload();

    Assert.assertEquals(ridBag.size(), 2);
    Assert.assertEquals(rootDoc.getVersion(), version);
  }

  public void testAddingDocsDontUpdateVersionInTx() {
    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();

    ridBag.add(docOne);

    rootDoc.save();

    database.commit();

    final int version = rootDoc.getVersion();

    ODocument docTwo = new ODocument();
    ridBag.add(docTwo);

    rootDoc.save();
    database.commit();

    Assert.assertEquals(ridBag.size(), 2);
    Assert.assertEquals(rootDoc.getVersion(), version);

    rootDoc = (ODocument) rootDoc.reload();

    Assert.assertEquals(ridBag.size(), 2);
    Assert.assertEquals(rootDoc.getVersion(), version);
  }

  public void testAddTwoAdditionalNewDocumentsWithCME() {
    final ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.getLocalCache().clear();
    ODocument staleCMEDoc = database.load(cmeDoc.getIdentity());

    Assert.assertNotSame(staleCMEDoc, cmeDoc);
    cmeDoc.field("v", "v");
    cmeDoc.save();

    database.begin();

    ODocument docThree = new ODocument();
    ODocument docFour = new ODocument();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    staleCMEDoc.field("v", "v1");
    staleCMEDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 2);

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  public void testAddTwoSavedDocuments() {
    long recordsCount = database.countClusterElements(database.getDefaultClusterId());

    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    docOne.save();
    ODocument docTwo = new ODocument();
    docTwo.save();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.rollback();

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);
  }

  public void testAddTwoAdditionalSavedDocuments() {
    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.begin();

    ODocument docThree = new ODocument();
    docThree.save();
    ODocument docFour = new ODocument();
    docFour.save();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    database.rollback();

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 2);

    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  public void testAddTwoAdditionalSavedDocumentsWithCME() {
    final ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.getLocalCache().clear();
    ODocument staleCMEDoc = database.load(cmeDoc.getIdentity());

    Assert.assertNotSame(staleCMEDoc, cmeDoc);
    cmeDoc.field("v", "v");
    cmeDoc.save();

    database.begin();

    ODocument docThree = new ODocument();
    docThree.save();
    ODocument docFour = new ODocument();
    docFour.save();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    staleCMEDoc.field("v", "vn");
    staleCMEDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 2);

    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  public void testAddInternalDocumentsAndSubDocuments() {
    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    docOne.save();

    ODocument docTwo = new ODocument();
    docTwo.save();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());
    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.begin();

    ODocument docThree = new ODocument();
    docThree.save();

    ODocument docFour = new ODocument();
    docFour.save();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    ODocument docThreeOne = new ODocument();
    docThreeOne.save();

    ODocument docThreeTwo = new ODocument();
    docThreeTwo.save();

    ORidBag ridBagThree = new ORidBag();
    ridBagThree.add(docThreeOne);
    ridBagThree.add(docThreeTwo);
    docThree.field("ridBag", ridBagThree);

    docThree.save();

    ODocument docFourOne = new ODocument();
    docFourOne.save();

    ODocument docFourTwo = new ODocument();
    docFourTwo.save();

    ORidBag ridBagFour = new ORidBag();
    ridBagFour.add(docFourOne);
    ridBagFour.add(docFourTwo);

    docFour.field("ridBag", ridBagFour);

    docFour.save();

    database.rollback();

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);
    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  public void testAddInternalDocumentsAndSubDocumentsWithCME() {
    final ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    database.begin();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ODocument docOne = new ODocument();
    docOne.save();

    ODocument docTwo = new ODocument();
    docTwo.save();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    database.commit();

    long recordsCount = database.countClusterElements(database.getDefaultClusterId());
    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    database.getLocalCache().clear();
    ODocument staleCMEDoc = database.load(cmeDoc.getIdentity());
    Assert.assertNotSame(staleCMEDoc, cmeDoc);
    cmeDoc.field("v", "v");
    cmeDoc.save();

    database.begin();

    ODocument docThree = new ODocument();
    docThree.save();

    ODocument docFour = new ODocument();
    docFour.save();

    ridBag.add(docThree);
    ridBag.add(docFour);

    rootDoc.save();

    ODocument docThreeOne = new ODocument();
    docThreeOne.save();

    ODocument docThreeTwo = new ODocument();
    docThreeTwo.save();

    ORidBag ridBagThree = new ORidBag();
    ridBagThree.add(docThreeOne);
    ridBagThree.add(docThreeTwo);
    docThree.field("ridBag", ridBagThree);

    docThree.save();

    ODocument docFourOne = new ODocument();
    docFourOne.save();

    ODocument docFourTwo = new ODocument();
    docFourTwo.save();

    ORidBag ridBagFour = new ORidBag();
    ridBagFour.add(docFourOne);
    ridBagFour.add(docFourTwo);

    docFour.field("ridBag", ridBagFour);

    docFour.save();

    staleCMEDoc.field("v", "vn");
    staleCMEDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    Assert.assertEquals(database.countClusterElements(database.getDefaultClusterId()), recordsCount);
    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(Arrays.asList(docOne, docTwo));

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    Assert.assertTrue(addedDocs.remove(iterator.next()));
    Assert.assertTrue(addedDocs.remove(iterator.next()));
  }

  /**
   * This test is no longer useful
   */
  @Test(enabled = false)
  public void testAddTwoSavedDocumentsWithoutTx() {
    ODocument docOne = new ODocument();
    ODocument docTwo = new ODocument();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    rootDoc.save();

    ODocument staleRooDoc = database.load(rootDoc.getIdentity());
    ORidBag staleRidBag = staleRooDoc.field("ridBag");

    staleRidBag.add(docOne);
    staleRidBag.add(docTwo);

    rootDoc.setDirty();
    rootDoc.save();
    try {
      staleRooDoc.save();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 0);
  }

  /**
   * This test is no longer useful
   */
  @Test(enabled = false)
  public void testAddOneSavedDocumentsAndDeleteOneWithoutTx() {
    ODocument docOne = new ODocument();
    docOne.save();

    ODocument docTwo = new ODocument();
    docTwo.save();

    ODocument docThree = new ODocument();
    docThree.save();

    ODocument rootDoc = new ODocument();

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    ridBag.add(docOne);
    ridBag.add(docTwo);

    rootDoc.save();

    ODocument staleRooDoc = database.load(rootDoc.getIdentity());
    ORidBag staleRidBag = staleRooDoc.field("ridBag");

    Iterator<OIdentifiable> iterator = staleRidBag.iterator();
    iterator.next();
    iterator.remove();

    staleRidBag.add(docThree);

    rootDoc.setDirty();
    rootDoc.save();
    try {
      staleRooDoc.save();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    rootDoc = database.load(rootDoc.getIdentity());
    ridBag = rootDoc.field("ridBag");

    Assert.assertEquals(ridBag.size(), 2);

    iterator = ridBag.iterator();
    Assert.assertEquals(iterator.next(), docOne);
    Assert.assertEquals(iterator.next(), docTwo);

    Assert.assertTrue(!iterator.hasNext());
  }

  public void testRandomModificationsNotTx() {
    final long seed = System.currentTimeMillis();
    System.out.println("testRandomModificationsNotTx seed: " + seed);

    final Random rnd = new Random(seed);
    final int iterations = 20;
    for (int n = 0; n < iterations; n++) {
      final int amountOfAddedDocs = rnd.nextInt(10) + 10;
      final int amountOfAddedDocsAfterSave = rnd.nextInt(5) + 5;
      final int amountOfDeletedDocs = rnd.nextInt(5) + 5;

      List<OIdentifiable> addedDocuments = new ArrayList<OIdentifiable>();

      ODocument document = new ODocument();
      ORidBag ridBag = new ORidBag();
      document.field("ridBag", ridBag);

      for (int i = 0; i < amountOfAddedDocs; i++) {
        final ODocument docToAdd = new ODocument();
        docToAdd.save();
        addedDocuments.add(docToAdd.getIdentity());
        ridBag.add(docToAdd);
      }

      document.save();

      database.getLocalCache().clear();
      ODocument staleDocument = database.load(document.getIdentity());
      ORidBag staleRidBag = staleDocument.field("ridBag");

      Assert.assertNotSame(document, staleDocument);
      Assert.assertNotSame(ridBag, staleRidBag);

      int k = 0;
      Iterator<OIdentifiable> iterator = staleRidBag.iterator();
      while (k < amountOfDeletedDocs && iterator.hasNext()) {
        iterator.next();
        if (rnd.nextBoolean()) {
          iterator.remove();
          k++;
        }

        if (!iterator.hasNext())
          iterator = staleRidBag.iterator();
      }

      for (k = 0; k < amountOfAddedDocsAfterSave; k++) {
        ODocument docToAdd = new ODocument();
        docToAdd.save();

        staleRidBag.add(docToAdd);
        addedDocuments.add(docToAdd);
      }

      Assert.assertEquals(staleRidBag.size(), addedDocuments.size() - amountOfDeletedDocs);

      document.setDirty();
      document.save();
      staleDocument.save();

      document = database.load(document.getIdentity());
      ridBag = document.field("ridBag");

      Assert.assertEquals(ridBag.size(), addedDocuments.size() - amountOfDeletedDocs);
      iterator = ridBag.iterator();
      while (iterator.hasNext())
        Assert.assertTrue(addedDocuments.contains(iterator.next()));
    }
  }

  public void testVisibility() {
    ODocument document = new ODocument();
    ORidBag ridBag = new ORidBag();

    document.field("ridBag", ridBag);
    ODocument docOne = new ODocument();
    docOne.save();

    ODocument docTwo = new ODocument();
    docTwo.save();

    ridBag.add(docOne);
    ridBag.add(docTwo);

    document.save();

    ODocument copyOne = database.load(document.getIdentity());

    database.getLocalCache().clear();
    ODocument copyTwo = database.load(document.getIdentity());

    Assert.assertNotSame(copyOne, copyTwo);

    ORidBag ridBagOne = copyOne.field("ridBag");
    ORidBag ridBagTwo = copyTwo.field("ridBag");

    ODocument docTree = new ODocument();
    docTree.save();

    ODocument docFour = new ODocument();
    docFour.save();

    ridBagOne.remove(docOne);

    ridBagOne.add(docTree);
    ridBagTwo.add(docFour);

    Assert.assertEquals(ridBagOne.size(), 2);
    Assert.assertEquals(ridBagTwo.size(), 3);
  }

  public void testRandomChangedInTxLevel2() {
    testRandomChangedInTx(2);
  }

  public void testRandomChangedInTxLevel1() {
    testRandomChangedInTx(1);
  }

  private void testRandomChangedInTx(final int levels) {
    Random rnd = new Random();

    final List<Integer> amountOfAddedDocsPerLevel = new ArrayList<Integer>();
    final List<Integer> amountOfAddedDocsAfterSavePerLevel = new ArrayList<Integer>();
    final List<Integer> amountOfDeletedDocsPerLevel = new ArrayList<Integer>();
    Map<LevelKey, List<OIdentifiable>> addedDocPerLevel = new HashMap<LevelKey, List<OIdentifiable>>();

    for (int i = 0; i < levels; i++) {
      amountOfAddedDocsPerLevel.add(rnd.nextInt(5) + 10);
      amountOfAddedDocsAfterSavePerLevel.add(rnd.nextInt(5) + 5);
      amountOfDeletedDocsPerLevel.add(rnd.nextInt(5) + 5);
    }

    database.begin();
    ODocument rootDoc = new ODocument();
    createDocsForLevel(amountOfAddedDocsPerLevel, 0, levels, addedDocPerLevel, rootDoc);
    database.commit();

    addedDocPerLevel = new HashMap<LevelKey, List<OIdentifiable>>(addedDocPerLevel);

    rootDoc = database.load(rootDoc.getIdentity());
    database.begin();
    deleteDocsForLevel(amountOfDeletedDocsPerLevel, 0, levels, rootDoc, rnd);
    addDocsForLevel(amountOfAddedDocsAfterSavePerLevel, 0, levels, rootDoc);
    database.rollback();

    rootDoc = database.load(rootDoc.getIdentity());
    assertDocsAfterRollback(0, levels, addedDocPerLevel, rootDoc);
  }

  public void testRandomChangedInTxWithCME() {
    final ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    Random rnd = new Random();

    final int levels = rnd.nextInt(2) + 1;
    final List<Integer> amountOfAddedDocsPerLevel = new ArrayList<Integer>();
    final List<Integer> amountOfAddedDocsAfterSavePerLevel = new ArrayList<Integer>();
    final List<Integer> amountOfDeletedDocsPerLevel = new ArrayList<Integer>();
    Map<LevelKey, List<OIdentifiable>> addedDocPerLevel = new HashMap<LevelKey, List<OIdentifiable>>();

    for (int i = 0; i < levels; i++) {
      amountOfAddedDocsPerLevel.add(rnd.nextInt(5) + 10);
      amountOfAddedDocsAfterSavePerLevel.add(rnd.nextInt(5) + 5);
      amountOfDeletedDocsPerLevel.add(rnd.nextInt(5) + 5);
    }

    database.getLocalCache().clear();
    ODocument staleCMEDoc = database.load(cmeDoc.getIdentity());
    Assert.assertNotSame(staleCMEDoc, cmeDoc);
    cmeDoc.field("v", "v");
    cmeDoc.save();

    database.begin();
    ODocument rootDoc = new ODocument();
    createDocsForLevel(amountOfAddedDocsPerLevel, 0, levels, addedDocPerLevel, rootDoc);
    database.commit();

    addedDocPerLevel = new HashMap<LevelKey, List<OIdentifiable>>(addedDocPerLevel);

    rootDoc = database.load(rootDoc.getIdentity());
    database.begin();
    deleteDocsForLevel(amountOfDeletedDocsPerLevel, 0, levels, rootDoc, rnd);
    addDocsForLevel(amountOfAddedDocsAfterSavePerLevel, 0, levels, rootDoc);

    staleCMEDoc.field("v", "vn");
    staleCMEDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    rootDoc = database.load(rootDoc.getIdentity());
    assertDocsAfterRollback(0, levels, addedDocPerLevel, rootDoc);
  }

  public void testFromEmbeddedToSBTreeRollback() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(5);

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    database.begin();

    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    database.commit();

    Assert.assertEquals(docsToAdd.size(), 3);
    Assert.assertTrue(ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    database.begin();
    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
    }

    Assert.assertTrue(document.isDirty());

    document.save();
    database.rollback();

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(ridBag.isEmbedded());
    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  public void testFromEmbeddedToSBTreeTXWithCME() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(5);

    ODocument cmeDocument = new ODocument();
    cmeDocument.field("v", "v1");
    cmeDocument.save();

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    database.begin();

    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    database.commit();

    Assert.assertEquals(docsToAdd.size(), 3);
    Assert.assertTrue(ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    database.getLocalCache().clear();
    ODocument staleDocument = database.load(cmeDocument.getIdentity());
    Assert.assertNotSame(staleDocument, cmeDocument);

    cmeDocument.field("v", "v234");
    cmeDocument.save();

    database.begin();
    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
    }

    Assert.assertTrue(document.isDirty());

    document.save();
    staleDocument.field("v", "ver");
    staleDocument.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(ridBag.isEmbedded());
    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  public void testFromEmbeddedToSBTreeWithCME() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(5);

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    Assert.assertEquals(docsToAdd.size(), 3);
    Assert.assertTrue(ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    database.getLocalCache().clear();
    ODocument cmeDocument = database.load(document.getIdentity());
    Assert.assertNotSame(cmeDocument, document);
    cmeDocument.field("v", "v1");
    cmeDocument.save();

    for (int i = 0; i < 3; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
    }

    Assert.assertTrue(document.isDirty());

    try {
      document.save();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(ridBag.isEmbedded());
    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  public void testFromSBTreeToEmbeddedRollback() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(7);

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    database.begin();

    for (int i = 0; i < 10; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    database.commit();

    Assert.assertEquals(docsToAdd.size(), 10);
    Assert.assertTrue(!ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    database.begin();
    for (int i = 0; i < 4; i++) {
      OIdentifiable docToRemove = docsToAdd.get(i);
      ridBag.remove(docToRemove);
    }

    Assert.assertTrue(document.isDirty());

    document.save();
    database.rollback();

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(!ridBag.isEmbedded());

    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  public void testFromSBTreeToEmbeddedTxWithCME() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(7);

    ODocument cmeDoc = new ODocument();
    cmeDoc.save();

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    database.begin();

    for (int i = 0; i < 10; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    database.commit();

    Assert.assertEquals(docsToAdd.size(), 10);
    Assert.assertTrue(!ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    database.getLocalCache().clear();
    ODocument staleDoc = database.load(cmeDoc.getIdentity());
    Assert.assertNotSame(staleDoc, cmeDoc);

    cmeDoc.field("v", "sd");
    cmeDoc.save();

    database.begin();
    for (int i = 0; i < 4; i++) {
      OIdentifiable docToRemove = docsToAdd.get(i);
      ridBag.remove(docToRemove);
    }

    Assert.assertTrue(document.isDirty());

    document.save();

    staleDoc.field("v", "d");
    staleDoc.save();

    try {
      database.commit();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(!ridBag.isEmbedded());

    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  /**
   * This test is no longer useful
   */
  @Test(enabled = false)
  public void testFromSBTreeToEmbeddedWithCME() {
    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(5);
    OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(7);

    List<OIdentifiable> docsToAdd = new ArrayList<OIdentifiable>();

    ODocument document = new ODocument();

    ORidBag ridBag = new ORidBag();
    document.field("ridBag", ridBag);
    document.save();

    for (int i = 0; i < 10; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();
      ridBag.add(docToAdd);
      docsToAdd.add(docToAdd);
    }

    document.save();

    Assert.assertEquals(docsToAdd.size(), 10);
    Assert.assertTrue(!ridBag.isEmbedded());

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    ODocument cmeDoc = database.load(document.getIdentity());
    cmeDoc.field("v", "v1");
    cmeDoc.save();

    for (int i = 0; i < 4; i++) {
      OIdentifiable docToRemove = docsToAdd.get(i);
      ridBag.remove(docToRemove);
    }

    Assert.assertTrue(document.isDirty());

    try {
      document.save();
      Assert.fail();
    } catch (OConcurrentModificationException e) {
    }

    document = database.load(document.getIdentity());
    ridBag = document.field("ridBag");

    Assert.assertTrue(!ridBag.isEmbedded());

    for (OIdentifiable identifiable : ridBag)
      Assert.assertTrue(docsToAdd.remove(identifiable));

    Assert.assertTrue(docsToAdd.isEmpty());
  }

  private void createDocsForLevel(final List<Integer> amountOfAddedDocsPerLevel, int level, int levels,
      Map<LevelKey, List<OIdentifiable>> addedDocPerLevel, ODocument rootDoc) {

    int docs = amountOfAddedDocsPerLevel.get(level);

    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>();
    addedDocPerLevel.put(new LevelKey(rootDoc.getIdentity(), level), addedDocs);

    ORidBag ridBag = new ORidBag();
    rootDoc.field("ridBag", ridBag);

    for (int i = 0; i < docs; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();

      addedDocs.add(docToAdd.getIdentity());
      ridBag.add(docToAdd);

      if (level + 1 < levels)
        createDocsForLevel(amountOfAddedDocsPerLevel, level + 1, levels, addedDocPerLevel, docToAdd);
    }

    rootDoc.save();
  }

  private void deleteDocsForLevel(List<Integer> amountOfDeletedDocsPerLevel, int level, int levels, ODocument rootDoc, Random rnd) {
    ORidBag ridBag = rootDoc.field("ridBag");
    Iterator<OIdentifiable> iter = ridBag.iterator();
    while (iter.hasNext()) {
      OIdentifiable identifiable = iter.next();
      ODocument doc = identifiable.getRecord();
      if (level + 1 < levels)
        deleteDocsForLevel(amountOfDeletedDocsPerLevel, level + 1, levels, doc, rnd);
    }

    int docs = amountOfDeletedDocsPerLevel.get(level);

    int k = 0;
    Iterator<OIdentifiable> iterator = ridBag.iterator();
    while (k < docs && iterator.hasNext()) {
      iterator.next();

      if (rnd.nextBoolean()) {
        iterator.remove();
        k++;
      }

      if (!iterator.hasNext())
        iterator = ridBag.iterator();
    }
    rootDoc.save();

  }

  private void addDocsForLevel(List<Integer> amountOfAddedDocsAfterSavePerLevel, int level, int levels, ODocument rootDoc) {
    ORidBag ridBag = rootDoc.field("ridBag");

    for (OIdentifiable identifiable : ridBag) {
      ODocument doc = identifiable.getRecord();
      if (level + 1 < levels)
        addDocsForLevel(amountOfAddedDocsAfterSavePerLevel, level + 1, levels, doc);
    }

    int docs = amountOfAddedDocsAfterSavePerLevel.get(level);
    for (int i = 0; i < docs; i++) {
      ODocument docToAdd = new ODocument();
      docToAdd.save();

      ridBag.add(docToAdd);
    }
    rootDoc.save();

  }

  private void assertDocsAfterRollback(int level, int levels, Map<LevelKey, List<OIdentifiable>> addedDocPerLevel, ODocument rootDoc) {
    ORidBag ridBag = rootDoc.field("ridBag");
    List<OIdentifiable> addedDocs = new ArrayList<OIdentifiable>(addedDocPerLevel.get(new LevelKey(rootDoc.getIdentity(), level)));

    Iterator<OIdentifiable> iterator = ridBag.iterator();
    while (iterator.hasNext()) {
      ODocument doc = iterator.next().getRecord();
      if (level + 1 < levels)
        assertDocsAfterRollback(level + 1, levels, addedDocPerLevel, doc);
      else
        Assert.assertNull(doc.field("ridBag"));

      Assert.assertTrue(addedDocs.remove(doc));
    }

    Assert.assertTrue(addedDocs.isEmpty());
  }
}


text:
/* eslint-env mocha */
var DropboxBase = require('../src/dropbox-base');
var REQUEST_CONSTANTS = require('../src/request-constants');
var rpcRequest = require('../src/rpc-request');
var chai = require('chai');
var sinon = require('sinon');

var assert = chai.assert;

describe('DropboxBase', function () {
  var dbx;
  describe('.accessToken', function () {
    it('can be set in the constructor', function () {
      dbx = new DropboxBase({ accessToken: 'foo' });
      assert.equal(dbx.getAccessToken(), 'foo');
    });

    it('is undefined if not set in constructor', function () {
      dbx = new DropboxBase();
      assert.equal(dbx.getAccessToken(), undefined);
    });

    it('can be set after being instantiated', function () {
      dbx = new DropboxBase();
      dbx.setAccessToken('foo');
      assert.equal(dbx.getAccessToken(), 'foo');
    });
  });

  describe('.clientId', function () {
    it('can be set in the constructor', function () {
      dbx = new DropboxBase({ clientId: 'foo' });
      assert.equal(dbx.getClientId(), 'foo');
    });

    it('is undefined if not set in constructor', function () {
      dbx = new DropboxBase();
      assert.equal(dbx.getClientId(), undefined);
    });

    it('can be set after being instantiated', function () {
      dbx = new DropboxBase();
      dbx.setClientId('foo');
      assert.equal(dbx.getClientId(), 'foo');
    });
  });

  describe('.selectUser', function () {
    it('can be set in the constructor', function () {
      dbx = new DropboxBase({ selectUser: 'foo' });
      assert.equal(dbx.selectUser, 'foo');
    });

    it('is undefined if not set in constructor', function () {
      dbx = new DropboxBase();
      assert.equal(dbx.selectUser, undefined);
    });
  });

  describe('#rpcRequest()', function () {
    it('defaults to the libraries implementation', function () {
      dbx = new DropboxBase();
      assert.equal(dbx.getRpcRequest(), rpcRequest);
    });

    it('can be set to something else by the user', function () {
      var aFunction = function () {};
      dbx = new DropboxBase();
      dbx.setRpcRequest(aFunction);
      assert.equal(dbx.getRpcRequest(), aFunction);
    });
  });

  describe('#getAuthenticationUrl()', function () {
    it('throws an error if the client id isn\'t set', function () {
      dbx = new DropboxBase();
      assert.throws(
        DropboxBase.prototype.getAuthenticationUrl.bind(dbx, 'https://redirecturl.com'),
        Error,
        'A client id is required. You can set the client id using .setClientId().'
      );
    });

    it('throws an error if the redirect url isn\'t set', function () {
      dbx = new DropboxBase({ clientId: 'CLIENT_ID' });
      assert.throws(
        DropboxBase.prototype.getAuthenticationUrl.bind(dbx),
        Error,
        'A redirect uri is required.'
      );
    });

    it('returns auth url with redirect uri', function () {
      dbx = new DropboxBase({ clientId: 'CLIENT_ID' });
      assert.equal(
        dbx.getAuthenticationUrl('redirect'),
        'https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=redirect'
      );
    });

    it('returns auth url with redirect uri and state', function () {
      dbx = new DropboxBase({ clientId: 'CLIENT_ID' });
      assert.equal(
        dbx.getAuthenticationUrl('redirect', 'state'),
        'https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=redirect&state=state'
      );
    });
  });

  describe('.request()', function () {
    it('calls the correct request method', function () {
      var rpcSpy;
      dbx = new DropboxBase();
      rpcSpy = sinon.spy(dbx.getRpcRequest());
      dbx.setRpcRequest(rpcSpy);
      dbx.request('path', {}, 'user', 'api', REQUEST_CONSTANTS.RPC);
      assert(rpcSpy.calledOnce);
      assert.equal('path', dbx.rpcRequest.getCall(0).args[0]);
      assert.deepEqual({}, dbx.rpcRequest.getCall(0).args[1]);
    });
    it('throws an error for invalid request styles', function () {
      dbx = new DropboxBase();
      assert.throws(
        DropboxBase.prototype.request.bind(DropboxBase, '', {}, 'user', 'api', 'BADTYPE'),
        Error,
        'Invalid request style'
      );
    });
  });
});


text:
package org.apache.camel.builder.component.dsl;

import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.google.drive.GoogleDriveComponent;

/**
 * Manage files in Google Drive.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface GoogleDriveComponentBuilderFactory {

    /**
     * Google Drive (camel-google-drive)
     * Manage files in Google Drive.
     *
     * Category: file,cloud,api
     * Since: 2.14
     * Maven coordinates: org.apache.camel:camel-google-drive
     */
    static GoogleDriveComponentBuilder googleDrive() {
        return new GoogleDriveComponentBuilderImpl();
    }

    /**
     * Builder for the Google Drive component.
     */
    interface GoogleDriveComponentBuilder
            extends
                ComponentBuilder<GoogleDriveComponent> {
        /**
         * Google drive application name. Example would be
         * camel-google-drive/1.0.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default GoogleDriveComponentBuilder applicationName(
                java.lang.String applicationName) {
            doSetProperty("applicationName", applicationName);
            return this;
        }
        /**
         * Client ID of the drive application.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default GoogleDriveComponentBuilder clientId(java.lang.String clientId) {
            doSetProperty("clientId", clientId);
            return this;
        }
        /**
         * To use the shared configuration.
         *
         * The option is a:
         * org.apache.camel.component.google.drive.GoogleDriveConfiguration type.
         *
         * Group: common
         */
        default GoogleDriveComponentBuilder configuration(
                org.apache.camel.component.google.drive.GoogleDriveConfiguration configuration) {
            doSetProperty("configuration", configuration);
            return this;
        }
        /**
         * Specifies the level of permissions you want a drive application to
         * have to a user account. See
         * https://developers.google.com/drive/web/scopes for more info.
         *
         * The option is a: java.util.List<java.lang.String> type.
         *
         * Group: common
         */
        default GoogleDriveComponentBuilder scopes(
                java.util.List<java.lang.String> scopes) {
            doSetProperty("scopes", scopes);
            return this;
        }
        /**
         * Allows for bridging the consumer to the Camel routing Error Handler,
         * which mean any exceptions occurred while the consumer is trying to
         * pickup incoming messages, or the likes, will now be processed as a
         * message and handled by the routing Error Handler. By default the
         * consumer will use the org.apache.camel.spi.ExceptionHandler to deal
         * with exceptions, that will be logged at WARN or ERROR level and
         * ignored.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: consumer
         */
        default GoogleDriveComponentBuilder bridgeErrorHandler(
                boolean bridgeErrorHandler) {
            doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: producer
         */
        default GoogleDriveComponentBuilder lazyStartProducer(
                boolean lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * Whether the component should use basic property binding (Camel 2.x)
         * or the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default GoogleDriveComponentBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * To use the GoogleCalendarClientFactory as factory for creating the
         * client. Will by default use BatchGoogleDriveClientFactory.
         *
         * The option is a:
         * org.apache.camel.component.google.drive.GoogleDriveClientFactory type.
         *
         * Group: advanced
         */
        default GoogleDriveComponentBuilder clientFactory(
                org.apache.camel.component.google.drive.GoogleDriveClientFactory clientFactory) {
            doSetProperty("clientFactory", clientFactory);
            return this;
        }
        /**
         * OAuth 2 access token. This typically expires after an hour so
         * refreshToken is recommended for long term usage.
         *
         * The option is a: java.lang.String type.
         *
         * Group: security
         */
        default GoogleDriveComponentBuilder accessToken(
                java.lang.String accessToken) {
            doSetProperty("accessToken", accessToken);
            return this;
        }
        /**
         * Client secret of the drive application.
         *
         * The option is a: java.lang.String type.
         *
         * Group: security
         */
        default GoogleDriveComponentBuilder clientSecret(
                java.lang.String clientSecret) {
            doSetProperty("clientSecret", clientSecret);
            return this;
        }
        /**
         * OAuth 2 refresh token. Using this, the Google Calendar component can
         * obtain a new accessToken whenever the current one expires - a
         * necessity if the application is long-lived.
         *
         * The option is a: java.lang.String type.
         *
         * Group: security
         */
        default GoogleDriveComponentBuilder refreshToken(
                java.lang.String refreshToken) {
            doSetProperty("refreshToken", refreshToken);
            return this;
        }
    }

    class GoogleDriveComponentBuilderImpl
            extends
                AbstractComponentBuilder<GoogleDriveComponent>
            implements
                GoogleDriveComponentBuilder {
        @Override
        protected GoogleDriveComponent buildConcreteComponent() {
            return new GoogleDriveComponent();
        }
        private org.apache.camel.component.google.drive.GoogleDriveConfiguration getOrCreateConfiguration(
                org.apache.camel.component.google.drive.GoogleDriveComponent component) {
            if (component.getConfiguration() == null) {
                component.setConfiguration(new org.apache.camel.component.google.drive.GoogleDriveConfiguration());
            }
            return component.getConfiguration();
        }
        @Override
        protected boolean setPropertyOnComponent(
                Component component,
                String name,
                Object value) {
            switch (name) {
            case "applicationName": getOrCreateConfiguration((GoogleDriveComponent) component).setApplicationName((java.lang.String) value); return true;
            case "clientId": getOrCreateConfiguration((GoogleDriveComponent) component).setClientId((java.lang.String) value); return true;
            case "configuration": ((GoogleDriveComponent) component).setConfiguration((org.apache.camel.component.google.drive.GoogleDriveConfiguration) value); return true;
            case "scopes": getOrCreateConfiguration((GoogleDriveComponent) component).setScopes((java.util.List) value); return true;
            case "bridgeErrorHandler": ((GoogleDriveComponent) component).setBridgeErrorHandler((boolean) value); return true;
            case "lazyStartProducer": ((GoogleDriveComponent) component).setLazyStartProducer((boolean) value); return true;
            case "basicPropertyBinding": ((GoogleDriveComponent) component).setBasicPropertyBinding((boolean) value); return true;
            case "clientFactory": ((GoogleDriveComponent) component).setClientFactory((org.apache.camel.component.google.drive.GoogleDriveClientFactory) value); return true;
            case "accessToken": getOrCreateConfiguration((GoogleDriveComponent) component).setAccessToken((java.lang.String) value); return true;
            case "clientSecret": getOrCreateConfiguration((GoogleDriveComponent) component).setClientSecret((java.lang.String) value); return true;
            case "refreshToken": getOrCreateConfiguration((GoogleDriveComponent) component).setRefreshToken((java.lang.String) value); return true;
            default: return false;
            }
        }
    }
}


text:
@implementation HistoryForHobbyStore

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveSupport::Deprecation::Behavior</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            Module
            ActiveSupport::Deprecation::Behavior

/Users/Bonobo/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/deprecation/behaviors.rb

Methods

B

                behavior,

                behavior=

Attributes

              [RW]

            debug

Whether to print a backtrace along with the warning.

Instance Public methods

              behavior()

            Link

Returns the current behavior or if one isn't set, defaults to
:stderr.

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/deprecation/behaviors.rb, line 46
def behavior
  @behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
end

              behavior=(behavior)

            Link

Sets the behavior to the specified value. Can be a single value, array, or
an object that responds to call.

Available behaviors:

raise

Raise ActiveSupport::DeprecationException.

stderr

Log all deprecation warnings to +$stderr+.

log

Log all deprecation warnings to Rails.logger.

notify

Use ActiveSupport::Notifications to notify
deprecation.rails.

silence

Do nothing.

Setting behaviors only affects deprecations that happen after boot time. Deprecation warnings raised by gems are not
affected by this setting because they happen before Rails boots up.

ActiveSupport::Deprecation.behavior = :stderr
ActiveSupport::Deprecation.behavior = [:stderr, :log]
ActiveSupport::Deprecation.behavior = MyCustomHandler
ActiveSupport::Deprecation.behavior = ->(message, callstack) {
  # custom stuff
}

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/deprecation/behaviors.rb, line 71
def behavior=(behavior)
  @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
end


text:
layout: default
title: CAS - RADIUS Authentication
---

# RADIUS Authentication
RADIUS support is enabled by only including the following dependency in the WAR overlay:

```xml
<dependency>
  <groupId>org.apereo.cas</groupId>
  <artifactId>cas-server-support-radius</artifactId>
  <version>${cas.version}</version>
</dependency>
```

RSA RADIUS support for MFA is enabled by only including the following dependency in the WAR overlay:

```xml
<dependency>
  <groupId>org.apereo.cas</groupId>
  <artifactId>cas-server-support-radius-mfa</artifactId>
  <version>${cas.version}</version>
</dependency>
```

## Configuration

To see the relevant list of CAS properties, please [review this guide](Configuration-Properties.html).


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type HomeFeaturedEventsRail_orderedSet = {
    readonly items: ReadonlyArray<({
        readonly __typename: "FeaturedLink";
        readonly internalID: string | null;
        readonly title: string | null;
        readonly subtitle: string | null;
        readonly href: string | null;
        readonly image: {
            readonly cropped: {
                readonly src: string;
                readonly srcSet: string;
            } | null;
        } | null;
    } | {
        /*This will never be '%other', but we need some
        value in case none of the concrete values match.*/
        readonly __typename: "%other";
    }) | null> | null;
    readonly " $refType": "HomeFeaturedEventsRail_orderedSet";
};
export type HomeFeaturedEventsRail_orderedSet$data = HomeFeaturedEventsRail_orderedSet;
export type HomeFeaturedEventsRail_orderedSet$key = {
    readonly " $data"?: HomeFeaturedEventsRail_orderedSet$data;
    readonly " $fragmentRefs": FragmentRefs<"HomeFeaturedEventsRail_orderedSet">;
};

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "HomeFeaturedEventsRail_orderedSet",
  "selections": [
    {
      "alias": null,
      "args": null,
      "concreteType": null,
      "kind": "LinkedField",
      "name": "items",
      "plural": true,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "__typename",
          "storageKey": null
        },
        {
          "kind": "InlineFragment",
          "selections": [
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "internalID",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "title",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "subtitle",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "href",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "concreteType": "Image",
              "kind": "LinkedField",
              "name": "image",
              "plural": false,
              "selections": [
                {
                  "alias": null,
                  "args": [
                    {
                      "kind": "Literal",
                      "name": "height",
                      "value": 244
                    },
                    {
                      "kind": "Literal",
                      "name": "width",
                      "value": 325
                    }
                  ],
                  "concreteType": "CroppedImageUrl",
                  "kind": "LinkedField",
                  "name": "cropped",
                  "plural": false,
                  "selections": [
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "src",
                      "storageKey": null
                    },
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "srcSet",
                      "storageKey": null
                    }
                  ],
                  "storageKey": "cropped(height:244,width:325)"
                }
              ],
              "storageKey": null
            }
          ],
          "type": "FeaturedLink"
        }
      ],
      "storageKey": null
    }
  ],
  "type": "OrderedSet"
};
(node as any).hash = '72af24e3bc363d4cf36191111500564e';
export default node;


text:
package cn.springmvc.interceptor;

public class SomeInterceptor {

}


text:
using Lumpn.Mooga;

namespace Lumpn.ZeldaMooga
{
    public sealed class ZeldaGenomeFactory : GenomeFactory
    {
        private readonly ZeldaConfiguration configuration;

        public ZeldaGenomeFactory(ZeldaConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public Genome CreateGenome()
        {
            return new ZeldaGenome(configuration);
        }
    }
}


text:
require 'test_helper'

class GarbageZoneTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
package com.evolveum.midpoint.schema.processor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;

/**
 * @author semancik
 *
 */
public class ResourceObjectIdentification implements Serializable {
	private static final long serialVersionUID = 1L;

	private ObjectClassComplexTypeDefinition objectClassDefinition;
	private Collection<? extends ResourceAttribute<?>> primaryIdentifiers;
	private Collection<? extends ResourceAttribute<?>> secondaryIdentifiers;
	// TODO: identification strategy

	public ResourceObjectIdentification(ObjectClassComplexTypeDefinition objectClassDefinition,
			Collection<? extends ResourceAttribute<?>> primaryIdentifiers,
			Collection<? extends ResourceAttribute<?>> secondaryIdentifiers) {
		this.objectClassDefinition = objectClassDefinition;
		this.primaryIdentifiers = primaryIdentifiers;
		this.secondaryIdentifiers = secondaryIdentifiers;
	}

	public Collection<? extends ResourceAttribute<?>> getPrimaryIdentifiers() {
		return primaryIdentifiers;
	}

	public <T> ResourceAttribute<T> getPrimaryIdentifier() throws SchemaException {
		if (primaryIdentifiers == null || primaryIdentifiers.isEmpty()) {
			return null;
		}
		if (primaryIdentifiers.size() > 1) {
			throw new SchemaException("More than one primary identifier in "+this);
		}
		return (ResourceAttribute<T>) primaryIdentifiers.iterator().next();
	}

	public Collection<? extends ResourceAttribute<?>> getSecondaryIdentifiers() {
		return secondaryIdentifiers;
	}

	public <T> ResourceAttribute<T> getSecondaryIdentifier() throws SchemaException {
		if (secondaryIdentifiers == null || secondaryIdentifiers.isEmpty()) {
			return null;
		}
		if (secondaryIdentifiers.size() > 1) {
			throw new SchemaException("More than one secondary identifier in "+this);
		}
		return (ResourceAttribute<T>) secondaryIdentifiers.iterator().next();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Collection<? extends ResourceAttribute<?>> getAllIdentifiers() {
		if (primaryIdentifiers == null) {
			return secondaryIdentifiers;
		}
		if (secondaryIdentifiers == null) {
			return primaryIdentifiers;
		}
		List allIdentifiers = new ArrayList<>(primaryIdentifiers.size() + secondaryIdentifiers.size());
		allIdentifiers.addAll(primaryIdentifiers);
		allIdentifiers.addAll(secondaryIdentifiers);
		return allIdentifiers;
	}

	public ObjectClassComplexTypeDefinition getObjectClassDefinition() {
		return objectClassDefinition;
	}

	public static ResourceObjectIdentification create(ObjectClassComplexTypeDefinition objectClassDefinition,
			Collection<? extends ResourceAttribute<?>> allIdentifiers) throws SchemaException {
		if (allIdentifiers == null) {
			throw new IllegalArgumentException("Cannot create ResourceObjectIdentification with null identifiers");
		}
		Collection<? extends ResourceAttribute<?>> primaryIdentifiers =  null;
		Collection<? extends ResourceAttribute<?>> secondaryIdentifiers = null;
		for (ResourceAttribute<?> identifier: allIdentifiers) {
			if (objectClassDefinition.isPrimaryIdentifier(identifier.getElementName())) {
				if (primaryIdentifiers == null) {
					primaryIdentifiers = new ArrayList<>();
				}
				((Collection)primaryIdentifiers).add(identifier);
			} else if (objectClassDefinition.isSecondaryIdentifier(identifier.getElementName())) {
				if (secondaryIdentifiers == null) {
					secondaryIdentifiers = new ArrayList<>();
				}
				((Collection)secondaryIdentifiers).add(identifier);
			} else {
				throw new SchemaException("Attribute "+identifier+" is neither primary not secondary identifier in object class "+objectClassDefinition);
			}
		}
		return new ResourceObjectIdentification(objectClassDefinition, primaryIdentifiers, secondaryIdentifiers);
	}

	public static ResourceObjectIdentification createFromAttributes(ObjectClassComplexTypeDefinition objectClassDefinition,
			Collection<? extends ResourceAttribute<?>> attributes) throws SchemaException {
		Collection<? extends ResourceAttribute<?>> primaryIdentifiers =  null;
		Collection<? extends ResourceAttribute<?>> secondaryIdentifiers = null;
		for (ResourceAttribute<?> identifier: attributes) {
			if (objectClassDefinition.isPrimaryIdentifier(identifier.getElementName())) {
				if (primaryIdentifiers == null) {
					primaryIdentifiers = new ArrayList<>();
				}
				((Collection)primaryIdentifiers).add(identifier);
			} else if (objectClassDefinition.isSecondaryIdentifier(identifier.getElementName())) {
				if (secondaryIdentifiers == null) {
					secondaryIdentifiers = new ArrayList<>();
				}
				((Collection)secondaryIdentifiers).add(identifier);
			}
		}
		return new ResourceObjectIdentification(objectClassDefinition, primaryIdentifiers, secondaryIdentifiers);
	}

	public static ResourceObjectIdentification createFromShadow(ObjectClassComplexTypeDefinition objectClassDefinition,
			ShadowType shadowType) throws SchemaException {
		return createFromAttributes(objectClassDefinition, ShadowUtil.getAttributes(shadowType));
	}

	public void validatePrimaryIdenfiers() {
		if (!hasPrimaryIdentifiers()) {
			throw new IllegalStateException("No primary identifiers in " + this);
		}
	}

	public boolean hasPrimaryIdentifiers() {
		return primaryIdentifiers != null && !primaryIdentifiers.isEmpty();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((primaryIdentifiers == null) ? 0 : primaryIdentifiers.hashCode());
		result = prime * result + ((objectClassDefinition == null) ? 0 : objectClassDefinition.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ResourceObjectIdentification other = (ResourceObjectIdentification) obj;
		if (primaryIdentifiers == null) {
			if (other.primaryIdentifiers != null)
				return false;
		} else if (!primaryIdentifiers.equals(other.primaryIdentifiers))
			return false;
		if (objectClassDefinition == null) {
			if (other.objectClassDefinition != null)
				return false;
		} else if (!objectClassDefinition.equals(other.objectClassDefinition))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "ResourceObjectIdentification(" + PrettyPrinter.prettyPrint(objectClassDefinition.getTypeName())
				+ ": primary=" + primaryIdentifiers + ", secondary=" + secondaryIdentifiers + ")";
	}

}


text:
![Hoa](http://static.hoa-project.net/Image/Hoa_small.png)

Hoa is a **modular**, **extensible** and **structured** set of PHP libraries.
Moreover, Hoa aims at being a bridge between industrial and research worlds.

# Hoa\Json ![state](http://central.hoa-project.net/State/Json)

This library provides only the grammar of JSON in the PP format (see the
[`Hoa\Compiler`
library](http://central.hoa-project.net/Resource/Library/Compiler)).

## Installation

With [Composer](http://getcomposer.org/), to include this library into your
dependencies, you need to require
[`hoa/json`](https://packagist.org/packages/hoa/json):

```json
{
    "require": {
        "hoa/json": "~1.0"
    }
}
```

Please, read the website to [get more informations about how to
install](http://hoa-project.net/Source.html).

## Quick usage

As a quick overview, we will see how to use the grammar to parse JSON strings.

### Parse JSON strings

All we have to do is to use the [`Hoa\Compiler`
library](http://central.hoa-project.net/Resource/Library/Compiler). For
instance, in CLI:

```sh
$ echo '{"foo": 42, "bar": [1, [2, [3, 5], 8], 13]}' | hoa compiler:pp hoa://Library/Json/Grammar.pp 0 -v dump
>  #object
>  >  #pair
>  >  >  token(string:string, foo)
>  >  >  token(number, 42)
>  >  #pair
>  >  >  token(string:string, bar)
>  >  >  #array
>  >  >  >  token(number, 1)
>  >  >  >  #array
>  >  >  >  >  token(number, 2)
>  >  >  >  >  #array
>  >  >  >  >  >  token(number, 3)
>  >  >  >  >  >  token(number, 5)
>  >  >  >  >  token(number, 8)
>  >  >  >  token(number, 13)
```

## Documentation

Different documentations can be found on the website:
[http://hoa-project.net/](http://hoa-project.net/).

## License

Hoa is under the New BSD License (BSD-3-Clause). Please, see
[`LICENSE`](http://hoa-project.net/LICENSE).


text:
    #include "chrono_irrlicht/ChVisualSystemIrrlicht.h"
#endif

using namespace chrono;

// =============================================================================

template <int N>
class MixerTestNSC : public utils::ChBenchmarkTest {
  public:
    MixerTestNSC();
    ~MixerTestNSC() { delete m_system; }

    ChSystem* GetSystem() override { return m_system; }
    void ExecuteStep() override { m_system->DoStepDynamics(m_step); }

    void SimulateVis();

  private:
    ChSystemNSC* m_system;
    double m_step;
};

template <int N>
MixerTestNSC<N>::MixerTestNSC() : m_system(new ChSystemNSC()), m_step(0.02) {
    auto mat = chrono_types::make_shared<ChMaterialSurfaceNSC>();

    for (int bi = 0; bi < N; bi++) {
        auto sphereBody = chrono_types::make_shared<ChBodyEasySphere>(1.0, 1000, true, true, mat);
        sphereBody->SetPos(ChVector<>(-5 + ChRandom() * 10, 4 + bi * 0.05, -5 + ChRandom() * 10));
        m_system->Add(sphereBody);

        auto boxBody = chrono_types::make_shared<ChBodyEasyBox>(1.25, 1.25, 1.25, 1000, true, true, mat);
        boxBody->SetPos(ChVector<>(-5 + ChRandom() * 10, 4 + bi * 0.05, -5 + ChRandom() * 10));
        m_system->Add(boxBody);

        auto cylBody = chrono_types::make_shared<ChBodyEasyCylinder>(0.8, 1.0, 1000, true, true, mat);
        cylBody->SetPos(ChVector<>(-5 + ChRandom() * 10, 4 + bi * 0.05, -5 + ChRandom() * 10));
        m_system->Add(cylBody);
    }

    auto floorBody = chrono_types::make_shared<ChBodyEasyBox>(20, 1, 20, 1000, true, true, mat);
    floorBody->SetPos(ChVector<>(0, -5, 0));
    floorBody->SetBodyFixed(true);
    m_system->Add(floorBody);

    auto wallBody1 = chrono_types::make_shared<ChBodyEasyBox>(1, 10, 20.99, 1000, true, true, mat);
    wallBody1->SetPos(ChVector<>(-10, 0, 0));
    wallBody1->SetBodyFixed(true);
    m_system->Add(wallBody1);

    auto wallBody2 = chrono_types::make_shared<ChBodyEasyBox>(1, 10, 20.99, 1000, true, true, mat);
    wallBody2->SetPos(ChVector<>(10, 0, 0));
    wallBody2->SetBodyFixed(true);
    m_system->Add(wallBody2);

    auto wallBody3 = chrono_types::make_shared<ChBodyEasyBox>(20.99, 10, 1, 1000, true, true, mat);
    wallBody3->SetPos(ChVector<>(0, 0, -10));
    wallBody3->SetBodyFixed(true);
    m_system->Add(wallBody3);

    auto wallBody4 = chrono_types::make_shared<ChBodyEasyBox>(20.99, 10, 1, 1000, true, true, mat);
    wallBody4->SetPos(ChVector<>(0, 0, 10));
    wallBody4->SetBodyFixed(true);
    m_system->Add(wallBody4);

    auto rotatingBody = chrono_types::make_shared<ChBodyEasyBox>(10, 5, 1, 4000, true, true, mat);
    rotatingBody->SetPos(ChVector<>(0, -1.6, 0));
    m_system->Add(rotatingBody);

    auto motor = chrono_types::make_shared<ChLinkMotorRotationSpeed>();
    motor->Initialize(rotatingBody, floorBody, ChFrame<>(ChVector<>(0, 0, 0), Q_from_AngAxis(CH_C_PI_2, VECT_X)));
    auto fun = chrono_types::make_shared<ChFunction_Const>(CH_C_PI / 3.0);
    motor->SetSpeedFunction(fun);
    m_system->AddLink(motor);
}

template <int N>
void MixerTestNSC<N>::SimulateVis() {
#ifdef CHRONO_IRRLICHT
    // Create the Irrlicht visualization system
    auto vis = chrono_types::make_shared<irrlicht::ChVisualSystemIrrlicht>();
    m_system->SetVisualSystem(vis);
    vis->SetWindowSize(800, 600);
    vis->SetWindowTitle("Rigid contacts");
    vis->Initialize();
    vis->AddLogo();
    vis->AddSkyBox();
    vis->AddTypicalLights();
    vis->AddCamera(ChVector<>(0, 14, -20), ChVector<>(0, 0, 0));

    while (vis->Run()) {
        vis->BeginScene();
        vis->DrawAll();
        ExecuteStep();
        vis->EndScene();
    }
#endif
}

// =============================================================================

#define NUM_SKIP_STEPS 2000  // number of steps for hot start
#define NUM_SIM_STEPS 1000   // number of simulation steps for each benchmark

CH_BM_SIMULATION_LOOP(MixerNSC032, MixerTestNSC<32>,  NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(MixerNSC064, MixerTestNSC<64>,  NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);

// =============================================================================

int main(int argc, char* argv[]) {
    ::benchmark::Initialize(&argc, argv);

#ifdef CHRONO_IRRLICHT
    if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
        MixerTestNSC<64> test;
        test.SimulateVis();
        return 0;
    }
#endif

    ::benchmark::RunSpecifiedBenchmarks();
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**rc** | [**\Swagger\Client\Model\RunnerChange[]**](RunnerChange.md) | Runner Changes - a list of changes to runners (or null if un-changed) | [optional]
**img** | **bool** | Image - replace existing prices / data with the data supplied: it is not a delta (or null if delta) | [optional]
**tv** | **double** | The total amount matched across the market. This value is truncated at 2dp (or null if un-changed) | [optional]
**con** | **bool** | Conflated - have more than a single change been combined (or null if not conflated) | [optional]
**market_definition** | [**\Swagger\Client\Model\MarketDefinition**](MarketDefinition.md) | Market Definition - the definition of the market (or null if un-changed) | [optional]
**id** | **string** | Market Id - the id of the market | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
using System;

public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to a nullable long.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a long?</returns>
    public static long? ToNullableLong(this object @this)
    {
        if (@this == null || @this == DBNull.Value)
        {
            return null;
        }

        return Convert.ToInt64(@this);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lichenologist 15(2): 113 (1983)

#### Original name
Lichen cochleatus J. Dicks.

### Remarks
null


text:
package session

import (
	"encoding/json"
	"sync/atomic"
	"time"

	"github.com/eclipse/paho.mqtt.golang/packets"

	log "github.com/Sirupsen/logrus"

	"github.com/iotalking/mqtt-broker/config"
	"github.com/iotalking/mqtt-broker/dashboard"
	"github.com/iotalking/mqtt-broker/store"
)

//处理 CONNECT 消息
//连接消息
func (this *Session) onConnect(msg *packets.ConnectPacket) (err error) {
	//如果已经连接,则是违规,应该断开
	if this.IsConnected() {
		log.Error("connected client dup CONNECT")
		return packets.ConnErrors[packets.ErrProtocolViolation]
	}
	//判断保留标志位是否为0,如果不为0,返回协议错误
	if msg.ReservedBit&0x1 == 0x1 {
		log.Error("client ReservedBit != 0")
		return packets.ConnErrors[packets.ErrProtocolViolation]
	}
	//检查是否有相同clientId的连接,如果有,则要断开原有连接
	this.clientId = msg.ClientIdentifier
	this.mgr.DisconectSessionByClientId(this.clientId)

	conack := packets.NewControlPacket(packets.Connack).(*packets.ConnackPacket)
	conack.ReturnCode = packets.Accepted
	if msg.CleanSession {
		conack.SessionPresent = false
	} else {
		//如果服务器有保存session,则 SessionPresent设成true
		//如果服务器没有保存session,则SessionPresent设成false
		conack.SessionPresent = false
	}

	log.Debug("sessionMgr.OnConnected")
	this.mgr.OnConnected(this)

	log.Debug("session.Send")

	err = this.channel.Send(conack)
	atomic.StoreInt32(&this.connected, 1)

	if msg.WillFlag {
		this.willFlag = true
		this.willTopic = msg.WillTopic
		this.willQos = msg.WillQos
		this.willMessage = msg.WillMessage
	}

	//save keep alive (seconds)
	this.keepalive = int64(float64(msg.Keepalive) * 1.5 * float64(time.Second))
	this.resetTimeout()
	return
}

//处理 CONNACK 消息
//连接应答消息
//此消息只有作为客户端时才会收到
func (this *Session) onConnack(msg *packets.ConnackPacket) error {

	if msg.ReturnCode > 0 {
		log.Debug("server return conack code is:", msg.ReturnCode)
		atomic.StoreInt32(&this.connected, -int32(msg.ReturnCode))
	} else {
		log.Debug("Session was connected")
		atomic.StoreInt32(&this.connected, 1)
	}
	this.mgr.OnConnected(this)
	if this.connectToken != nil {
		if msg.ReturnCode != packets.Accepted {
			//验证失败
			this.connectToken.err = packets.ConnErrors[msg.ReturnCode]
		}
		this.connectToken.flowComplete()
	}

	return nil
}

//由独立的协程调用,注意共享数据访问
func (this *Session) BroadcastSessionInfo() {

	subMgr := this.mgr.GetSubscriptionMgr()
	infoTopic := config.SessionInfoTopic(this.clientId)
	sessionQosMap, err := subMgr.GetSessions(infoTopic)
	if err != nil {
		log.Error("subMgr.GetSessions error:", err)
		return
	}
	if len(sessionQosMap) == 0 {
		log.Debug("sessionQosMap is empty for topic:", infoTopic)
		return
	}
	nmsg := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
	var info SessionInfo
	info.Id = this.clientId
	info.InflightMsgCnt = this.inflightingList.Len()
	info.PeddingMsgCnt = this.peddingMsgList.Len()
	info.SendingMsgCnt = this.channel.iSendList.Len()
	bs, err := json.MarshalIndent(info, "", "\t")
	log.Debug("broadcastSessionInfo ", info)

	if err != nil {
		log.Error("broadcastSessionInfo json.MarshalIndent :", err)
		return
	}
	nmsg.Payload = bs
	//qos取订阅和原消息的最小值
	nmsg.Qos = 0

	for v, _ := range sessionQosMap {
		s := v.(*Session)
		if s.IsConnected() && !s.IsClosed() {
			_, err = s.Publish(nmsg)
			if err != nil {
				log.Errorf("session[%s].Publish Send error:", s.clientId, err)
				break
			}
		} else {
			log.Debug("session is disconnected or not connect")
		}

	}

	return
}

//要除自己之外的所有订阅者
func (this *Session) sendToSubcriber(msg *packets.PublishPacket) error {
	log.Debug("sendToSubcriber")
	subMgr := this.mgr.GetSubscriptionMgr()

	sessionQosMap, err := subMgr.GetSessions(msg.TopicName)
	if err != nil {
		log.Error("subMgr.GetSessions error:", err)
		return err
	}
	if len(sessionQosMap) == 0 {
		log.Debug("sessionQosMap is empty for topic:", msg.TopicName)
	}
	log.Debug("sessionQosMap len:", len(sessionQosMap))
	msg.Retain = false
	for v, qos := range sessionQosMap {
		s := v.(*Session)
		if config.SendToSelf == false {
			//不给自己发消息
			if s == this {
				continue
			}
		}
		if s.IsConnected() && !s.IsClosed() {
			nmsg := msg.Copy()
			//qos取订阅和原消息的最小值
			if qos < msg.Qos {
				nmsg.Qos = qos
			}
			_, err = s.Publish(msg)
			if err != nil {
				log.Errorf("session[%s].Publish Send error:", s.clientId, err)
				break
			}
		} else {
			log.Debug("session is disconnected or not connect")
		}

	}

	return nil
}

//处理 PUBLISH 消息
//发布消息
//retain消息的处理方式:
//1.服务端只保存payload不为空的消息
//2.服务端收到payload为空的消息清空以前相关主题的消息
func (this *Session) onPublish(msg *packets.PublishPacket) (err error) {
	log.Debug("session onpublish")
	//从mgr获取和tipic匹配的sessions
	//TODO:获取匹配的sessions
	payloadLen := len(msg.Payload)
	if payloadLen == 0 {
		if msg.Retain {
			err = this.mgr.GetStoreMgr().RemoveMsgByTopic(msg.TopicName)
			if err != nil {
				log.Errorf("this.mgr.storeMgr.RemoveMsgByTopic error:", err)
				if err == store.ErrNoExsit {
					err = nil
				} else {
					return
				}
			}
		}

	}
	switch msg.Qos {
	case 0:
		if msg.Retain {
			//清空离线消息
			if payloadLen > 0 {
				err = this.mgr.GetStoreMgr().RemoveMsgByTopic(msg.TopicName)
				if err != nil {
					log.Errorf("this.mgr.storeMgr.RemoveMsgByTopic error:", err)
					if err == store.ErrNoExsit {
						err = nil
					}
				}
				log.Debugf("retain msg has clear for client:%s", this.clientId)

				err = this.mgr.GetStoreMgr().SaveRetainMsg(msg.TopicName, msg.Payload, msg.Qos)
				if err != nil {
					log.Errorf("SaveRetainMsg error:%s", err.Error())
				}
			}

		}
		dashboard.Overview.RecvMsgCnt.Add(1)
		if this.isServer {
			this.sendToSubcriber(msg)
		} else {
			//回调接入到消息的函数
			this.callbackOnMessage(msg)
		}
	case 1:
		ack := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
		ack.MessageID = msg.MessageID
		this.channel.Send(ack)
		dashboard.Overview.RecvMsgCnt.Add(1)
		smsg := &store.Msg{
			ClientId: this.clientId,
			MsgId:    msg.MessageID,
			Topic:    msg.TopicName,
			Qos:      msg.Qos,
			Body:     msg.Payload,
		}

		if msg.Retain {
			if payloadLen > 0 {
				err = this.mgr.GetStoreMgr().SaveRetainMsg(smsg.Topic, smsg.Body, smsg.Qos)
				if err != nil {
					log.Error(err)
					err = packets.ConnErrors[packets.ErrRefusedServerUnavailable]
					return
				}
			}

		}

		if this.isServer {
			this.sendToSubcriber(msg)
		} else {
			//回调接入到消息的函数
			this.callbackOnMessage(msg)
		}
	case 2:
		ack := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket)
		ack.MessageID = msg.MessageID
		this.channel.Send(ack)

		storeMgr := this.mgr.GetStoreMgr()
		if _, err = storeMgr.GetMsgByClientIdMsgId(this.clientId, msg.MessageID); err == store.ErrNoExsit {
			//保存消息,等待PUBREL后再发送
			smsg := &store.Msg{
				ClientId: this.clientId,
				MsgId:    msg.MessageID,
				Topic:    msg.TopicName,
				Qos:      msg.Qos,
				Body:     msg.Payload,
			}
			err = storeMgr.SaveByClientIdMsgId(smsg)
			if err != nil {
				log.Error(err)
				err = packets.ConnErrors[packets.ErrRefusedServerUnavailable]
				return
			}
			if msg.Retain {
				if payloadLen > 0 {
					err = this.mgr.GetStoreMgr().SaveRetainMsg(smsg.Topic, smsg.Body, smsg.Qos)
					if err != nil {
						log.Error(err)
						err = packets.ConnErrors[packets.ErrRefusedServerUnavailable]
						return
					}
				}

			}
		}

	}
	return err
}

//处理 PUBACK 消息
//向qos=1的主题消息发布者应答
func (this *Session) onPuback(msg *packets.PubackPacket) error {
	this.onInflightDone(msg)
	return nil
}

//处理 PUBREC 消息
func (this *Session) onPubrec(msg *packets.PubrecPacket) error {

	relmsg := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
	relmsg.MessageID = msg.MessageID
	this.channel.Send(relmsg)

	this.updateInflightMsg(relmsg)
	return nil
}

//处理 PUBREL 消息
//向qos=2的主题消息发布者应答服务器第二步
//对PUBREC的响应
func (this *Session) onPubrel(msg *packets.PubrelPacket) error {
	compmsg := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket)
	compmsg.MessageID = msg.MessageID
	this.channel.Send(compmsg)

	storeMgr := this.mgr.GetStoreMgr()
	smsg, err := storeMgr.GetMsgByClientIdMsgId(this.clientId, msg.MessageID)
	if err != nil {
		log.Debugf("onPubrel error:%s,clientId:%s,msgId:%d", err, this.clientId, msg.MessageID)
		return nil
	}
	dashboard.Overview.RecvMsgCnt.Add(1)

	storeMgr.RemoveMsgById(smsg.Id)

	pubMsg := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
	pubMsg.Qos = smsg.Qos
	pubMsg.Payload = smsg.Body
	pubMsg.TopicName = smsg.Topic

	if this.isServer {
		this.sendToSubcriber(pubMsg)
	} else {
		//回调接入到消息的函数
		this.callbackOnMessage(pubMsg)
	}
	return nil
}

//处理 PUBCOMP 消息
//向qos=2的主题消息发布者应答服务器第三步(发布完成)
//对PUBREL的响应
//它是QoS 2等级协议交换的第四个也是最后一个报文
func (this *Session) onPubcomp(msg *packets.PubcompPacket) error {
	this.onInflightDone(msg)
	return nil
}

//处理 SUBSCRIBE - 订阅主题消息
//客户端向服务端发送SUBSCRIBE报文用于创建一个或多个订阅。
//每个订阅注册客户端关心的一个或多个主题。为了将应用消息转发给与那些订阅匹配的主题,服务端发送PUBLISH报文给客户端。
//SUBSCRIBE报文也(为每个订阅)指定了最大的QoS等级,服务端根据这个发送应用消息给客户端。
func (this *Session) onSubscribe(msg *packets.SubscribePacket) error {
	log.Debug("session.onSubscribe")
	submgr := this.mgr.GetSubscriptionMgr()

	err := submgr.Add(msg.Topics, msg.Qoss, this)

	suback := packets.NewControlPacket(packets.Suback).(*packets.SubackPacket)
	suback.MessageID = msg.MessageID

	suback.ReturnCodes = msg.Qoss
	for i, _ := range msg.Qoss {
		if err != nil {
			suback.ReturnCodes[i] = 0x80
		}

	}
	//向客户端发送匹配主题的retain消息
	go this.procRetainMessages(msg)

	return this.channel.Send(suback)
}
func (this *Session) procRetainMessages(msg *packets.SubscribePacket) {
	subMgr := this.mgr.GetSubscriptionMgr()
	storeMgr := this.mgr.GetStoreMgr()
	msgs, err := storeMgr.GetAllRetainMsgs()
	if err != nil {
		log.Debug("no retain messages")
		return
	}

	log.Debug("retain len:", len(msgs))
	for _, msg := range msgs {
		pubMsg := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
		log.Debugf("%#v", msg)
		pubMsg.Retain = true
		pubMsg.TopicName = msg.Topic
		pubMsg.Qos = msg.Qos
		pubMsg.Payload = msg.Body
		if subMgr.IsTopicMatch(msg.Topic, msg.Topic) {
			//匹配主题,发送给session
			this.Publish(pubMsg)
		}
	}
}

//处理 SUBACK – 订阅确认
//服务端发送SUBACK报文给客户端,用于确认它已收到并且正在处理SUBSCRIBE报文。
//SUBACK报文包含一个返回码清单,它们指定了SUBSCRIBE请求的每个订阅被授予的最大QoS等级。
func (this *Session) onSuback(msg *packets.SubackPacket) error {
	this.onInflightDone(msg)
	return nil
}

//处理 UNSUBACK –取消订阅
//客户端发送UNSUBSCRIBE报文给服务端,用于取消订阅主题。
func (this *Session) onUnsubscribe(msg *packets.UnsubscribePacket) error {
	submgr := this.mgr.GetSubscriptionMgr()
	for _, s := range msg.Topics {
		submgr.Remove(s, this)
	}
	ack := &packets.UnsubackPacket{
		MessageID: msg.MessageID,
	}
	this.channel.Send(ack)
	return nil
}

//处理 UNSUBSCRIBE –取消订阅确认
//服务端发送UNSUBACK报文给客户端。
func (this *Session) onUnsuback(msg *packets.UnsubackPacket) error {
	this.onInflightDone(msg)
	return nil
}

//处理 PINGREQ
func (this *Session) onPingreq(msg *packets.PingreqPacket) error {
	pingresp := packets.NewControlPacket(packets.Pingresp).(*packets.PingrespPacket)
	this.channel.Send(pingresp)
	return nil
}

//处理 PINGRESP
//服务端发送PINGRESP报文响应客户端的PINGREQ报文。表示服务端还活着。
//保持连接(Keep Alive)处理中用到这个报文
func (this *Session) onPingresp(msg *packets.PingrespPacket) error {
	//TODO
	return nil
}

//处理 DISCONNECT
//从sessionMgr中删除session
//断开网络
func (this *Session) onDisconnect(msg *packets.DisconnectPacket) error {
	log.Debugf("session(%s) onDisconnect", this.clientId, this.sentMsgChan)
	this.mgrOnDisconnected()

	log.Debugf("session(%s) onDisconnect end", this.clientId)
	return nil
}

//消息发送完成。走完所有流程
func (this *Session) onInflightDone(msg packets.ControlPacket) {
	switch msg.Type() {
	case packets.Publish:
		if msg.Details().Qos > 0 {
			break
		}
		fallthrough
	case packets.Puback, packets.Pubcomp, packets.Suback, packets.Unsuback:
		imsg := this.removeInflightMsg(msg.Details().MessageID)
		if imsg != nil && imsg.pt != nil && imsg.pt.t != nil {
			switch msg.Type() {
			case packets.Suback:
				var subToken *SubscribeToken = imsg.pt.t.(*SubscribeToken)
				subackMsg := msg.(*packets.SubackPacket)
				for i, sub := range subToken.subs {
					subToken.subResult[sub] = subackMsg.ReturnCodes[i]
				}
			}
			log.Debug("flowComplete for msgId:", imsg.pt.p.Details().MessageID)
			imsg.pt.t.flowComplete()
		}
	}

	if this.inflightingList.Len() < config.MaxSizeOfInflight {
		select {
		case <-this.peddingChan:
		default:
		}
		v := this.peddingMsgList.Pop()
		if v != nil {
			this.insert2Inflight(v.(*PacketAndToken))
		}
	}
	dashboard.Overview.SentMsgCnt.Add(1)
}


text:
package io.dropwizard.lifecycle;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.junit.jupiter.api.Test;

public class AutoCloseableManagerTest {

    private final AutoCloseable managed = mock(AutoCloseable.class);
    private final AutoCloseableManager closeableManager = new AutoCloseableManager(this.managed);

    @Test
    void startsAndStops() throws Exception {
        this.closeableManager.start();
        this.closeableManager.stop();

        verify(this.managed).close();
    }

}


text:
import Ember from 'ember';

export default Ember.Route.extend({

  kubeClient: Ember.inject.service(),

  model(params) {
    return this.get('kubeClient').findRecord('node', null, params.name);
  }

});


text:
var createCORSRequest = require('./cors');
/**
 * @module core/fetch
 * @type {Promise}
 */
module.exports =  function fetch(obj, options) {
  options = options || {};
  options.parser = options.parser || function(request){return JSON.parse(request.responseText)};
  var request = createCORSRequest(obj.method, obj.url, options);
  if (!request) {
    throw new Error('You cannot perform ajax request on other domains.');
  }
  return new Promise(function (success, failure) {
    //Request error handler
    request.onerror = function (error) {
      failure(error);
    };
    //Request success handler
    request.onload = function () {
      var status = request.status;
      if (status !== 200) {
        var err = JSON.parse(request.response);
        err.statusCode = status;
        failure(err);
      }
      var contentType = request.getResponseHeader('content-type');
      var data;
      if (contentType && contentType.indexOf("application/json") !== -1) {
        data = options.parser(request);
      } else {
        data = request.responseText;
      }
      success(data);
    };
    //Execute the request.
    request.send(JSON.stringify(obj.data));
  });

};


text:
import { ExpressionFormatter } from "./expression.formatter";
import { createInjector, resolve2, resolveMock } from "../../../../tests.components/resolve.builder";
import {
    FunctionExpression,
    GetPropertyExpression,
    MethodExpression,
    NewOperatorExpression
} from "../../../reflector/expressions";
import { FunctionFormatter } from "../../../formatters/function.formatter";
import { PropertyKeyFormatter } from "../../../formatters/property-key.formatter";
import { MethodFormatter } from "../../../formatters/method.formatter";
import { ConstantFormatter } from "../../../formatters/constant.formatter";

describe("Expression formatter", () => {

    beforeEach(() => {
        createInjector(ExpressionFormatter, [FunctionFormatter, PropertyKeyFormatter, MethodFormatter, ConstantFormatter]);
    });

    it("Returns function presentation", () => {
        const name = "name";
        const expression = new FunctionExpression([]);
        const presentation = "presentation";

        resolveMock(FunctionFormatter)
            .setup(instance => instance.format(expression))
            .returns(presentation);

        const formatter = resolve2(ExpressionFormatter);
        const actual = formatter.format(expression, name);

        expect(actual).toEqual(presentation);
    });

    it("Returns get property presentation", () => {
        const name = "name";
        const propertyName = "property name";
        const expression = new GetPropertyExpression(propertyName);
        const presentation = "presentation";

        resolveMock(PropertyKeyFormatter)
            .setup(instance => instance.format(propertyName))
            .returns(presentation);

        const formatter = resolve2(ExpressionFormatter);
        const actual = formatter.format(expression, name);

        expect(actual).toEqual(`.${presentation}`);
    });

    it("Returns method presentation", () => {
        const name = "name";
        const expression = new MethodExpression("property name", []);
        const presentation = "presentation";

        resolveMock(MethodFormatter)
            .setup(instance => instance.format(expression))
            .returns(presentation);

        const formatter = resolve2(ExpressionFormatter);
        const actual = formatter.format(expression, name);

        expect(actual).toEqual(`.${presentation}`);
    });

    it("Returns new operator presentation", () => {
        const name = "name";
        const expression = new NewOperatorExpression([]);
        const presentation = "presentation";

        resolveMock(ConstantFormatter)
            .setup(instance => instance.format(expression.args))
            .returns(presentation);

        const formatter = resolve2(ExpressionFormatter);
        const actual = formatter.format(expression, name);

        expect(actual).toEqual(`new ${name}(${presentation})`);
    });
});


text:
//public struct UserField {
//    public string Name { get; private set; }
//    public double Value { get; private set; }

//    public UserField(string name, double value) {
//        Name = name;
//        Value = value;
//    }

//}