text:
namespace google {
namespace protobuf {
namespace compiler {
namespace java {

class PrimitiveFieldGenerator : public FieldGenerator {
 public:
  explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor,
      int messageBitIndex, int builderBitIndex);
  ~PrimitiveFieldGenerator();

  // implements FieldGenerator ---------------------------------------
  int GetNumBitsForMessage() const;
  int GetNumBitsForBuilder() const;
  void GenerateInterfaceMembers(io::Printer* printer) const;
  void GenerateMembers(io::Printer* printer) const;
  void GenerateBuilderMembers(io::Printer* printer) const;
  void GenerateInitializationCode(io::Printer* printer) const;
  void GenerateBuilderClearCode(io::Printer* printer) const;
  void GenerateMergingCode(io::Printer* printer) const;
  void GenerateBuildingCode(io::Printer* printer) const;
  void GenerateParsingCode(io::Printer* printer) const;
  void GenerateSerializationCode(io::Printer* printer) const;
  void GenerateSerializedSizeCode(io::Printer* printer) const;
  void GenerateFieldBuilderInitializationCode(io::Printer* printer) const;
  void GenerateEqualsCode(io::Printer* printer) const;
  void GenerateHashCode(io::Printer* printer) const;

  string GetBoxedType() const;

 private:
  const FieldDescriptor* descriptor_;
  map<string, string> variables_;
  const int messageBitIndex_;
  const int builderBitIndex_;

  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
};

class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
 public:
  explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
      int messageBitIndex, int builderBitIndex);
  ~RepeatedPrimitiveFieldGenerator();

  // implements FieldGenerator ---------------------------------------
  int GetNumBitsForMessage() const;
  int GetNumBitsForBuilder() const;
  void GenerateInterfaceMembers(io::Printer* printer) const;
  void GenerateMembers(io::Printer* printer) const;
  void GenerateBuilderMembers(io::Printer* printer) const;
  void GenerateInitializationCode(io::Printer* printer) const;
  void GenerateBuilderClearCode(io::Printer* printer) const;
  void GenerateMergingCode(io::Printer* printer) const;
  void GenerateBuildingCode(io::Printer* printer) const;
  void GenerateParsingCode(io::Printer* printer) const;
  void GenerateParsingCodeFromPacked(io::Printer* printer) const;
  void GenerateSerializationCode(io::Printer* printer) const;
  void GenerateSerializedSizeCode(io::Printer* printer) const;
  void GenerateFieldBuilderInitializationCode(io::Printer* printer) const;
  void GenerateEqualsCode(io::Printer* printer) const;
  void GenerateHashCode(io::Printer* printer) const;

  string GetBoxedType() const;

 private:
  const FieldDescriptor* descriptor_;
  map<string, string> variables_;
  const int messageBitIndex_;
  const int builderBitIndex_;

  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
};

}  // namespace java
}  // namespace compiler
}  // namespace protobuf

}  // namespace google
#endif  // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__


text:
SYNONYM

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

#### Published in
Trans. Linn. Soc. London, Bot. 2: 46 (1882)

#### Original name
Lecidea enteroxantha C. Knight

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>dataleach.webgrabber</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package dataleach ::
        Package webgrabber

[hide private]

[frames] | no frames]

Package webgrabber

source code

        Classes
        [hide private]

        WebGrabber

      Class for retrieving a webpage.

        Functions
        [hide private]

          main()

            source code

        Variables
        [hide private]

        logger = logging.getLogger("dataleach.webgrabber")

        __package__ = 'dataleach.webgrabber'

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Fri Oct 14 15:52:04 2011

      http://epydoc.sourceforge.net


text:
package org.apache.helix.controller.stages;

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

import org.apache.helix.AccessOption;
import org.apache.helix.HelixConstants;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.common.DedupEventProcessor;
import org.apache.helix.controller.dataproviders.BaseControllerDataProvider;
import org.apache.helix.controller.pipeline.AsyncWorkerType;
import org.apache.helix.task.TaskUtil;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.common.caches.TaskDataCache;
import org.apache.helix.controller.dataproviders.WorkflowControllerDataProvider;
import org.apache.helix.controller.stages.task.TaskPersistDataStage;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.TaskTestUtil;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.JobContext;
import org.apache.helix.task.JobQueue;
import org.apache.helix.task.TaskPartitionState;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.WorkflowContext;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestTaskStage extends TaskTestBase {
  private ClusterEvent _event =
      new ClusterEvent(CLUSTER_NAME, ClusterEventType.TaskCurrentStateChange);
  private PropertyKey.Builder _keyBuilder;
  private String _testWorkflow = TestHelper.getTestClassName();
  private String _testJobPrefix = _testWorkflow + "_Job_";

  @BeforeClass
  public void beforeClass() throws Exception {
    super.beforeClass();
    // Stop the controller for isolated testing of the stage
    _controller.syncStop();
    _keyBuilder = _manager.getHelixDataAccessor().keyBuilder();
  }

  @Test
  public void testPersistContextData() {
    _event.addAttribute(AttributeName.helixmanager.name(), _manager);

    WorkflowControllerDataProvider cache = new WorkflowControllerDataProvider(CLUSTER_NAME);
    TaskDataCache taskDataCache = cache.getTaskDataCache();

    // Build a queue
    JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(_testWorkflow);
    JobConfig.Builder jobBuilder_0 =
        new JobConfig.Builder().setJobId("Job_0").setTargetResource("1").setCommand("1");
    JobConfig.Builder jobBuilder_1 =
        new JobConfig.Builder().setJobId("Job_0").setTargetResource("1").setCommand("1");
    JobConfig.Builder jobBuilder_2 =
        new JobConfig.Builder().setJobId("Job_0").setTargetResource("1").setCommand("1");
    queueBuilder.enqueueJob("Job_0", jobBuilder_0).enqueueJob("Job_1", jobBuilder_1)
        .enqueueJob("Job_2", jobBuilder_2);

    _driver.createQueue(queueBuilder.build());
    // Manually trigger a cache refresh
    cache.refresh(new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor));

    // Create the context
    WorkflowContext wfCtx = new WorkflowContext(new ZNRecord(TaskUtil.WORKFLOW_CONTEXT_KW));
    wfCtx.setJobState(_testJobPrefix + "0", TaskState.COMPLETED);
    wfCtx.setJobState(_testJobPrefix + "1", TaskState.COMPLETED);
    wfCtx.setWorkflowState(TaskState.IN_PROGRESS);
    wfCtx.setName(_testWorkflow);
    wfCtx.setStartTime(System.currentTimeMillis());

    JobContext jbCtx0 = new JobContext(new ZNRecord(_testJobPrefix + "0"));
    jbCtx0.setName(_testJobPrefix + "0");
    jbCtx0.setStartTime(System.currentTimeMillis());
    jbCtx0.setPartitionState(0, TaskPartitionState.COMPLETED);

    JobContext jbCtx1 = new JobContext((new ZNRecord(_testJobPrefix + "1")));
    jbCtx1.setName(_testJobPrefix + "1");
    jbCtx1.setStartTime(System.currentTimeMillis());
    jbCtx1.setPartitionState(0, TaskPartitionState.COMPLETED);

    taskDataCache.updateWorkflowContext(_testWorkflow, wfCtx);
    taskDataCache.updateJobContext(_testJobPrefix + "0", jbCtx0);
    taskDataCache.updateJobContext(_testJobPrefix + "1", jbCtx1);

    _event.addAttribute(AttributeName.ControllerDataProvider.name(), cache);

    // Write contexts to ZK first
    TaskPersistDataStage persistDataStage = new TaskPersistDataStage();
    persistDataStage.process(_event);

    Assert.assertNotNull(_driver.getWorkflowContext(_testWorkflow));
    Assert.assertNotNull(_driver.getJobContext(_testJobPrefix + "0"));
    Assert.assertNotNull(_driver.getJobContext(_testJobPrefix + "1"));

    jbCtx0.setPartitionState(0, TaskPartitionState.ERROR);
    wfCtx.setJobState(_testJobPrefix + "0", TaskState.FAILED);
    taskDataCache.updateJobContext(_testJobPrefix + "0", jbCtx0);

    wfCtx.getJobStates().remove(_testJobPrefix + "1");
    taskDataCache.removeContext(_testJobPrefix + "1");

    JobContext jbCtx2 = new JobContext(new ZNRecord(_testJobPrefix + "2"));
    jbCtx2.setName(_testJobPrefix + "2");
    jbCtx2.setPartitionState(1, TaskPartitionState.INIT);
    wfCtx.setJobState(_testJobPrefix + "2", TaskState.IN_PROGRESS);
    taskDataCache.updateJobContext(_testJobPrefix + "2", jbCtx2);

    taskDataCache.updateWorkflowContext(_testWorkflow, wfCtx);

    persistDataStage.process(_event);

    Assert.assertEquals(_driver.getWorkflowContext(_testWorkflow), wfCtx);
    Assert.assertEquals(_driver.getJobContext(_testJobPrefix + "0"), jbCtx0);
    Assert.assertEquals(_driver.getJobContext(_testJobPrefix + "2"), jbCtx2);
    Assert.assertNull(_driver.getJobContext(_testJobPrefix + "1"));
  }

  /**
   * Test that if there is a job in the DAG with JobConfig gone (due to ZK delete failure), the
   * async job purge will try to delete it again.
   */
  @Test(dependsOnMethods = "testPersistContextData")
  public void testPartialDataPurge() throws Exception {
    DedupEventProcessor<String, Runnable> worker =
        new DedupEventProcessor<String, Runnable>(CLUSTER_NAME,
            AsyncWorkerType.TaskJobPurgeWorker.name()) {
          @Override
          protected void handleEvent(Runnable event) {
            event.run();
          }
        };
    worker.start();
    Map<AsyncWorkerType, DedupEventProcessor<String, Runnable>> workerPool = new HashMap<>();
    workerPool.put(AsyncWorkerType.TaskJobPurgeWorker, worker);
    _event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), workerPool);

    // Manually delete JobConfig
    deleteJobConfigs(_testWorkflow, _testJobPrefix + "0");
    deleteJobConfigs(_testWorkflow, _testJobPrefix + "1");
    deleteJobConfigs(_testWorkflow, _testJobPrefix + "2");

    // Manually refresh because there's no controller notify data change
    BaseControllerDataProvider dataProvider =
        _event.getAttribute(AttributeName.ControllerDataProvider.name());
    dataProvider.notifyDataChange(HelixConstants.ChangeType.RESOURCE_CONFIG);
    dataProvider.refresh(_manager.getHelixDataAccessor());

    // Then purge jobs
    TaskGarbageCollectionStage garbageCollectionStage = new TaskGarbageCollectionStage();
    garbageCollectionStage.process(_event);

    // Check that contexts have been purged for the 2 jobs in both old and new ZNode paths
    checkForContextRemoval(_testWorkflow, _testJobPrefix + "0");
    checkForContextRemoval(_testWorkflow, _testJobPrefix + "1");
    checkForContextRemoval(_testWorkflow, _testJobPrefix + "2");
  }

  @Test(dependsOnMethods = "testPartialDataPurge")
  public void testWorkflowGarbageCollection() throws Exception {
    DedupEventProcessor<String, Runnable> worker =
        new DedupEventProcessor<String, Runnable>(CLUSTER_NAME,
            AsyncWorkerType.TaskJobPurgeWorker.name()) {
          @Override
          protected void handleEvent(Runnable event) {
            event.run();
          }
        };
    worker.start();
    Map<AsyncWorkerType, DedupEventProcessor<String, Runnable>> workerPool = new HashMap<>();
    workerPool.put(AsyncWorkerType.TaskJobPurgeWorker, worker);
    _event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), workerPool);

    String zkPath =
        _manager.getHelixDataAccessor().keyBuilder().resourceConfig(_testWorkflow).getPath();
    _baseAccessor.remove(zkPath, AccessOption.PERSISTENT);

    // Manually refresh because there's no controller notify data change
    BaseControllerDataProvider dataProvider =
        _event.getAttribute(AttributeName.ControllerDataProvider.name());
    dataProvider.notifyDataChange(HelixConstants.ChangeType.RESOURCE_CONFIG);
    dataProvider.refresh(_manager.getHelixDataAccessor());

    // Then garbage collect workflow
    TaskGarbageCollectionStage garbageCollectionStage = new TaskGarbageCollectionStage();
    garbageCollectionStage.process(_event);

    // Check that contexts have been purged for the workflow
    checkForContextRemoval(_testWorkflow);

    worker.shutdown();
  }

  private void deleteJobConfigs(String workflowName, String jobName) {
    String oldPath = _manager.getHelixDataAccessor().keyBuilder().resourceConfig(jobName).getPath();
    String newPath = _manager.getHelixDataAccessor().keyBuilder()
        .jobConfigZNode(workflowName, jobName).getPath();
    _baseAccessor.remove(oldPath, AccessOption.PERSISTENT);
    _baseAccessor.remove(newPath, AccessOption.PERSISTENT);
  }

  private void checkForContextRemoval(String workflow, String job) throws Exception {
    // JobContexts in old ZNode path
    String oldPath =
        String.format("/%s/PROPERTYSTORE/TaskRebalancer/%s/Context", CLUSTER_NAME, job);
    String newPath = _keyBuilder.jobContextZNode(workflow, job).getPath();

    Assert.assertTrue(TestHelper.verify(
        () -> !_baseAccessor.exists(oldPath, AccessOption.PERSISTENT) && !_baseAccessor
            .exists(newPath, AccessOption.PERSISTENT), 120000));
  }

  private void checkForContextRemoval(String workflow) throws Exception {
    Assert.assertTrue(TestHelper.verify(() -> !_baseAccessor
            .exists(_keyBuilder.workflowContextZNode(workflow).getPath(), AccessOption.PERSISTENT),
        120000));
  }
}


text:
require 'new_relic/agent/method_tracer'

Assessment::TrainingSubmissionsController.class_eval do
  include ::NewRelic::Agent::MethodTracer

  add_method_tracer :submit
  add_method_tracer :submit_mcq
  add_method_tracer :submit_code
end


text:
"use strict";

jest.mock("../../../src/lib/analytics");

const analytics = require("../../../src/lib/analytics");
const VisaCheckout = require("../../../src/visa-checkout/visa-checkout");
const BraintreeError = require("../../../src/lib/braintree-error");
const {
  fake: { configuration },
} = require("../../helpers");
const methods = require("../../../src/lib/methods");

describe("Visa Checkout", () => {
  let testContext;

  beforeEach(() => {
    testContext = {};
    testContext.configuration = configuration();
    testContext.client = {
      request: jest.fn().mockResolvedValue({
        visaCheckoutCards: [],
      }),
      getConfiguration: () => testContext.configuration,
    };
    testContext.visaCheckout = new VisaCheckout({
      client: testContext.client,
    });
  });

  describe("createInitOptions", () => {
    it("throws an error if options is not defined", () => {
      expect.assertions(4);

      try {
        VisaCheckout.prototype.createInitOptions.call({
          _client: testContext.client,
          _transformCardTypes: VisaCheckout.prototype._transformCardTypes,
        });
      } catch (err) {
        expect(err).toBeInstanceOf(BraintreeError);
        expect(err.code).toBe("VISA_CHECKOUT_INIT_OPTIONS_REQUIRED");
        expect(err.type).toBe("MERCHANT");
        expect(err.message).toBe("initOptions requires an object.");
      }
    });

    it("sets apikey if undefined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {}
      );

      expect(initOptions.apikey).toBe("gwApikey");
    });

    it("does not overwrite apikey if defined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        { apikey: "apikey" }
      );

      expect(initOptions.apikey).toBe("apikey");
    });

    it("sets encryptionKey", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {}
      );

      expect(initOptions.encryptionKey).toBe("gwEncryptionKey");
    });

    it("sets externalClientId if undefined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {}
      );

      expect(initOptions.externalClientId).toBe("gwExternalClientId");
    });

    it("does not overwrite externalClientId if defined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        { externalClientId: "externalClientId" }
      );

      expect(initOptions.externalClientId).toBe("externalClientId");
    });

    it("sets settings.dataLevel if undefined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        { _client: testContext.client },
        {}
      );

      expect(initOptions.settings.dataLevel).toBe("FULL");
    });

    it("overwrites settings.dataLevel if defined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {
          settings: {
            dataLevel: "summary",
          },
        }
      );

      expect(initOptions.settings.dataLevel).toBe("FULL");
    });

    it("transforms gateway visaCheckout.supportedCardTypes to settings.payment.cardBrands if undefined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {}
      );

      expect(initOptions.settings.payment.cardBrands).toEqual([
        "VISA",
        "MASTERCARD",
        "DISCOVER",
        "AMEX",
      ]);
    });

    it("does not overwrite settings.payment.cardBrands if defined", () => {
      const initOptions = VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
        },
        {
          settings: {
            payment: {
              cardBrands: ["CARD1", "CARD2"],
            },
          },
        }
      );

      expect(initOptions.settings.payment.cardBrands).toEqual([
        "CARD1",
        "CARD2",
      ]);
    });

    it("does not mutate incoming options", () => {
      const originalOptions = {
        settings: {
          dataLevel: "summary",
        },
      };

      VisaCheckout.prototype.createInitOptions.call(
        {
          _client: testContext.client,
          _transformCardTypes: VisaCheckout.prototype._transformCardTypes,
        },
        originalOptions
      );

      expect(originalOptions).toEqual({
        settings: {
          dataLevel: "summary",
        },
      });
    });
  });

  describe("tokenize", () => {
    it.each([["callid"], ["encKey"], ["encPaymentData"]])(
      "rejects with error when payment.%s is undefined",
      (optionKey) => {
        const options = {
          callid: "callId",
          encKey: "encKey",
          encPaymentdata: "encPaymentData",
        };

        delete options[optionKey];

        return testContext.visaCheckout.tokenize(options).catch((err) => {
          expect(err).toBeInstanceOf(BraintreeError);
          expect(err.code).toBe("VISA_CHECKOUT_PAYMENT_REQUIRED");
          expect(err.type).toBe("MERCHANT");
          expect(err.message).toBe(
            "tokenize requires callid, encKey, and encPaymentData."
          );
        });
      }
    );

    it("makes a request with the proper data", () => {
      const payment = {
        callid: "callid",
        encKey: "encKey",
        encPaymentData: "encPaymentData",
      };

      return testContext.visaCheckout.tokenize(payment).then(() => {
        expect(testContext.client.request).toHaveBeenCalledWith({
          method: "post",
          endpoint: "payment_methods/visa_checkout_cards",
          data: {
            _meta: { source: "visa-checkout" },
            visaCheckoutCard: {
              callId: "callid",
              encryptedKey: "encKey",
              encryptedPaymentData: "encPaymentData",
            },
          },
        });
      });
    });

    it("rejects with error if the request fails", () => {
      const originalError = new BraintreeError({
        type: "NETWORK",
        code: "CODE",
        message: "message",
      });

      testContext.client.request.mockRejectedValue(originalError);

      return testContext.visaCheckout
        .tokenize({
          callid: "callId",
          encKey: "encKey",
          encPaymentData: "encPaymentData",
        })
        .catch((err) => {
          expect(err.type).toBe(BraintreeError.types.NETWORK);
          expect(err.code).toBe("VISA_CHECKOUT_TOKENIZATION");
          expect(err.message).toBe(
            "A network error occurred when processing the Visa Checkout payment."
          );
          expect(err.details.originalError).toBe(originalError);
        });
    });

    it("resolves with a tokenized payload when success", () => {
      const tokenizedPayload = {
        foo: "baz",
      };

      testContext.client.request.mockResolvedValue({
        visaCheckoutCards: [tokenizedPayload],
      });

      return testContext.visaCheckout
        .tokenize({
          callid: "callId",
          encKey: "encKey",
          encPaymentData: "encPaymentData",
        })
        .then((payload) => {
          expect(payload.foo).toBe("baz");
        });
    });
  });

  describe("analytics", () => {
    describe("tokenize", () => {
      it("submits succeeded", () => {
        testContext.client.request.mockResolvedValue({
          visaCheckoutCards: [{}],
        });

        return VisaCheckout.prototype.tokenize
          .call(
            {
              _client: testContext.client,
            },
            {
              callid: "callId",
              encKey: "encKey",
              encPaymentData: "encPaymentData",
            }
          )
          .then(() => {
            expect(analytics.sendEvent).toHaveBeenCalledWith(
              testContext.client,
              "visacheckout.tokenize.succeeded"
            );
          });
      });

      it("submits failed", () => {
        testContext.client.request.mockRejectedValue(new Error());

        return VisaCheckout.prototype.tokenize
          .call(
            {
              _client: testContext.client,
            },
            {
              callid: "callId",
              encKey: "encKey",
              encPaymentData: "encPaymentData",
            }
          )
          .catch(() => {
            expect(analytics.sendEvent).toHaveBeenCalledWith(
              testContext.client,
              "visacheckout.tokenize.failed"
            );
          });
      });
    });
  });

  describe("teardown", () => {
    it("replaces all methods so error is thrown when methods are invoked", () => {
      const instance = testContext.visaCheckout;

      instance.teardown().then(() => {
        methods(VisaCheckout.prototype).forEach((method) => {
          try {
            instance[method]();
          } catch (err) {
            expect(err).toBeInstanceOf(BraintreeError);
            expect(err.type).toBe(BraintreeError.types.MERCHANT);
            expect(err.code).toBe("METHOD_CALLED_AFTER_TEARDOWN");
            expect(err.message).toBe(
              `${method} cannot be called after teardown.`
            );
          }
        });
      });
    });
  });
});


text:
int main()
  {

  // Member function is volatile, not const

  BOOST_MPL_ASSERT((AnVol<int (AnotherType::*)(AType *,short) const>));

  return 0;

  }


text:
<?php

/**
 * Generates a PHPUnit test file for unit tests.
 *
 * @package    sfPHPUnit2Plugin
 * @subpackage task
 *
 * @author     Frank Stelzer <dev@frankstelzer.de>
 */
class sfPHPUnitGenerateUnitTestTask extends sfPHPUnitGenerateBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('name', sfCommandArgument::REQUIRED, 'The unit test file name'),
    ));

    $this->addOptions(array(
      new sfCommandOption('overwrite', null, sfCommandOption::PARAMETER_NONE, 'Forces the task to overwrite any existing files'),
      new sfCommandOption('dir', null, sfCommandOption::PARAMETER_REQUIRED, 'A subfolder name, where the unit test should be saved to'),
      new sfCommandOption('template', null, sfCommandOption::PARAMETER_REQUIRED, 'A template name, without base dir (like unit) neither extension'),
      new sfCommandOption('plugin', null, sfCommandOption::PARAMETER_REQUIRED, 'A plugin name, without base dir (like sfPHPUnit)'),
    ));

    $this->namespace        = 'phpunit';
    $this->name             = 'generate-unit';
    $this->briefDescription = 'Generates a test case for unit tests';
    $this->detailedDescription = <<<EOF
The [phpunit:generate-unit|INFO] generates a test case for unit tests, which is lateron
executable with PHPUnit.

Call it with:

  [php symfony phpunit:generate-unit|INFO]
EOF;
  }

   /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $this->createBootstrap();

    if ($options['template'])
    {
      $templateName = $options['template'];
    }
    else
    {
      $templateName = 'unit_test';
    }

    $template = $this->getTemplate('unit/'.$templateName.'.tpl');

    $filename = $arguments['name'] . 'Test.php';
    $replacePairs = array(
      '{test_class}' => $arguments['name'],
    );

    $dir = isset($options['dir'])? '/../..' : '/..';

    $replacePairs['{path_to_bootstrap}'] = $dir.'/bootstrap/unit.php';

    if (isset($options['plugin']))
    {
      $replacePairs['{path_to_bootstrap}'] = $dir.'/../../../../test/phpunit/bootstrap/unit.php';
    }

    $rendered = $this->renderTemplate($template, $replacePairs);
    $this->saveFile($rendered, 'unit/'.($options['dir']? $options['dir'].'/' : '').$filename, $options);

    $optionsStr = '';
    if ($options['dir'])
    {
      $optionsStr .='--dir="'.$options['dir'].'" ';
    }

    $this->logSection('help', 'run this test with: ./symfony phpunit:test-unit '.$optionsStr.$arguments['name']);
  }
}


text:
var bgImageArray = ["1.jpg", "2.JPG", "3.JPG", "4.JPG"],
base = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-",
secs = 4;
bgImageArray.forEach(function(img){
    new Image().src = base + img;
    // caches images, avoiding white flash between background replacements
});

function backgroundSequence() {
	window.clearTimeout();
	var k = 0;
	for (i = 0; i < bgImageArray.length; i++) {
		setTimeout(function(){
			document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
			document.documentElement.style.backgroundSize ="cover";
		if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
		}, (secs * 1000) * i)
	}
}
backgroundSequence();


text:
package org.camunda.community.process_test_coverage.examples.junit5.platform8;

import io.camunda.zeebe.client.ZeebeClient;
import io.camunda.zeebe.client.api.response.ActivatedJob;
import io.camunda.zeebe.client.api.response.ProcessInstanceEvent;
import io.camunda.zeebe.process.test.api.ZeebeTestEngine;
import io.camunda.zeebe.process.test.extension.testcontainer.ZeebeProcessTest;
import org.camunda.community.process_test_coverage.junit5.platform8.ProcessEngineCoverageExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import static io.camunda.zeebe.process.test.assertions.BpmnAssert.assertThat;
import static io.camunda.zeebe.protocol.Protocol.USER_TASK_JOB_TYPE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ZeebeProcessTest
@ExtendWith(ProcessEngineCoverageExtension.class)
public class OrderProcessTest {

//    @RegisterExtension
//    public static ProcessEngineCoverageExtension extension = ProcessEngineCoverageExtension.builder().build();

    private ZeebeClient zeebe;
    private ZeebeTestEngine engine;

    @BeforeEach
    public void setup() {
        zeebe.newDeployResourceCommand()
                .addResourceFromClasspath("order-process.bpmn")
                .send()
                .join();
    }

    @Test
    public void shouldExecuteHappyPath() throws InterruptedException, TimeoutException {
        final ProcessInstanceEvent instance = this.startProcess();

        waitForUserTaskAndComplete("Task_ProcessOrder", Collections.singletonMap("orderOk", true));

        assertThat(instance).isWaitingAtElements("Task_DeliverOrder");

        waitForUserTaskAndComplete("Task_DeliverOrder", Collections.emptyMap());

        assertThat(instance)
                .hasPassedElement("Event_OrderProcessed")
                .isCompleted();
    }

    @Test
    public void shouldCancelOrder() throws Exception {
        final ProcessInstanceEvent instance = this.startProcess();

        waitForUserTaskAndComplete("Task_ProcessOrder", Collections.singletonMap("orderOk", false));

        assertThat(instance)
                .hasPassedElement("Event_OrderCancelled")
                .isCompleted();
    }

    private void waitForUserTaskAndComplete(String userTaskId, Map<String, Object> variables) throws InterruptedException, TimeoutException {
        // Let the workflow engine do whatever it needs to do
        engine.waitForIdleState(Duration.ofSeconds(10));

        // Now get all user tasks
        List<ActivatedJob> jobs = zeebe.newActivateJobsCommand().jobType(USER_TASK_JOB_TYPE).maxJobsToActivate(1).workerName("waitForUserTaskAndComplete").send().join().getJobs();

        // Should be only one
        assertTrue(jobs.size()>0, "Job for user task '" + userTaskId + "' does not exist");
        ActivatedJob userTaskJob = jobs.get(0);
        // Make sure it is the right one
        if (userTaskId!=null) {
            assertEquals(userTaskId, userTaskJob.getElementId());
        }

        // And complete it passing the variables
        if (variables!=null && variables.size()>0) {
            zeebe.newCompleteCommand(userTaskJob.getKey()).variables(variables).send().join();
        } else {
            zeebe.newCompleteCommand(userTaskJob.getKey()).send().join();
        }
        // Let the workflow engine do whatever it needs to do
        engine.waitForIdleState(Duration.ofSeconds(10));
    }

    private ProcessInstanceEvent startProcess() {
        return zeebe.newCreateInstanceCommand() //
                .bpmnProcessId("order-process")
                .latestVersion() //
                .send().join();
    }
}


text:
layout: leaf-node
title: "Design-based Research Strategies for Studying Situated Learning in a Multi-user Virtual Environment"
title-url: "http://rivercity5.activeworlds.com/rivercityproject/documents/dedeICLS04.pdf"
author: ["Chris Dede", "Brian Nelson", "Diane Jass Ketelhut", "Jody Clarke", "Cassie Bowman"]
groups: research-principles-and-methodologies
categories: design-based-research
topics: examples
summary: >
    Applied to a science curriculum, the research sought to understand if a Multi-User Virtual Environment (MUVE)
    could achieve acceptable results in a situated learning environment.
cite: >
    Dede, C., Nelson, B., Ketelhut, D. J., Clarke, J., & Bowman, C. (2004, June). Design-based research
    strategies for studying situated learning in a multi-user virtual environment. In Proceedings of the 6th international conference on Learning sciences (pp. 158-165). International Society of the Learning Sciences.
    Retrieved from http://rivercity5.activeworlds.com/rivercityproject/documents/dedeICLS04.pdf
pub-date: 2004-06-22
added-date: 2017-04-30
resource-type: pdf-document
---


text:
pub enum ErrorReason {
    /// The operations requires all inputs to have the same size,
    /// in most cases this means that the following must be true:
    /// `self.len()` == `argument.len()`
    InputMustHaveTheSameSize,

    /// The operations requires all inputs to have the same meta data.
    /// For a vector this means that the following must be true:
    /// `self.is_complex()` == `argument.is_complex()` &&
    /// `self.domain()` == `argument.domain()` &&
    /// `self.delta()`== `argument.domain()`;
    /// Consider to convert one of the inputs so that this condition is true.
    /// The necessary operations may include FFT/IFFT, complex/real conversion and resampling.
    InputMetaDataMustAgree,

    /// The operation requires the input to be complex.
    InputMustBeComplex,

    /// The operation requires the input to be real.
    InputMustBeReal,

    /// The operation requires the input to be in time domain.
    InputMustBeInTimeDomain,

    /// The operation requires the input to be in frequency domain.
    InputMustBeInFrequencyDomain,

    /// The arguments have an invalid length to perform the operation. The
    /// operations documentation should have more information about the requirements.
    /// Please open a defect if this isn't the case.
    InvalidArgumentLength,

    /// The operations is only valid if the data input contains half of a symmetric spectrum.
    /// The symmetry definition follows soon however more important is that the element at 0 Hz
    /// which happens to be the first vector element must be real. The error message is raised
    /// if this
    /// is violated, the rest of the definition is only listed here for completeness snce it can't
    /// be checked.
    /// The required symmetry for a vector is that for every point
    /// `vector[x].conj() == vector[-x]`(pseudocode)
    /// where `x` is the x-axis position relative to 0 Hz and `conj` is the complex conjugate.
    InputMustBeConjSymmetric,

    /// `self.points()` must be an odd number.
    InputMustHaveAnOddLength,

    /// The function passed as argument must be symmetric
    ArgumentFunctionMustBeSymmetric,

    /// The number of arguments passed into a combined operation methods doesn't match
    /// with the number of arguments specified previously via the `add_op` methods.
    InvalidNumberOfArgumentsForCombinedOp,

    /// The operation isn't specified for an empty vector.
    InputMustNotBeEmpty,

    /// Given input must have an even length.
    InputMustHaveAnEvenLength,

    /// The arguments would require that the type allocates larger memory. But the
    /// type can't do that.
    TypeCanNotResize,
}


text:
/**
 * Module dependencies.
 */
var express = require('express');
var ejs = require('ejs');
var flash = require('connect-flash');
var helpers = require('view-helpers');
var config = require('./config');

module.exports = function(app, passport) {

    console.log('Initializing Express');

    app.set('showStackError', true);

    //Prettify HTML
    app.locals.pretty = true;

    //Should be placed before express.static
    app.use(express.compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    //Setting the fav icon and static folder
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));

    //Don't use logger for test env
    if (process.env.NODE_ENV !== 'test') {
        app.use(express.logger('dev'));
    }

    //Set views path, template engine and default layout
    app.set('views', config.root + '/app/views');
    app.set('view engine', 'ejs');

//    app.set('view engine', 'html');
    app.set('view engine', 'jade');

    //Enable jsonp
    app.enable("jsonp callback");

    app.configure(function() {
        //cookieParser should be above session
        app.use(express.cookieParser());

        // request body parsing middleware should be above methodOverride
        app.use(express.urlencoded());
        app.use(express.json());
        app.use(express.methodOverride());

        //express/mongo session storage
        app.use(express.session({ secret: '$uper$ecret$e$$ionKey'}));

        //connect flash for flash messages
        app.use(flash());

        //dynamic helpers
        app.use(helpers(config.app.name));

        //use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        //routes should be at the last
        app.use(app.router);

        //Assume "not found" in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
        app.use(function(err, req, res, next) {
            //Treat as 404
            if (~err.message.indexOf('not found')) return next();

            //Log it
            console.error(err.stack);

            //Error page
            res.status(500).render('500', {
                error: err.stack
            });
        });

        //Assume 404 since no middleware responded
        app.use(function(req, res, next) {
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not found'
            });
        });

    });
};


text:
package org.sullivan;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 워드 데이터 파일(*.word)로부터 워드(한 단어에 관한 총괄 데이터)를 생성한다.
 */
public class SLWordLoader {

    /**
     * 워드의 세 레이어
     */
    private enum Layer {
        MODEL("model"), SUCCESS("success"), FAILURE("failure");

        private String label;

        Layer(String label) {
            this.label = label;
        }
    }

    /**
     * .word 파일은 XML 형식을 갖고 있다.
     * XML 파일을 파싱하기 위한 변수들
     */
    private DocumentBuilderFactory builderFactory;
    private DocumentBuilder builder;
    private Document document;

    /**
     * 파일을 처리할 패스
     */
    private File targetPath;

    /**
     * 워드 생성 이벤트를 받는 리스너들
     */
    private List<SLWordLoaderListener> listeners;

    public SLWordLoader() {

        builderFactory = DocumentBuilderFactory.newInstance();

        listeners = new ArrayList<>();

        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public void load(File wordDataFile, SLWordLoaderListener callback) {
        try {

            targetPath = wordDataFile.getAbsoluteFile().getParentFile();

            // XML 파일을 파싱한다.
            document = builder.parse(wordDataFile);
            document.getDocumentElement().normalize();

            NodeList childNodes = document.getChildNodes();

            for (int i = 0; i < childNodes.getLength(); i++) {

                Node childNode = childNodes.item(i);

                if (!childNode.getNodeName().equals("word"))
                    continue;

                SLWordEntry wordEntry = getWordEntry(childNode);

                if (wordEntry == null)
                    System.out.println("Invalid word data format.");

                generateWord(wordEntry, (SLWord word) -> {
                    callback.onWordGenerated(word);
                });
            }

        } catch (SAXException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * XML 노드로부터 워드 정보를 잃어온다.
     *
     * @param wordNode
     * @return
     */
    private SLWordEntry getWordEntry(Node wordNode) {

        NodeList childNodes = wordNode.getChildNodes();

        Node nameNode = null;
        Node modelNode = null;
        Node successNode = null;
        Node failureNode = null;

        for (int i = 0; i < childNodes.getLength(); i++) {

            Node childNode = childNodes.item(i);

            switch (childNode.getNodeName()) {
                case "name":
                    nameNode = childNode;
                    break;
                case "model":
                    modelNode = childNode;
                    break;
                case "success":
                    successNode = childNode;
                    break;
                case "failure":
                    failureNode = childNode;
                    break;
            }
        }

        // 필수 요소는 없으면 안 된다.
        if (wordNode == null || nameNode == null || modelNode == null || successNode == null || failureNode == null)
            return null;

        NamedNodeMap wordAttributes = wordNode.getAttributes();

        String name = nameNode.getTextContent();
        String version = getAttributeValue(wordAttributes, "version");
        String registeredDate = getAttributeValue(wordAttributes, "registered-registeredDate");

        // 워드의 음성 데이터를 읽어온다.
        List<SLNodeEntry> modelLayerNodeEntries = getNodeEntries(modelNode);
        List<SLNodeEntry> successLayerNodeEntries = getNodeEntries(successNode);
        List<SLNodeEntry> failureLayerNodeEntries = getNodeEntries(failureNode);

        SLWordEntry wordEntry = new SLWordEntry(name, modelLayerNodeEntries, successLayerNodeEntries, failureLayerNodeEntries);
        wordEntry.version = version;
        wordEntry.registeredDate = registeredDate;

        return wordEntry;
    }

    /**
     * XML 노드로부터 내부의 노드(데이터) 정보를 불러온다.
     *
     * @param layerNode
     * @return
     */
    private List<SLNodeEntry> getNodeEntries(Node layerNode) {

        List<SLNodeEntry> nodeEntries = new ArrayList<>();

        NodeList childNodes = layerNode.getChildNodes();

        for (int i = 0; i < childNodes.getLength(); i++) {

            Node childNode = childNodes.item(i);

            // 태그 이름이 형식에 맞는지 체크한다.
            if (!childNode.getNodeName().equals("data"))
                continue;

            NamedNodeMap attributes = childNode.getAttributes();

            // 값들을 읽어온다.
            String source = getAttributeValue(attributes, "source");
            String uid = getAttributeValue(attributes, "uid");
            int iuid = 0;
            String recorder = getAttributeValue(attributes, "recorder");
            String recorderSex = getAttributeValue(attributes, "recorder-sex");
            String recorderAge = getAttributeValue(attributes, "recorder-age");
            String recordedDate = getAttributeValue(attributes, "recorded-date");
            List<SLDescription> descriptions = new ArrayList<>();

            if (source.equals("unknown"))
                continue;
            if (uid.equals("unknown"))
                continue;
            if (!uid.matches("^-?\\d+$"))
                continue;
            iuid = Integer.parseInt(uid);

            NodeList descriptionNodes = childNode.getChildNodes();

            // 각 설명에 대하여
            for (int j = 0; j < descriptionNodes.getLength(); j++) {

                Node descriptionNode = descriptionNodes.item(j);
                if (!descriptionNode.getNodeName().equals("description"))
                    continue;

                NamedNodeMap descriptionAttributes = descriptionNode.getAttributes();

                // 값들을 읽어온다.
                String text = descriptionNode.getTextContent();
                String prominence = getAttributeValue(descriptionAttributes, "prominence");
                String rate = getAttributeValue(descriptionAttributes, "rate");
                String provider = getAttributeValue(descriptionAttributes, "provider");
                String registeredDate = getAttributeValue(descriptionAttributes, "registered-registeredDate");

                SLDescription.SLDescriptionInfo descriptionInfo = new SLDescription.SLDescriptionInfo();

                // 채워 넣는다.
                if (prominence.matches("^-?\\d+$"))
                    descriptionInfo.prominence = Integer.parseInt(prominence);
                if (rate.matches("^-?\\d+$"))
                    descriptionInfo.rate = Integer.parseInt(rate);
                descriptionInfo.provider = provider;
                descriptionInfo.registeredDate = registeredDate;

                SLDescription description = new SLDescription(text, descriptionInfo);

                // 리스트에 추가
                descriptions.add(description);
            }

            // 채워 넣는다.
            SLNodeEntry nodeEntry = new SLNodeEntry(source, iuid, descriptions);
            nodeEntry.recorder = recorder;
            nodeEntry.recorderAge = recorderAge;
            nodeEntry.recorderSex = recorderSex;
            nodeEntry.recordedDate = recordedDate;

            nodeEntries.add(nodeEntry);
        }

        return nodeEntries;
    }

    /**
     * 워드 정보를 바탕으로 워드를 생성한다.
     *
     * @param wordEntry
     * @return
     */
    private void generateWord(SLWordEntry wordEntry, SLWordListener callback) {

        // 워드 메타데이터
        SLWord.SLWordInfo wordInfo = new SLWord.SLWordInfo();
        wordInfo.version = wordEntry.version;
        wordInfo.registeredDate = wordEntry.registeredDate;

        final SLWord word = new SLWord(wordEntry.name, wordInfo);

        generateNodes(wordEntry.modelLayerNodeEntries, (List<SLNode> modelNodes) -> {
            word.layer.model.nodes = modelNodes;
            word.layer.model.analyzer.initialize();

            generateNodes(wordEntry.successLayerNodeEntries, (List<SLNode> successNodes) -> {
                word.layer.success.nodes = successNodes;
                word.layer.success.analyzer.initialize();

                generateNodes(wordEntry.failureLayerNodeEntries, (List<SLNode> failureNodes) -> {
                    word.layer.failure.nodes = failureNodes;
                    word.layer.failure.analyzer.initialize();

                    callback.onWordGenerated(word);
                });
            });
        });
    }

    /**
     * 노드 정보를 바탕으로 노드를 생성한다.
     *
     * @param nodeEntries
     * @return
     */
    private void generateNodes(List<SLNodeEntry> nodeEntries, SLNodesListener callback) {

        final int totalNodes = nodeEntries.size();

        final List<SLNode> nodes = new ArrayList<>();

        for (SLNodeEntry nodeEntry : nodeEntries) {

            File audioFile = new File(targetPath, nodeEntry.source);

            // 파일이 존재하지 않을 경우
            if (!audioFile.exists()) {
                System.out.println("Warning: Audio source '" + audioFile.getPath() + "' does not exist.");
                continue;
            }

            SLNode.SLNodeInfo nodeInfo = new SLNode.SLNodeInfo();
            nodeInfo.source = audioFile;
            nodeInfo.recorder = nodeEntry.recorder;
            nodeInfo.recorderAge = nodeEntry.recorderAge;
            nodeInfo.recorderSex = nodeEntry.recorderSex;
            nodeInfo.recordedDate = nodeEntry.recordedDate;

            // 최고 uid 업데이트
            SLNode.maximumUid = Math.max(SLNode.maximumUid, nodeEntry.uid);

            SLNode.fromFile(nodeEntry.uid, nodeInfo, audioFile, (SLNode node) -> {

                node.descriptions = nodeEntry.descriptions;

                nodes.add(node);

                if (totalNodes == nodes.size()) {

                    // null 노드를 제거한다.
                    nodes.removeAll(Collections.singleton(null));

                    callback.onNodesGenerated(nodes);
                }
            });
        }
    }

    /**
     * XML 어트리뷰트에서 속성을 구한다. 속성이 비었다면 'unknown'을 리턴한다.
     *
     * @param attributes
     * @param attributeName
     * @return
     */
    private String getAttributeValue(NamedNodeMap attributes, String attributeName) {

        Node attribute = attributes.getNamedItem(attributeName);

        if (attribute != null && attribute.getNodeValue().trim().length() > 0)
            return attribute.getNodeValue();
        else
            return "unknown";
    }

    /**
     * 워드를 구성하는데 필요한 정보들
     */
    private static class SLWordEntry {

        /**
         * 단어의 이름
         */
        public String name;

        /**
         * 단어 포멧의 버전
         */
        public String version;

        /**
         * 등록된 날
         */
        public String registeredDate;

        /**
         * 모델 레이어
         */
        public List<SLNodeEntry> modelLayerNodeEntries;

        /**
         * 성공 레이어
         */
        public List<SLNodeEntry> successLayerNodeEntries;

        /**
         * 실패 레이어
         */
        public List<SLNodeEntry> failureLayerNodeEntries;

        public SLWordEntry(String name, List<SLNodeEntry> modelLayerNodeEntries, List<SLNodeEntry> successLayerNodeEntries, List<SLNodeEntry> failureLayerNodeEntries) {
            this.name = name;
            this.modelLayerNodeEntries = modelLayerNodeEntries;
            this.successLayerNodeEntries = successLayerNodeEntries;
            this.failureLayerNodeEntries = failureLayerNodeEntries;
        }
    }

    /**
     * 노드를 구성하는데 필요한 정보들
     */
    private static class SLNodeEntry {

        /**
         * 이 노드의 Unique ID
         */
        public int uid;

        /**
         * 음성 데이터 소스
         */
        public String source;

        /**
         * 녹음자의 ID
         */
        public String recorder;

        /**
         * 녹음자의 나이
         */
        public String recorderAge;

        /**
         * 녹음자의 성별
         */
        public String recorderSex;

        /**
         * 녹음된 날짜
         */
        public String recordedDate;

        /**
         * 노드 Description
         */
        public List<SLDescription> descriptions;

        /**
         * 노드를 구성하는 데 필요한 필수 데이터를 입력받는다.
         *
         * @param source
         * @param uid
         * @param descriptions
         */
        public SLNodeEntry(String source, int uid, List<SLDescription> descriptions) {
            this.source = source;
            this.uid = uid;
            this.descriptions = descriptions;
        }
    }

    private interface SLNodesListener {
        void onNodesGenerated(List<SLNode> nodes);
    }

    private interface SLWordListener {
        void onWordGenerated(SLWord word);
    }

}


text:
package cfvbaibai.cardfantasy.engine.feature;

import java.util.List;

import cfvbaibai.cardfantasy.CardFantasyRuntimeException;
import cfvbaibai.cardfantasy.data.Feature;
import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.FeatureEffect;
import cfvbaibai.cardfantasy.engine.FeatureEffectType;
import cfvbaibai.cardfantasy.engine.FeatureInfo;
import cfvbaibai.cardfantasy.engine.FeatureResolver;
import cfvbaibai.cardfantasy.engine.Field;

public class HolyGuardFeature {
    public static void apply(FeatureResolver resolver, FeatureInfo featureInfo, CardInfo card) {
        if (card == null || card.isDead()) {
            throw new CardFantasyRuntimeException("card should not be null or dead!");
        }
        Feature feature = featureInfo.getFeature();
        int impact = feature.getImpact();
        resolver.getStage().getUI().useSkill(card, feature, true);
        Field field = card.getOwner().getField();
        List<CardInfo> allies = resolver.getAdjacentCards(field, card.getPosition());
        for (CardInfo ally : allies) {
            if (ally.getEffectsCausedBy(featureInfo).isEmpty()) {
                resolver.getStage().getUI().adjustHP(card, ally, impact, feature);
                ally.addEffect(new FeatureEffect(FeatureEffectType.MAXHP_CHANGE, featureInfo, impact, false));
            }
        }
    }

    public static void remove(FeatureResolver resolver, FeatureInfo feature, CardInfo card) {
        for (CardInfo ally : card.getOwner().getField().toList()) {
            if (ally == null) { continue; }
            List<FeatureEffect> effects = ally.getEffectsCausedBy(feature);
            for (FeatureEffect effect : effects) {
                resolver.getStage().getUI().loseAdjustHPEffect(ally, effect);
                ally.removeEffect(effect);
            }
        }
    }
}


text:
ES5Harness.registerTest( {
id: "15.2.3.3-2-1",

path: "TestCases/chapter15/15.2/15.2.3/15.2.3.3/15.2.3.3-2-1.js",

description: "Object.getOwnPropertyDescriptor returns undefined for undefined property name",

test: function testcase() {
    var o = {};
    var desc = Object.getOwnPropertyDescriptor(o, undefined);
    if (desc === undefined) {
      return true;
    }
 },

precondition: function prereq() {
  return fnExists(Object.getOwnPropertyDescriptor);
 }
});


text:
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y --no-install-recommends \
  g++ \
  make \
  ninja-build \
  file \
  curl \
  ca-certificates \
  python3 \
  git \
  cmake \
  sudo \
  gdb \
  xz-utils \
  g++-mipsel-linux-gnu \
  libssl-dev \
  pkg-config

COPY scripts/sccache.sh /scripts/
RUN sh /scripts/sccache.sh

COPY scripts/cmake.sh /scripts/
RUN /scripts/cmake.sh

ENV HOSTS=mipsel-unknown-linux-gnu

ENV RUST_CONFIGURE_ARGS --enable-extended --disable-docs
ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $HOSTS


text:
require 'spec_helper'

feature 'Project member activity', js: true do
  let(:user)            { create(:user) }
  let(:project)         { create(:project, :public, name: 'x', namespace: user.namespace) }

  before do
    project.team << [user, :master]
  end

  def visit_activities_and_wait_with_event(event_type)
    Event.create(project: project, author_id: user.id, action: event_type)
    visit activity_project_path(project)
    wait_for_requests
  end

  subject { page.find(".event-title").text }

  context 'when a user joins the project' do
    before do
      visit_activities_and_wait_with_event(Event::JOINED)
    end

    it { is_expected.to eq("#{user.name} joined project") }
  end

  context 'when a user leaves the project' do
    before do
      visit_activities_and_wait_with_event(Event::LEFT)
    end

    it { is_expected.to eq("#{user.name} left project") }
  end

  context 'when a users membership expires for the project' do
    before do
      visit_activities_and_wait_with_event(Event::EXPIRED)
    end

    it "presents the correct message" do
      message = "#{user.name} removed due to membership expiration from project"
      is_expected.to eq(message)
    end
  end
end


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

abstract class base_controller extends backup implements loggable {
    /**
     * @var \core\progress\base Progress reporting object.
     */
    protected $progress;

    /**
     * @var base_logger Logging chain object (moodle, inline, fs, db, syslog)
     */
    protected $logger;

    /**
     * Gets the progress reporter, which can be used to report progress within
     * the backup or restore process.
     *
     * @return \core\progress\base Progress reporting object
     */
    public function get_progress() {
        return $this->progress;
    }

    /**
     * Sets the progress reporter.
     *
     * @param \core\progress\base $progress Progress reporting object
     */
    public function set_progress(\core\progress\base $progress) {
        $this->progress = $progress;
    }

    /**
     * Gets first logger in logging chain.
     *
     * @return base_logger Logger
     */
    public function get_logger() {
        return $this->logger;
    }

    /**
     * Inserts a new logger at end of logging chain.
     *
     * @param base_logger $logger New logger to add
     */
    public function add_logger(base_logger $logger) {
        $existing = $this->logger;
        while ($existing->get_next()) {
            $existing = $existing->get_next();
        }
        $existing->set_next($logger);
    }

    /**
     * Logs data to the logger chain.
     *
     * @see loggable::log()
     */
    public function log($message, $level, $a = null, $depth = null, $display = false) {
        backup_helper::log($message, $level, $a, $depth, $display, $this->logger);
    }
}


text:
#include "core_attach_address_lookup.h"
#include "core_client_api.h"
#include "core_events.h"
#include "module.h"
#include "router_core_private.h"

#include "qpid/dispatch/address_lookup_utils.h"
#include "qpid/dispatch/ctools.h"
#include "qpid/dispatch/discriminator.h"

#include <stdio.h>

static uint64_t on_reply(qdr_core_t    *core,
                         qdrc_client_t *api_client,
                         void          *user_context,
                         void          *request_context,
                         qd_iterator_t *app_properties,
                         qd_iterator_t *body);

static void on_request_done(qdr_core_t    *core,
                            qdrc_client_t *api_client,
                            void          *user_context,
                            void          *request_context,
                            const char    *error);

typedef struct qcm_addr_lookup_request_t {
    DEQ_LINKS(struct qcm_addr_lookup_request_t);
    qdr_connection_t_sp  conn_sp;
    qdr_link_t_sp        link_sp;
    qd_direction_t       dir;
    qdr_terminus_t      *source;
    qdr_terminus_t      *target;
} qcm_addr_lookup_request_t;

DEQ_DECLARE(qcm_addr_lookup_request_t, qcm_addr_lookup_request_list_t);
ALLOC_DECLARE(qcm_addr_lookup_request_t);
ALLOC_DEFINE(qcm_addr_lookup_request_t);

typedef struct qcm_lookup_client_t {
    qdr_core_t                     *core;
    qdrc_event_subscription_t      *event_sub;
    qdr_connection_t               *edge_conn;
    uint32_t                        request_credit;
    bool                            client_api_active;
    qdrc_client_t                  *client_api;
    qcm_addr_lookup_request_list_t  pending_requests;
    qcm_addr_lookup_request_list_t  sent_requests;
} qcm_lookup_client_t;

static char* disambiguated_link_name(qdr_connection_info_t *conn, char *original)
{
    size_t olen = strlen(original);
    size_t clen = strlen(conn->container);
    char *name = (char*) qd_malloc(olen + clen + 2);
    memset(name, 0, olen + clen + 2);
    strcat(name, original);
    name[olen] = '@';
    strcat(name + olen + 1, conn->container);
    return name;
}

/**
 * Generate a temporary routable address for a destination connected to this
 * router node. Caller must free() return value when done.
 */
static char *qdr_generate_temp_addr(qdr_core_t *core)
{
    static const char edge_template[] = "amqp:/_edge/%s/temp.%s";
    static const char topo_template[] = "amqp:/_topo/%s/%s/temp.%s";
    const size_t      max_template    = 19;  // printable chars
    char discriminator[QD_DISCRIMINATOR_SIZE];

    qd_generate_discriminator(discriminator);
    size_t len = max_template + QD_DISCRIMINATOR_SIZE +
        strlen(core->router_id) + strlen(core->router_area) + 1;

    int rc;
    char *buffer = qd_malloc(len);
    if (core->router_mode == QD_ROUTER_MODE_EDGE) {
        rc = snprintf(buffer, len, edge_template, core->router_id, discriminator);
    } else {
        rc = snprintf(buffer, len, topo_template, core->router_area, core->router_id, discriminator);
    }
    (void)rc; assert(rc < len);
    return buffer;
}

/**
 * Generate a temporary mobile address for a producer connected to this
 * router node. Caller must free() return value when done.
 */
static char *qdr_generate_mobile_addr(qdr_core_t *core)
{
    static const char mobile_template[] = "amqp:/_$temp.%s";
    const size_t      max_template      = 13; // printable chars
    char discriminator[QD_DISCRIMINATOR_SIZE];

    qd_generate_discriminator(discriminator);
    size_t len = max_template + QD_DISCRIMINATOR_SIZE + 1;
    char *buffer = qd_malloc(len);
    int rc = snprintf(buffer, len, mobile_template, discriminator);
    (void)rc; assert(rc < len);
    return buffer;
}

/**
 * qdr_lookup_terminus_address_CT
 *
 * Lookup a terminus address in the route table and possibly create a new address
 * if no match is found.
 *
 * @param core Pointer to the core object
 * @param dir Direction of the link for the terminus
 * @param conn The connection over which the terminus was attached
 * @param terminus The terminus containing the addressing information to be looked up
 * @param create_if_not_found Iff true, return a pointer to a newly created address record
 * @param accept_dynamic Iff true, honor the dynamic flag by creating a dynamic address
 * @param [out] link_route True iff the lookup indicates that an attach should be routed
 * @param [out] unavailable True iff this address is blocked as unavailable
 * @param [out] core_endpoint True iff this address is bound to a core-internal endpoint
 * @param [out] fallback True iff this terminus has fallback capability
 * @return Pointer to an address record or 0 if none is found
 */
static qdr_address_t *qdr_lookup_terminus_address_CT(qdr_core_t       *core,
                                                     qd_direction_t    dir,
                                                     qdr_connection_t *conn,
                                                     qdr_terminus_t   *terminus,
                                                     bool              create_if_not_found,
                                                     bool              accept_dynamic,
                                                     bool             *link_route,
                                                     bool             *unavailable,
                                                     bool             *core_endpoint,
                                                     bool             *fallback)
{
    qdr_address_t *addr = 0;

    //
    // Unless expressly stated, link routing is not indicated for this terminus.
    //
    *link_route    = false;
    *unavailable   = false;
    *core_endpoint = false;
    *fallback      = false;

    if (qdr_terminus_is_dynamic(terminus)) {
        //
        // The terminus is dynamic.  Check to see if there is an address provided
        // in the dynamic node properties.  If so, look that address up as a link-routed
        // destination.
        //
        qd_iterator_t *dnp_address = qdr_terminus_dnp_address(terminus);
        if (dnp_address) {
            qd_iterator_reset_view(dnp_address, ITER_VIEW_ADDRESS_WITH_SPACE);
            if (conn->tenant_space)
                qd_iterator_annotate_space(dnp_address, conn->tenant_space, conn->tenant_space_len);
            qd_parse_tree_retrieve_match(core->link_route_tree[dir], dnp_address, (void**) &addr);

            if (addr && conn->tenant_space) {
                //
                // If this link is in a tenant space, translate the dnp address to
                // the fully-qualified view
                //
                qdr_terminus_set_dnp_address_iterator(terminus, dnp_address);
            }

            qd_iterator_free(dnp_address);
            *link_route = true;
            return addr;
        }

        //
        // The dynamic terminus has no address in the dynamic-node-propteries.  If we are
        // permitted to generate dynamic addresses, create a new address that is local to
        // this router and insert it into the address table with a hash index.
        //
        if (!accept_dynamic)
            return 0;

        bool generating = true;
        while (generating) {
            //
            // The address-generation process is performed in a loop in case the generated
            // address collides with a previously generated address (this should be _highly_
            // unlikely).
            //
            char *temp_addr = 0;
            if (dir == QD_OUTGOING)
                temp_addr = qdr_generate_temp_addr(core);
            else
                temp_addr = qdr_generate_mobile_addr(core);

            qd_iterator_t *temp_iter = qd_iterator_string(temp_addr, ITER_VIEW_ADDRESS_HASH);
            qd_hash_retrieve(core->addr_hash, temp_iter, (void**) &addr);
            if (!addr) {
                addr = qdr_address_CT(core, QD_TREATMENT_ANYCAST_BALANCED, 0);
                qd_hash_insert(core->addr_hash, temp_iter, addr, &addr->hash_handle);
                DEQ_INSERT_TAIL(core->addrs, addr);
                qdr_terminus_set_address(terminus, temp_addr);
                generating = false;
            }
            qd_iterator_free(temp_iter);
            free(temp_addr);
        }
        return addr;
    }

    //
    // If the terminus is anonymous, there is no address to look up.
    //
    if (qdr_terminus_is_anonymous(terminus))
        return 0;

    //
    // The terminus has a non-dynamic address that we need to look up.  First, look for
    // a link-route destination for the address.
    //
    qd_iterator_t *iter = qdr_terminus_get_address(terminus);
    qd_iterator_reset_view(iter, ITER_VIEW_ADDRESS_WITH_SPACE);
    if (conn->tenant_space)
        qd_iterator_annotate_space(iter, conn->tenant_space, conn->tenant_space_len);
    qd_parse_tree_retrieve_match(core->link_route_tree[dir], iter, (void**) &addr);
    if (addr) {
        *link_route = true;

        //
        // If this link is in a tenant space, translate the terminus address to
        // the fully-qualified view
        //
        if (conn->tenant_space) {
            qdr_terminus_set_address_iterator(terminus, iter);
        }
        return addr;
    }

    //
    // There was no match for a link-route destination, look for a message-route address.
    //
    int  in_phase  = 0;
    int  out_phase = 0;
    char addr_phase;
    int  priority  = -1;
    qd_address_treatment_t  treat       = core->qd->default_treatment;
    qdr_address_config_t   *addr_config = qdr_config_for_address_CT(core, conn, iter);

    if (addr_config) {
        in_phase  = addr_config->in_phase;
        out_phase = addr_config->out_phase;
        priority  = addr_config->priority;
        treat     = addr_config->treatment;
    }

    //
    // If the terminus has a waypoint capability, override the configured phases and use the waypoint phases.
    //
    int waypoint_ordinal = qdr_terminus_waypoint_capability(terminus);
    if (waypoint_ordinal > 0) {
        in_phase  = waypoint_ordinal;
        out_phase = waypoint_ordinal - 1;
    }

    //
    // Determine if this endpoint is acting as a fallback destination for the address.
    //
    *fallback = qdr_terminus_has_capability(terminus, QD_CAPABILITY_FALLBACK);
    bool edge_link = conn->role == QDR_ROLE_EDGE_CONNECTION;

    qd_iterator_reset_view(iter, ITER_VIEW_ADDRESS_HASH);
    qd_iterator_annotate_prefix(iter, '\0'); // Cancel previous override
    addr_phase = dir == QD_INCOMING ?
        (*fallback && edge_link ? QD_ITER_HASH_PHASE_FALLBACK : in_phase + '0') :
        (*fallback ? QD_ITER_HASH_PHASE_FALLBACK : out_phase + '0');
    qd_iterator_annotate_phase(iter, addr_phase);

    qd_hash_retrieve(core->addr_hash, iter, (void**) &addr);

    if (addr && addr->treatment == QD_TREATMENT_UNAVAILABLE)
        *unavailable = true;

    //
    // If the address is a router-class address, change treatment to closest.
    //
    qd_iterator_reset(iter);
    if (qd_iterator_octet(iter) == (unsigned char) QD_ITER_HASH_PREFIX_ROUTER) {
        treat = QD_TREATMENT_ANYCAST_CLOSEST;

        //
        // It is not valid for an outgoing link to have a router-class address.
        //
        if (dir == QD_OUTGOING)
            return 0;
    }

    if (!addr && create_if_not_found) {
        addr = qdr_address_CT(core, treat, addr_config);
        if (addr) {
            qd_iterator_reset(iter);
            qd_hash_insert(core->addr_hash, iter, addr, &addr->hash_handle);
            DEQ_INSERT_TAIL(core->addrs, addr);

            //
            // If this address is configured with a fallback, set up the
            // fallback address linkage.
            //
            if (!!addr_config && addr_config->fallback && !addr->fallback)
                qdr_setup_fallback_address_CT(core, addr);
        }

        if (!addr && treat == QD_TREATMENT_UNAVAILABLE)
            *unavailable = true;
    }

    if (!!addr && addr->core_endpoint != 0)
        *core_endpoint = true;

    if (addr)
        addr->priority = priority;
    return addr;
}

static void qdr_link_react_to_first_attach_CT(qdr_core_t       *core,
                                              qdr_connection_t *conn,
                                              qdr_address_t    *addr,
                                              qdr_link_t       *link,
                                              qd_direction_t    dir,
                                              qdr_terminus_t   *source,  // must free when done
                                              qdr_terminus_t   *target,  // must free when done
                                              bool              link_route,
                                              bool              unavailable,
                                              bool              core_endpoint,
                                              bool              fallback)
{
    link->fallback = fallback;

    if (core_endpoint) {
        qdrc_endpoint_do_bound_attach_CT(core, addr, link, source, target);
        source = target = 0;  // ownership passed to qdrc_endpoint_do_bound_attach_CT
    }
    else if (unavailable && qdr_terminus_is_coordinator(dir == QD_INCOMING ? target : source) && !addr) {
        qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_COORDINATOR_PRECONDITION_FAILED, true);
    }
    else if (unavailable) {
        qdr_link_outbound_detach_CT(core, link, qdr_error(QD_AMQP_COND_NOT_FOUND, "Node not found"), 0, true);
    }
    else if (!addr) {
        //
        // No route to this destination, reject the link
        //
        qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_NO_ROUTE_TO_DESTINATION, true);
    }
    else if (link_route) {
        //
        // This is a link-routed destination, forward the attach to the next hop
        //
        qdr_terminus_t *term = dir == QD_INCOMING ? target : source;
        if (qdr_terminus_survives_disconnect(term) && !core->qd->allow_resumable_link_route) {
            qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_INVALID_LINK_EXPIRATION, true);
        } else {
            if (conn->role != QDR_ROLE_INTER_ROUTER && conn->connection_info) {
                link->disambiguated_name = disambiguated_link_name(conn->connection_info, link->name);
            }
            bool success = qdr_forward_attach_CT(core, addr, link, source, target);
            if (success) {
                source = target = 0;  // ownership passed to qdr_forward_attach_CT
            } else {
                qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_NO_ROUTE_TO_DESTINATION, true);
            }
        }
    }
    else if (dir == QD_INCOMING && qdr_terminus_is_coordinator(target)) {
        //
        // This target terminus is a coordinator.
        // If we got here, it means that the coordinator link attach could not be link routed to a broker (or to the next router).
        // The router should reject this link because the router cannot coordinate transactions itself.
        //
        // The attach response should have a null target to indicate refusal and the immediately coming detach.
        //
        qdr_link_outbound_second_attach_CT(core, link, source, 0);
        source = 0;  // ownership passed to qdr_link_outbound_second_attach_CT

        //
        // Now, send back a detach with the error amqp:precondition-failed
        //
        qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_COORDINATOR_PRECONDITION_FAILED, true);
    } else {
        //
        // Associate the link with the address.  With this association, it will be unnecessary
        // to do an address lookup for deliveries that arrive on this link.
        //
        qdr_core_bind_address_link_CT(core, addr, link);
        qdr_link_outbound_second_attach_CT(core, link, source, target);
        source = target = 0;  // ownership passed to qdr_link_outbound_second_attach_CT

        //
        // Issue the initial credit only if one of the following
        // holds:
        // - there are destinations for the address
        // - the address is that of an exchange (no subscribers allowed)
        //
        if (dir == QD_INCOMING
            && (DEQ_SIZE(addr->subscriptions)
                || DEQ_SIZE(addr->rlinks)
                || qd_bitmask_cardinality(addr->rnodes)
                || !!addr->exchange
                || (!!addr->fallback
                    && (DEQ_SIZE(addr->fallback->subscriptions)
                        || DEQ_SIZE(addr->fallback->rlinks)
                        || qd_bitmask_cardinality(addr->fallback->rnodes))))) {
            qdr_link_issue_credit_CT(core, link, link->capacity, false);
        }

        //
        // If this link came through an edge connection, raise a link event to
        // herald that fact.
        //
        if (link->conn->role == QDR_ROLE_EDGE_CONNECTION)
            qdrc_event_link_raise(core, QDRC_EVENT_LINK_EDGE_DATA_ATTACHED, link);
    }

    if (source)
        qdr_terminus_free(source);
    if (target)
        qdr_terminus_free(target);
}

static void qcm_addr_lookup_local_search(qcm_lookup_client_t *client, qcm_addr_lookup_request_t *request)
{
    bool              link_route;
    bool              unavailable;
    bool              core_endpoint;
    bool              fallback;
    qdr_connection_t *conn = safe_deref_qdr_connection_t(request->conn_sp);
    qdr_link_t       *link = safe_deref_qdr_link_t(request->link_sp);

    if (conn == 0 || link == 0)
        return;

    qdr_terminus_t *term = request->dir == QD_INCOMING ? request->target : request->source;
    qdr_address_t  *addr = qdr_lookup_terminus_address_CT(client->core,
                                                          request->dir,
                                                          conn,
                                                          term,
                                                          true,
                                                          true,
                                                          &link_route,
                                                          &unavailable,
                                                          &core_endpoint,
                                                          &fallback);
    qdr_link_react_to_first_attach_CT(client->core,
                                      conn,
                                      addr,
                                      link,
                                      request->dir,
                                      request->source,
                                      request->target,
                                      link_route,
                                      unavailable,
                                      core_endpoint,
                                      fallback);
}

static void qcm_addr_lookup_process_pending_requests_CT(qcm_lookup_client_t *client)
{
    const uint32_t timeout = 3;
    int result;

    while (client->request_credit > 0 && DEQ_SIZE(client->pending_requests) > 0) {
        qcm_addr_lookup_request_t *request = DEQ_HEAD(client->pending_requests);
        DEQ_REMOVE_HEAD(client->pending_requests);

        do {
            qd_composed_field_t *props;
            qd_composed_field_t *body;
            qd_iterator_t       *iter = qdr_terminus_get_address(request->dir == QD_INCOMING ? request->target : request->source);

            if (iter) {
                result = qcm_link_route_lookup_request(iter, request->dir, &props, &body);
                if (result == 0) {
                    result = qdrc_client_request_CT(client->client_api, request, props, body, timeout, on_reply, 0, on_request_done);
                    if (result == 0) {
                        DEQ_INSERT_TAIL(client->sent_requests, request);
                        client->request_credit--;
                        break;
                    }

                    //
                    // TODO - set a timer (or use a timeout in the client API)
                    //

                    qd_compose_free(props);
                    qd_compose_free(body);
                }
            }

            //
            // If we get here, we failed to launch the asynchronous lookup.  Fall back to a local,
            // synchronous lookup.
            //
            qcm_addr_lookup_local_search(client, request);
            free_qcm_addr_lookup_request_t(request);
        } while (false);
    }
}

static bool qcm_terminus_has_local_link_route(qdr_core_t *core, qdr_connection_t *conn, qdr_terminus_t *terminus, qd_direction_t dir)
{
    qdr_address_t *addr;
    qd_iterator_t *iter = qd_iterator_dup(qdr_terminus_get_address(terminus));
    qd_iterator_reset_view(iter, ITER_VIEW_ADDRESS_WITH_SPACE);
    if (conn->tenant_space)
        qd_iterator_annotate_space(iter, conn->tenant_space, conn->tenant_space_len);
    qd_parse_tree_retrieve_match(core->link_route_tree[dir], iter, (void**) &addr);
    qd_iterator_free(iter);
    return addr && (DEQ_SIZE(addr->conns) > 0);
}

//================================================================================
// Address Lookup Handler
//================================================================================

static void qcm_addr_lookup_CT(void             *context,
                               qdr_connection_t *conn,
                               qdr_link_t       *link,
                               qd_direction_t    dir,
                               qdr_terminus_t   *source,
                               qdr_terminus_t   *target)
{
    qcm_lookup_client_t *client = (qcm_lookup_client_t*) context;
    bool                 link_route;
    bool                 unavailable;
    bool                 core_endpoint;
    bool                 fallback;
    qdr_terminus_t      *term = dir == QD_INCOMING ? target : source;

    if (client->core->router_mode == QD_ROUTER_MODE_EDGE
        && client->client_api_active
        && conn != client->edge_conn
        && qdr_terminus_get_address(term) != 0
        && !qcm_terminus_has_local_link_route(client->core, conn, term, dir)) {
        //
        // We are in edge mode, there is an active edge connection, the terminus has an address,
        // and there is no local link route for this address.  Set up the asynchronous lookup.
        //
        qcm_addr_lookup_request_t *request = new_qcm_addr_lookup_request_t();
        DEQ_ITEM_INIT(request);
        set_safe_ptr_qdr_connection_t(conn, &request->conn_sp);
        set_safe_ptr_qdr_link_t(link, &request->link_sp);
        request->dir    = dir;
        request->source = source;
        request->target = target;

        DEQ_INSERT_TAIL(client->pending_requests, request);
        qcm_addr_lookup_process_pending_requests_CT(client);
        return;
    }

    //
    // If this lookup doesn't meet the criteria for asynchronous action, perform the built-in, synchronous address lookup
    //
    qdr_address_t *addr = qdr_lookup_terminus_address_CT(client->core, dir, conn, term, true, true,
                                                         &link_route, &unavailable, &core_endpoint, &fallback);
    qdr_link_react_to_first_attach_CT(client->core, conn, addr, link, dir, source, target,
                                      link_route, unavailable, core_endpoint, fallback);
}

//================================================================================
// Core Client API Handlers
//================================================================================

static void on_state(qdr_core_t    *core,
                     qdrc_client_t *api_client,
                     void          *user_context,
                     bool           active)
{
    qcm_lookup_client_t *client = (qcm_lookup_client_t*) user_context;

    client->client_api_active = active;
    if (!active) {
        //
        // Client-API links are down, set our available credit to zero.
        //
        client->request_credit = 0;

        //
        // Locally process all pending requests
        //
        qcm_addr_lookup_request_t *request = DEQ_HEAD(client->pending_requests);
        while (request) {
            DEQ_REMOVE_HEAD(client->pending_requests);
            qcm_addr_lookup_local_search(client, request);
            free_qcm_addr_lookup_request_t(request);
            request = DEQ_HEAD(client->pending_requests);
        }
    }
}

static void on_flow(qdr_core_t    *core,
                    qdrc_client_t *api_client,
                    void          *user_context,
                    int            more_credit,
                    bool           drain)
{
    qcm_lookup_client_t *client = (qcm_lookup_client_t*) user_context;

    client->request_credit += more_credit;

    //
    // If we have positive credit, process any pending requests
    //
    if (client->request_credit > 0)
        qcm_addr_lookup_process_pending_requests_CT(client);

    if (drain)
        client->request_credit = 0;
}

static uint64_t on_reply(qdr_core_t    *core,
                         qdrc_client_t *api_client,
                         void          *user_context,
                         void          *request_context,
                         qd_iterator_t *app_properties,
                         qd_iterator_t *body)
{
    qcm_lookup_client_t         *client  = (qcm_lookup_client_t*) user_context;
    qcm_addr_lookup_request_t   *request = (qcm_addr_lookup_request_t*) request_context;
    qcm_address_lookup_status_t  status;
    bool                         is_link_route;
    bool                         has_destinations;

    qdr_connection_t *conn = safe_deref_qdr_connection_t(request->conn_sp);
    qdr_link_t       *link = safe_deref_qdr_link_t(request->link_sp);

    //
    // If the connection or link pointers are NULL, exit without processing
    // because either the connection or link has been freed while the
    // request was in-flight.
    //
    if (conn == 0 || link == 0) {
        qdr_terminus_free(request->source);
        qdr_terminus_free(request->target);
        qd_iterator_free(body);
        qd_iterator_free(app_properties);
        return 0;
    }

    status = qcm_link_route_lookup_decode(app_properties, body, &is_link_route, &has_destinations);
    if (status == QCM_ADDR_LOOKUP_OK) {
        //
        // The lookup decode is of a valid service response.
        //
        if (!is_link_route)
            //
            // The address is not for a link route.  Use the local search.
            //
            qcm_addr_lookup_local_search(client, request);

        else if (!has_destinations)
            //
            // The address is for a link route, but there are no destinations upstream.  Fail with no-route.
            //
            qdr_link_outbound_detach_CT(core, link, 0, QDR_CONDITION_NO_ROUTE_TO_DESTINATION, true);
        else
            //
            // The address is for a link route and there are destinations upstream.  Directly forward the attach.
            //
            qdr_forward_link_direct_CT(core, client->edge_conn, link, request->source, request->target, 0, 0);

    } else {
        //
        // The reply was not a valid server response.  Fall back to the local search.
        //
        qcm_addr_lookup_local_search(client, request);
    }

    qd_iterator_free(body);
    qd_iterator_free(app_properties);

    return 0;
}

static void on_request_done(qdr_core_t    *core,
                            qdrc_client_t *api_client,
                            void          *user_context,
                            void          *request_context,
                            const char    *error)
{
    qcm_lookup_client_t       *client  = (qcm_lookup_client_t*) user_context;
    qcm_addr_lookup_request_t *request = (qcm_addr_lookup_request_t*) request_context;

    if (error) {
        qcm_addr_lookup_local_search(client, request);
    }

    DEQ_REMOVE(client->sent_requests, request);
    free_qcm_addr_lookup_request_t(request);
}

//================================================================================
// Event Handlers
//================================================================================

static void on_conn_event(void             *context,
                          qdrc_event_t      event_type,
                          qdr_connection_t *conn)
{
    qcm_lookup_client_t *client = (qcm_lookup_client_t*) context;

    switch (event_type) {
    case QDRC_EVENT_CONN_EDGE_ESTABLISHED:
        client->edge_conn      = conn;
        client->request_credit = 0;

        //
        // Set up a Client API session on the edge connection.
        //
        qdr_terminus_t *target = qdr_terminus(0);
        qdr_terminus_set_address(target, QD_TERMINUS_ADDRESS_LOOKUP);
        client->client_api = qdrc_client_CT(client->core,
                                            client->edge_conn,
                                            target,
                                            250,
                                            client,
                                            on_state,
                                            on_flow);
        break;

    case QDRC_EVENT_CONN_EDGE_LOST:
        client->edge_conn      = 0;
        client->request_credit = 0;

        //
        // Remove the Client API session.
        //
        qdrc_client_free_CT(client->client_api);
        client->client_api = 0;
        break;

    default:
        assert(false);
        break;
    }
}

//================================================================================
// Module Handlers
//================================================================================

static bool qcm_addr_lookup_client_enable_CT(qdr_core_t *core)
{
    return true;
}

static void qcm_addr_lookup_client_init_CT(qdr_core_t *core, void **module_context)
{
    assert(core->addr_lookup_handler == 0);
    qcm_lookup_client_t *client = NEW(qcm_lookup_client_t);
    ZERO(client);

    client->core      = core;
    client->event_sub = qdrc_event_subscribe_CT(client->core,
                                                QDRC_EVENT_CONN_EDGE_ESTABLISHED | QDRC_EVENT_CONN_EDGE_LOST,
                                                on_conn_event, 0, 0, 0,
                                                client);

    core->addr_lookup_handler = qcm_addr_lookup_CT;
    core->addr_lookup_context = client;
    *module_context           = client;
}

static void qcm_addr_lookup_client_final_CT(void *module_context)
{
    qcm_lookup_client_t *client = (qcm_lookup_client_t*) module_context;
    qdrc_event_unsubscribe_CT(client->core, client->event_sub);
    client->core->addr_lookup_handler = 0;
    qdrc_client_free_CT(client->client_api);
    free(client);
}

QDR_CORE_MODULE_DECLARE("address_lookup_client", qcm_addr_lookup_client_enable_CT, qcm_addr_lookup_client_init_CT, qcm_addr_lookup_client_final_CT)


text:
/**
 * @brief Front End Module control for the nRF 802.15.4 radio driver.
 *
 */

#ifndef NRF_FEM_CONTROL_API_H_
#define NRF_FEM_CONTROL_API_H_

#include <stdint.h>
#include <stdbool.h>

#include "hal/nrf_ppi.h"
#include "hal/nrf_timer.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @section Resource configuration.
 */

/** Default Power Amplifier pin. */
#define NRF_FEM_CONTROL_DEFAULT_PA_PIN                      26

/** Default Low Noise Amplifier pin. */
#define NRF_FEM_CONTROL_DEFAULT_LNA_PIN                     27

/** Default PPI channel for pin setting. */
#define NRF_FEM_CONTROL_DEFAULT_SET_PPI_CHANNEL             18

/** Default PPI channel for pin clearing. */
#define NRF_FEM_CONTROL_DEFAULT_CLR_PPI_CHANNEL             19

/** Default GPIOTE channel for FEM control. */
#define NRF_FEM_CONTROL_DEFAULT_LNA_GPIOTE_CHANNEL          6

/** Default GPIOTE channel for FEM control. */
#define NRF_FEM_CONTROL_DEFAULT_PA_GPIOTE_CHANNEL           7

#if ENABLE_FEM

/**
 * @brief Configuration parameters for the PA and LNA.
 */
typedef struct
{
     uint8_t enable :1;         /**< Enable toggling for this amplifier */
     uint8_t active_high :1;    /**< Set the pin to be active high */
     uint8_t gpio_pin :6;       /**< The GPIO pin to toggle for this amplifier */
} nrf_fem_control_pa_lna_cfg_t;

/**
 * @brief PA & LNA GPIO toggle configuration
 *
 * This option configures the nRF 802.15.4 radio driver to toggle pins when the radio
 * is active for use with a power amplifier and/or a low noise amplifier.
 *
 * Toggling the pins is achieved by using two PPI channels and a GPIOTE channel. The hardware channel IDs are provided
 * by the application and should be regarded as reserved as long as any PA/LNA toggling is enabled.
 *
 * @note Changing this configuration while the radio is in use may have undefined
 *       consequences and must be avoided by the application.
 */
typedef struct
{
    nrf_fem_control_pa_lna_cfg_t pa_cfg;            /**< Power Amplifier configuration */
    nrf_fem_control_pa_lna_cfg_t lna_cfg;           /**< Low Noise Amplifier configuration */
    uint8_t                      pa_gpiote_ch_id;   /**< GPIOTE channel used for Power Amplifier pin toggling */
    uint8_t                      lna_gpiote_ch_id;  /**< GPIOTE channel used for Low Noise Amplifier pin toggling */
    uint8_t                      ppi_ch_id_set;     /**< PPI channel used for radio Power Amplifier and Low Noise Amplifier pins setting */
    uint8_t                      ppi_ch_id_clr;     /**< PPI channel used for radio pin clearing */
} nrf_fem_control_cfg_t;

/**
 * @brief Hardware pins controlled by the Front End Module.
 */
typedef enum
{
    NRF_FEM_CONTROL_PA_PIN,
    NRF_FEM_CONTROL_LNA_PIN,
    NRF_FEM_CONTROL_ANY_PIN,
} nrf_fem_control_pin_t;

/**@brief Set PA & LNA GPIO toggle configuration.
 *
 * @note This function shall not be called when radio is in use.
 *
 * @param[in] p_cfg A pointer to the PA & LNA GPIO toggle configuration.
 *
 */
void nrf_fem_control_cfg_set(const nrf_fem_control_cfg_t * p_cfg);

/**@brief Get PA & LNA GPIO toggle configuration.
 *
 * @param[out] p_cfg A pointer to the structure for the PA & LNA GPIO toggle configuration.
 *
 */
void nrf_fem_control_cfg_get(nrf_fem_control_cfg_t * p_cfg);

/**@brief Activate FEM controller.
 *
 * This function should be called when radio wakes up.
 */
void nrf_fem_control_activate(void);

/**@brief Deactivate FEM controller.
 *
 * This function should be called when radio goes to sleep.
 */
void nrf_fem_control_deactivate(void);

/**@brief Configure PPI to activate one of the Front End Module pins on an appropriate timer event.
 *
 * @param[in] pin              The Front End Module controlled pin to be connected to the PPI.
 * @param[in] timer_cc_channel Timer CC channel that triggers the @p pin activation through the PPI.
 *
 */
void nrf_fem_control_ppi_enable(nrf_fem_control_pin_t pin, nrf_timer_cc_channel_t timer_cc_channel);

/**@brief Clear PPI configuration used to activate one of Front End Module pins.
 *
 * @param[in] pin              The Front End Module controlled pin to be disconnected from the PPI.
 *
 */
void nrf_fem_control_ppi_disable(nrf_fem_control_pin_t pin);

/**@brief Calculate target time for a timer, which activates one of the Front End Module pins.
 *
 * @param[in] pin The Front End Module controlled pin to be activated.
 *
 * @return    @p pin activation delay in microseconds.
 *
 */
uint32_t nrf_fem_control_delay_get(nrf_fem_control_pin_t pin);

/**@brief Clear the Power Amplifier and the Low Noise Amplifier pins immediately.
 *
 */
void nrf_fem_control_pin_clear(void);

/**@brief Configure and set a timer for one of the Front End Module pins activation.
 *
 * @param[in] pin              The Front End Module controlled pin to be activated.
 * @param[in] timer_cc_channel Timer CC channel to set.
 * @param[in] short_mask       Mask of timer shortcuts to be enabled.
 *
 */
void nrf_fem_control_timer_set(nrf_fem_control_pin_t  pin,
                               nrf_timer_cc_channel_t timer_cc_channel,
                               nrf_timer_short_mask_t short_mask);

/**@brief Clear timer configuration after one of the Front End Module pins deactivation.
 *
 * @param[in] pin              The Front End Module controlled pin that was deactivated.
 * @param[in] short_mask       Mask of timer shortcuts to be disabled.
 *
 */
void nrf_fem_control_timer_reset(nrf_fem_control_pin_t pin, nrf_timer_short_mask_t short_mask);

/**@brief Setup a PPI fork task necessary for one of the Front End Module pins.
 *
 * @param[in] pin              The Front End Module controlled pin that was deactivated.
 * @param[in] ppi_channel      PPI channel to connect the fork task to.
 *
 */
void nrf_fem_control_ppi_fork_setup(nrf_fem_control_pin_t pin,
                                    nrf_ppi_channel_t     ppi_channel,
                                    uint32_t              task_addr);

/**@brief Setup a PPI task necessary for one of the Front End Module pins.
 *
 * @param[in] pin              The Front End Module controlled pin that was deactivated.
 * @param[in] ppi_channel      PPI channel to connect the task to.
 * @param[in] event_addr       Address of the event to be connected to the PPI.
 * @param[in] task_addr        Address of the task to be connected to the PPI.
 *
 */
void nrf_fem_control_ppi_task_setup(nrf_fem_control_pin_t pin,
                                    nrf_ppi_channel_t     ppi_channel,
                                    uint32_t              event_addr,
                                    uint32_t              task_addr);

/**@brief Clear a PPI fork task configuration for one of the Front End Module pins.
 *
 * @param[in] pin              The Front End Module controlled pin that was deactivated.
 * @param[in] ppi_channel      PPI channel to disconnect the fork task from.
 *
 */
void nrf_fem_control_ppi_fork_clear(nrf_fem_control_pin_t pin, nrf_ppi_channel_t ppi_channel);

/**@brief Setup PPI task and fork that set or clear Front End Module pins on a given event.
 *
 * @param[in] ppi_channel      PPI channel to connect the task and fork to.
 * @param[in] event_addr       Address of the event to be connected to the PPI.
 * @param[in] lna_pin_set      If true, the Low Noise Amplifier pin will be set on the event @p event_addr.
 *                             Otherwise, it will be cleared.
 * @param[in] pa_pin_set       If true, the Power Amplifier pin will be set on the event @p event_addr.
 *                             Otherwise, it will be cleared.
 *
 */
void nrf_fem_control_ppi_pin_task_setup(nrf_ppi_channel_t ppi_channel,
                                        uint32_t          event_addr,
                                        bool              lna_pin_set,
                                        bool              pa_pin_set);

#else  // ENABLE_FEM

#define nrf_fem_control_cfg_set(...)
#define nrf_fem_control_cfg_get(...)
#define nrf_fem_control_activate(...)
#define nrf_fem_control_deactivate(...)
#define nrf_fem_control_ppi_enable(...)
#define nrf_fem_control_ppi_disable(...)
#define nrf_fem_control_delay_get(...)   1
#define nrf_fem_control_pin_clear(...)
#define nrf_fem_control_timer_set(...)
#define nrf_fem_control_timer_reset(...)
#define nrf_fem_control_ppi_fork_setup(...)
#define nrf_fem_control_ppi_task_setup(...)
#define nrf_fem_control_ppi_task_and_fork_setup(...)
#define nrf_fem_control_ppi_fork_clear(...)
#define nrf_fem_control_ppi_pin_task_setup(...)

#endif // ENABLE_FEM

#ifdef __cplusplus
}
#endif

#endif /* NRF_FEM_CONTROL_API_H_ */


text:
class DummyModel
	include MotionModel::Model
	include MotionModel::ArrayModelAdapter
	include MeteorMotion::Adapters::MotionModel

	# Make sure to define :id as String so MotionModel does not create a default int
	#
	columns :id => :string,
					:a => :int,
					:b => :int
end

describe MeteorMotion::Collections::MotionModel do
	describe 'Creation' do
		it 'creates a collection with a compatible class' do
			coll = MeteorMotion::Collections::MotionModel.new(DummyModel)
			coll.should.not.be.equal nil
			coll.name.should.be.equal 'dummymodel'
		end

		it 'sets a different name when it is provided' do
			coll = MeteorMotion::Collections::MotionModel.new(DummyModel, 'dums')
			coll.should.not.be.equal nil
			coll.name.should.be.equal 'dums'
		end
	end

	describe 'CRUD tasks' do

		before do
			@client = MeteorMotion::Client.new
			@client.connect
			@coll = MeteorMotion::Collections::MotionModel.new(DummyModel)
		end

		it 'adds an object to the collection and finds it' do
			@coll.add('abc', {a: 1, b:2})
			@coll.find('abc').should.not.be.equal nil
		end

		it 'adds the correct fields to the object' do
			@coll.add('abc', {a: 1, b:2})

			@coll.find('abc').a.should.be.equal 1
			@coll.find('abc').b.should.be.equal 2
		end

		it 'updates an objects fields' do
			@coll.add('abc', {a: 1, b:2})
			@coll.find('abc').a.should.be.equal 1

			@coll.update('abc', {a: 2}, nil)
			@coll.find('abc').a.should.be.equal 2
		end

		it 'removes an object from the collection' do
			@coll.add('abc', {a: 1, b:2})

			wait 1.0 do
				@coll.remove('abc')
				@coll.find('abc').should.be.equal nil
			end
		end

	end

end