text:
namespace Erpiko {

SCENARIO("Basic certificate test") {
  GIVEN("A new certificate") {
    Certificate* cert = new Certificate();
    THEN("There is nothing wrong") {
      REQUIRE_FALSE(cert == nullptr);
      delete(cert);
      cert = nullptr;
      REQUIRE(cert == nullptr);
    }
  }
}

SCENARIO("Import certificate from DER test") {
  GIVEN("A DER certificate") {
    DataSource* src = DataSource::fromFile("assets/crt1.der");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      Certificate* cert = Certificate::fromDer(v);
      delete(src);
      THEN("There is nothing wrong") {
        REQUIRE_FALSE(cert == nullptr);
        delete(cert);
        cert = nullptr;
        REQUIRE(cert == nullptr);
      }
    }
  }

  GIVEN("A DER certificate") {
    DataSource* src = DataSource::fromFile("assets/crt1.der");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      Certificate* cert = Certificate::fromDer(v);
      delete(src);
      THEN("There cert can be queried") {
        REQUIRE("160324131946Z" == cert->notAfter().toString());
        REQUIRE("150325131946Z" == cert->notBefore().toString());
        REQUIRE("1003" == cert->serialNumber().toHexString());
        const Identity& subjectIdentity = cert->subjectIdentity();
        const Identity& issuerIdentity = cert->issuerIdentity();

        REQUIRE(subjectIdentity.get("commonName") == "soda.id");
        REQUIRE(subjectIdentity.get("countryName") == "ID");
        REQUIRE(subjectIdentity.get("organizationalUnitName") == "Es Soda");
        REQUIRE(subjectIdentity.get("organizationName") == "Soda Susu");
        REQUIRE(subjectIdentity.get("stateOrProvinceName") == "Bogor");
        REQUIRE(subjectIdentity.get("emailAddress") == "info@soda.id");

        REQUIRE(issuerIdentity.get("commonName") == "sertifikat.id");
        REQUIRE(issuerIdentity.get("countryName") == "ID");
        REQUIRE(issuerIdentity.get("organizationalUnitName") == "Unit Penerbitan Sertifikat");
        REQUIRE(issuerIdentity.get("organizationName") == "Badan Otoritas Sertifikat Digital");
        REQUIRE(issuerIdentity.get("stateOrProvinceName") == "DKI Jakarta");
        REQUIRE(issuerIdentity.get("localityName") == "Jakarta Pusat");
        REQUIRE(issuerIdentity.get("emailAddress") == "cert@sertifikat.id");

        int numExts = cert->extensions().size();
        REQUIRE(numExts > 0);
        int allExtsInspected = 0;
        for (int i = 0; i < numExts; i ++) {
          const CertificateExtension* ext = cert->extensions().at(i);
          if (ext->objectId().toString() == "2.5.29.14") {
            const CertificateSubjectKeyIdentifierExtension& skid = dynamic_cast<const CertificateSubjectKeyIdentifierExtension&>(*ext);
            auto s = Utils::hexString(skid.value());
            REQUIRE(s == "47da867838ffc5bd44428fb0e18ad051051b27c3");
            REQUIRE(skid.critical() == false);
            allExtsInspected++;
          }
          else if (ext->objectId().toString() == "2.5.29.19") {
            const CertificateBasicConstraintsExtension& skid = dynamic_cast<const CertificateBasicConstraintsExtension&>(*ext);
            REQUIRE(skid.isCa() == false);
            REQUIRE(skid.pathLengthConstraints() == 0);
            allExtsInspected++;
          }

        }
        REQUIRE(allExtsInspected == 1);

      }
    }
  }
}

SCENARIO("Get the CRL uri from cert") {
  GIVEN("A DER certificate with CRL distribution point") {
    DataSource* src = DataSource::fromFile("assets/cert-with-crl.der");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      Certificate* cert = Certificate::fromDer(v);
      std::string uri = cert->crlDistPoint();
      REQUIRE(uri == "http://ca.tnisiberlab.xyz/ejbca/publicweb/webdist/certdist?cmd=crl&issuer=CN=TNISiberLabCA,O=TNI%20Siber%20Lab,C=ID");
    }
  }
}

SCENARIO("Import certificate from PEM test") {
  GIVEN("A PEM certificate") {
    DataSource* src = DataSource::fromFile("assets/cert.pem");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      std::string pem(v.begin(),v.end());
      Certificate* cert = Certificate::fromPem(pem);
      delete(src);
      THEN("There is nothing wrong") {
        REQUIRE_FALSE(cert == nullptr);
        delete(cert);
        cert = nullptr;
        REQUIRE(cert == nullptr);
      }
    }
  }

  GIVEN("A PEM certificate") {
    DataSource* src = DataSource::fromFile("assets/cert.pem");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      std::string pem(v.begin(),v.end());
      Certificate* cert = Certificate::fromPem(pem);
      delete(src);
      THEN("There cert can be queried") {
        REQUIRE("170501012102Z" == cert->notAfter().toString());
        REQUIRE("160501012102Z" == cert->notBefore().toString());
        REQUIRE("F1B40E1F1590B6A4" == cert->serialNumber().toHexString());
        const Identity& subjectIdentity = cert->subjectIdentity();
        const Identity& issuerIdentity = cert->issuerIdentity();

        REQUIRE(subjectIdentity.get("commonName") == "www.endpoint.com");

        REQUIRE(issuerIdentity.get("commonName") == "www.endpoint.com");
      }
    }
  }
}

SCENARIO("Export certificate to DER test") {
  GIVEN("A DER certificate") {
    DataSource* src = DataSource::fromFile("assets/crt1.der");
    THEN("The file is opened") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      Certificate* cert = Certificate::fromDer(v);
      delete(src);
      THEN("Export it again to DER") {
        auto der = cert->toDer();
        REQUIRE(der.size() > 0);
        THEN("Import again") {
          auto cert2 = Certificate::fromDer(der);
          REQUIRE_FALSE(cert2 == nullptr);
          THEN("Both certs must be the same") {
            REQUIRE(cert2->serialNumber() == cert->serialNumber());
          }
        }
      }
    }
  }
}

SCENARIO("Export certificate to PEM test") {
  GIVEN("A new certificate") {
    DataSource* src = DataSource::fromFile("assets/crt1.der");
    REQUIRE_FALSE(src == nullptr);
    auto v = src->readAll();
    Certificate* cert = Certificate::fromDer(v);
    delete(src);
    THEN("Export to PEM") {
      REQUIRE_FALSE(cert == nullptr);
      auto pem = cert->toPem();
      THEN("Import again") {
        Certificate* cert = Certificate::fromPem(pem);
        REQUIRE_FALSE(cert == nullptr);
      }
    }
  }
}

} //namespace Erpiko


text:
<!DOCTYPE html>

	<title>apple</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

cherry

A cherry is the fruit of many plants of the genus Prunus, and is a fleshy drupe (stone fruit).

The cherry fruits of commerce are usually obtained from a limited number of species such as cultivars of the sweet cherry, Prunus avium.

The name 'cherry' also refers to the cherry tree, and is sometimes applied to almonds and visually similar flowering trees in the genus Prunus, as in "ornamental cherry", "cherry blossom", etc.

Wild Cherry may refer to any of the cherry species growing outside of cultivation, although Prunus avium is often referred to specifically by the name "wild cherry" in the British Isles.

Many cherries are members of the subgenus Cerasus, which is distinguished by having the flowers in small corymbs of several together (not singly, nor in racemes), and by having smooth fruit with only a weak groove or none along one side.

The subgenus is native to the temperate regions of the Northern Hemisphere, with two species in America, three in Europe, and the remainder in Asia.

Other cherry fruits are members of subgenus Padus. Cherry trees with low exposure to light tend to have a bigger leaf size so they can intercept all light possible.

Cherry trees with high exposure to light tend to have thicker leaves to concentrate light and have a higher photosynthetic capacity.

Most eating cherries are derived from either Prunus avium, the sweet cherry (also called the wild cherry), or from Prunus cerasus, the sour cherry.

Reference
https://en.wikipedia.org/wiki/Cherry

Comment Space

This is comment description/This is comment description/This is comment description/This is comment description

		This is comment description/This is comment description/This is comment description/This is comment description

		previous page

		next page

redpajama_set_name: RedPajamaGithub


text:
namespace mojo {
namespace test {
namespace {

using Handle_Data = mojo::internal::Handle_Data;

const void* ToPtr(uintptr_t ptr) {
  return reinterpret_cast<const void*>(ptr);
}

#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
TEST(BoundsCheckerTest, ConstructorRangeOverflow) {
  {
    // Test memory range overflow.
    internal::BoundsChecker checker(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 5000, 0);

    EXPECT_FALSE(checker.IsValidRange(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 1));
    EXPECT_FALSE(checker.ClaimMemory(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 1));
  }

  if (sizeof(size_t) > sizeof(uint32_t)) {
    // Test handle index range overflow.
    size_t num_handles =
        static_cast<size_t>(std::numeric_limits<uint32_t>::max()) + 5;
    internal::BoundsChecker checker(ToPtr(0), 0, num_handles);

    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(0)));
    EXPECT_FALSE(checker.ClaimHandle(
        Handle_Data(std::numeric_limits<uint32_t>::max() - 1)));

    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(internal::kEncodedInvalidHandleValue)));
  }
}
#endif

TEST(BoundsCheckerTest, IsValidRange) {
  {
    internal::BoundsChecker checker(ToPtr(1234), 100, 0);

    // Basics.
    EXPECT_FALSE(checker.IsValidRange(ToPtr(100), 5));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1230), 50));
    EXPECT_TRUE(checker.IsValidRange(ToPtr(1234), 5));
    EXPECT_TRUE(checker.IsValidRange(ToPtr(1240), 50));
    EXPECT_TRUE(checker.IsValidRange(ToPtr(1234), 100));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 101));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1240), 100));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1333), 5));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(2234), 5));

    // ClaimMemory() updates the valid range.
    EXPECT_TRUE(checker.ClaimMemory(ToPtr(1254), 10));

    EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 1));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1254), 10));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1263), 1));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1263), 10));
    EXPECT_TRUE(checker.IsValidRange(ToPtr(1264), 10));
    EXPECT_TRUE(checker.IsValidRange(ToPtr(1264), 70));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1264), 71));
  }

  {
    internal::BoundsChecker checker(ToPtr(1234), 100, 0);
    // Should return false for empty ranges.
    EXPECT_FALSE(checker.IsValidRange(ToPtr(0), 0));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1200), 0));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 0));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1240), 0));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(2234), 0));
  }

  {
    // The valid memory range is empty.
    internal::BoundsChecker checker(ToPtr(1234), 0, 0);

    EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 1));
    EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 0));
  }

  {
    internal::BoundsChecker checker(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 2000), 1000, 0);

    // Test overflow.
    EXPECT_FALSE(checker.IsValidRange(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 1500), 4000));
    EXPECT_FALSE(checker.IsValidRange(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 1500),
        std::numeric_limits<uint32_t>::max()));

    // This should be fine.
    EXPECT_TRUE(checker.IsValidRange(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 1500), 200));
  }
}

TEST(BoundsCheckerTest, ClaimHandle) {
  {
    internal::BoundsChecker checker(ToPtr(0), 0, 10);

    // Basics.
    EXPECT_TRUE(checker.ClaimHandle(Handle_Data(0)));
    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(0)));

    EXPECT_TRUE(checker.ClaimHandle(Handle_Data(9)));
    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(10)));

    // Should fail because it is smaller than the max index that has been
    // claimed.
    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(8)));

    // Should return true for invalid handle.
    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(internal::kEncodedInvalidHandleValue)));
    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(internal::kEncodedInvalidHandleValue)));
  }

  {
    // No handle to claim.
    internal::BoundsChecker checker(ToPtr(0), 0, 0);

    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(0)));

    // Should still return true for invalid handle.
    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(internal::kEncodedInvalidHandleValue)));
  }

  {
    // Test the case that |num_handles| is the same value as
    // |internal::kEncodedInvalidHandleValue|.
    EXPECT_EQ(internal::kEncodedInvalidHandleValue,
              std::numeric_limits<uint32_t>::max());
    internal::BoundsChecker checker(
        ToPtr(0), 0, std::numeric_limits<uint32_t>::max());

    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(std::numeric_limits<uint32_t>::max() - 1)));
    EXPECT_FALSE(checker.ClaimHandle(
        Handle_Data(std::numeric_limits<uint32_t>::max() - 1)));
    EXPECT_FALSE(checker.ClaimHandle(Handle_Data(0)));

    // Should still return true for invalid handle.
    EXPECT_TRUE(checker.ClaimHandle(
        Handle_Data(internal::kEncodedInvalidHandleValue)));
  }
}

TEST(BoundsCheckerTest, ClaimMemory) {
  {
    internal::BoundsChecker checker(ToPtr(1000), 2000, 0);

    // Basics.
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(500), 100));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(800), 300));
    EXPECT_TRUE(checker.ClaimMemory(ToPtr(1000), 100));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(1099), 100));
    EXPECT_TRUE(checker.ClaimMemory(ToPtr(1100), 200));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(2000), 1001));
    EXPECT_TRUE(checker.ClaimMemory(ToPtr(2000), 500));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(2000), 500));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(1400), 100));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(3000), 1));
    EXPECT_TRUE(checker.ClaimMemory(ToPtr(2500), 500));
  }

  {
    // No memory to claim.
    internal::BoundsChecker checker(ToPtr(10000), 0, 0);

    EXPECT_FALSE(checker.ClaimMemory(ToPtr(10000), 1));
    EXPECT_FALSE(checker.ClaimMemory(ToPtr(10000), 0));
  }

  {
    internal::BoundsChecker checker(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 1000), 500, 0);

    // Test overflow.
    EXPECT_FALSE(checker.ClaimMemory(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 750), 4000));
    EXPECT_FALSE(
        checker.ClaimMemory(ToPtr(std::numeric_limits<uintptr_t>::max() - 750),
                            std::numeric_limits<uint32_t>::max()));

    // This should be fine.
    EXPECT_TRUE(checker.ClaimMemory(
        ToPtr(std::numeric_limits<uintptr_t>::max() - 750), 200));
  }
}

}  // namespace
}  // namespace test
}  // namespace mojo


text:
package slpart.models.lenet

import java.text.SimpleDateFormat
import java.util.Date

import com.intel.analytics.bigdl.dataset.{DataSet, DistributedDataSet, MiniBatch, SampleToIDAryMiniBatch}
import com.intel.analytics.bigdl.utils._
import com.intel.analytics.bigdl.nn.{ClassNLLCriterion, Module}
import com.intel.analytics.bigdl.optim._
import org.apache.log4j.{Level, Logger}
import org.apache.spark.SparkContext
import com.intel.analytics.bigdl.numeric.NumericFloat
import slpart.dataloader.MnistLoader

object TrainMnist {
  val logger = Logger.getLogger("org")
  logger.setLevel(Level.OFF)

  import slpart.models.OptionUtils._

  def main(args: Array[String]): Unit = {
    trainParser.parse(args,new TrainParams()).map(param =>{
      val curTime = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date)
      val logFile = s"${curTime}-${param.appName}-bigdl.log"
      LoggerFilter.redirectSparkInfoLogs(logFile)
      val conf = Engine.createSparkConf()
        .setAppName(param.appName)
      val sc = new SparkContext(conf)
      Engine.init

      val virtualCores = vCores(conf)
      val start = System.nanoTime()
      val trainSamples = MnistLoader.trainingSamplesAry(sc,param.dataset,param.zeroScore,isAggregate = param.aggregate,category = param.classes,
        itqbitN = param.itqbitN,itqitN = param.itqitN,itqratioN = param.itqratioN,upBound = param.upBound,splitN = param.minPartN,isSparse = param.isSparse)

      val validationSamples = MnistLoader.validateSamples(sc,param.dataset,param.zeroScore)
      System.out.println(s"generate Aggregate Samples: ${(System.nanoTime()-start) * 1.0 / 1e9} seconds")

      val model = if(param.loadSnapshot && param.model.isDefined){
        Module.load[Float](param.model.get)
      }
      else{
        LeNet5(param.classes)
      }

      val optimMethod = if(param.loadSnapshot && param.state.isDefined){
        OptimMethod.load[Float](param.state.get)
      }else{
        param.optMethod match {
          case "adam" => new Adam[Float](learningRate = param.learningRate,learningRateDecay = param.learningRateDecay)
          case "adadelta" => new Adadelta[Float]()
          case "rmsprop" => new RMSprop[Float](param.learningRate,param.learningRateDecay)
          case "ftrl" => new Ftrl[Float](param.learningRate)
          case _ => new SGD[Float](learningRate = param.learningRate,learningRateDecay = param.learningRateDecay,
            weightDecay = param.weightDecay,momentum = param.momentum,
            dampening = param.dampening,nesterov = param.nesterov)
        }
      }

      if(param.storeInitModel && param.initModel.isDefined){
        System.out.println(s"save initial model in ${param.initModel.get}")
        model.save(param.initModel.get,true)
      }

      val trainDataset = (DataSet.rdd(trainSamples) -> SampleToIDAryMiniBatch(param.batchSize)).asInstanceOf[DistributedDataSet[MiniBatch[Float]]]
      val criterion = ClassNLLCriterion()
      val optimizer = new IDAryDistriOptimizer(model,trainDataset,_criterion = criterion)

      if(param.checkpoint.isDefined){
        optimizer.setCheckpoint(param.checkpoint.get,Trigger.severalIteration(param.checkpointIteration))
        if(param.overwriteCheckpoint) optimizer.overWriteCheckpoint()
      }

      val remvControler = new RemvControler()
      remvControler.isExtraCompute = param.extraCompute
      remvControler.layerName = param.layerName
      remvControler.gradName = param.gradName
      remvControler.removeCriterion = param.removeCriterion
      remvControler.excludeEpoch = param.excludeEpoch
      remvControler.excludeIteration = param.excludeIteration
      remvControler.limitRemoveFraction = param.limitRemoveFraction

      remvControler.isTaskRemove = param.isTaskRemove
      remvControler.taskStrategy = param.taskStrategy
      remvControler.taskFraction = param.taskFraction
      remvControler.excludeTaskFraction = param.excludeTaskFraction

      val prestate = T(
        ("removecontroler",remvControler)
      )
      // set user defined state
      optimizer.setState(prestate)

      optimizer.setValidation(
        trigger = Trigger.everyEpoch,
        sampleRDD = validationSamples,
        vMethods = Array(new Top1Accuracy(),new Top5Accuracy(),new Loss()),
        batchSize = param.batchSize
      )
      optimizer.setOptimMethod(optimMethod)
      optimizer.setEndWhen(Trigger.maxEpoch(param.maxEpoch))

      val trainedModel = optimizer.optimize()

      if(param.storeTrainedModel && param.trainedModel.isDefined){
        System.out.println(s"save trained model in ${param.trainedModel.get}")
        trainedModel.save(param.trainedModel.get,overWrite = true)
        if(param.trainedState.isDefined) {
          System.out.println(s"save trained state in ${param.trainedState.get}")
          optimMethod.save(param.trainedState.get,overWrite = true)
        }
      }

      sc.stop()
    })
  }

}


text:
var fs = require('fs');
var path = require('path');

module.exports = function(filePath, fileExt, callback) {
  fs.readdir(filePath, function(err, data) {
    if (err) {
      return callback(err);
    }
    var filteredFiles = data.filter(function(file) {
      if (path.extname(file) === ('.' + fileExt)) {
        return true;
      }
    });

    callback(null, filteredFiles);
  });
};


text:
#ifndef H_TESTUTIL_
#define H_TESTUTIL_

#include <assert.h>
#include <inttypes.h>
#include <setjmp.h>

#include "os/mynewt.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
  * @addtogroup OSSystem
  * @{
  *   @defgroup OSTestutil Test Utilities
  *   @{
  */

/*
 * General execution flow of test suites and callbacks.
 *
 * TEST_SUITE
 *     TEST_CASE
 *         tu_suite_pre_test_cb
 *         <test-body>
 *         tu_case_pass/tu_case_fail
 *         tu_case_post_test_cb
 */

typedef void tu_case_report_fn_t(const char *msg, void *arg);
typedef void tu_pre_test_fn_t(void *arg);
typedef void tu_post_test_fn_t(void *arg);
typedef void tu_testsuite_fn_t(void);

void tu_set_pass_cb(tu_case_report_fn_t *cb, void *cb_arg);
void tu_set_fail_cb(tu_case_report_fn_t *cb, void *cb_arg);
void tu_suite_init(const char *name);
void tu_suite_pre_test(void);
void tu_suite_complete(void);
int tu_suite_register(tu_testsuite_fn_t* ts, const char *name);

struct ts_suite {
    SLIST_ENTRY(ts_suite) ts_next;
    const char *ts_name;
    tu_testsuite_fn_t *ts_test;
};

SLIST_HEAD(ts_testsuite_list, ts_suite);
extern struct ts_testsuite_list g_ts_suites;

struct tu_config {
    int ts_system_assert;

    const char *ts_suite_name;

    tu_pre_test_fn_t *pre_test_cb;
    void *pre_test_arg;

    /*
     * Called after the current test case completes.
     */
    tu_post_test_fn_t *post_test_cb;
    void *post_test_arg;

    /*
     * Called after test returns success
     */
    tu_case_report_fn_t *pass_cb;
    void *pass_arg;

    /*
     * Called after test fails (typically through a failed test assert)
     */
    tu_case_report_fn_t *fail_cb;
    void *fail_arg;
};

void tu_restart(void);
void tu_start_os(const char *test_task_name, os_task_func_t test_task_handler);

/*
 * Public declarations - test case configuration
 */

void tu_suite_set_pre_test_cb(tu_pre_test_fn_t *cb, void *cb_arg);
void tu_case_set_post_test_cb(tu_post_test_fn_t *cb, void *cb_arg);

void tu_case_init(const char *name);
void tu_case_complete(void);
void tu_case_pass(void);
void tu_case_fail(void);
void tu_case_fail_assert(int fatal, const char *file, int line,
                         const char *expr, const char *format, ...);
void tu_case_write_pass_auto(void);
void tu_case_pass_manual(const char *file, int line,
                         const char *format, ...);
void tu_case_post_test(void);

extern struct tu_config tu_config;

extern const char *tu_suite_name;
extern const char *tu_case_name;

extern int tu_any_failed;
extern int tu_suite_failed;
extern int tu_case_reported;
extern int tu_case_failed;
extern int tu_case_idx;
extern jmp_buf tu_case_jb;

#define TEST_SUITE_DECL(suite_name) void suite_name(void)

#define TEST_SUITE_REGISTER(suite_name)                     \
    tu_suite_register(suite_name, #suite_name);

#define TEST_SUITE(suite_name)                               \
void                                                         \
TEST_SUITE_##suite_name(void);                               \
                                                             \
    void                                                     \
    suite_name(void)                                         \
    {                                                        \
        tu_suite_init(#suite_name);                          \
        TEST_SUITE_##suite_name();                           \
        tu_suite_complete();                                 \
    }                                                        \
                                                             \
    void                                                     \
    TEST_SUITE_##suite_name(void)

/*
 * For declaring the test cases across multiple files
 * belonging to the same suite
 */
#define TEST_CASE_DECL(case_name)                           \
    int case_name(void);

#define TEST_CASE_DEFN(case_name, do_sysinit, body)         \
    int                                                     \
    case_name(void)                                         \
    {                                                       \
        if (do_sysinit) {                                   \
            sysinit();                                      \
        }                                                   \
        tu_suite_pre_test();                                \
        tu_case_init(#case_name);                           \
                                                            \
        if (setjmp(tu_case_jb) == 0) {                      \
            /* Execute test body. */                        \
            body;                                           \
            tu_case_post_test();                            \
            if (!tu_case_failed) {                          \
                tu_case_pass();                             \
            }                                               \
        }                                                   \
        tu_case_complete();                                 \
                                                            \
        return tu_case_failed;                              \
    }                                                       \

/**
 * @brief Defines a test case suitable for running in an application.
 *
 * The `TEST_CASE()` macro should not be used for self-tests (i.e., tests that
 * are run with `newt test`).  Instead, `TEST_CASE_SELF()` or
 * `TEST_CASE_TASK()` should be preferred; those macros perform system clean up
 * before the test runs.
 */
#define TEST_CASE(case_name)                                    \
    void TEST_CASE_##case_name(void);                           \
    TEST_CASE_DEFN(case_name, false, TEST_CASE_##case_name())   \
                                                                \
    void                                                        \
    TEST_CASE_##case_name(void)

#define TEST_CASE_SELF_EMIT_(case_name)                         \
    void TEST_CASE_##case_name(void);                           \
    TEST_CASE_DEFN(case_name, true, TEST_CASE_##case_name())    \
                                                                \
    void                                                        \
    TEST_CASE_##case_name(void)

#define TEST_CASE_TASK_EMIT_(case_name)                     \
    void TEST_CASE_##case_name(void *arg);                  \
    TEST_CASE_DEFN(case_name, true,                         \
                   tu_start_os(#case_name "_test_task",     \
                               TEST_CASE_##case_name));     \
                                                            \
    void                                                    \
    TEST_CASE_##case_name(void *TU_UNUSED_arg)

#if MYNEWT_VAL(SELFTEST) || defined __DOXYGEN__

/**
 * @brief Defines a test case for self-test mode (i.e., suitable for `newt
 * test`).
 *
 * Test cases defined with `TEST_CASE_SELF()` execute `sysinit()` before the
 * test body.
 */
#define TEST_CASE_SELF(case_name) TEST_CASE_SELF_EMIT_(case_name)

/**
 * @brief Defines a test case that runs inside a temporary task.
 *
 * Most tests don't utilize the OS scheduler; they simply run in main(),
 * outside the context of a task.  However, sometimes the OS is required to
 * fully test a package, e.g., to verify timeouts and other timed events.
 *
 * The `TEST_CASE_TASK()` macro simplifies the implementation of test cases
 * that require the OS.  This macro is identical in usage to
 * `TEST_CASE_SELF()`, except the test case it defines performs some additional
 * preliminary work:
 *
 * 1. Creates the default task.
 * 2. Creates the "test task" (the task where the test itself runs).
 * 3. Starts the OS.
 *
 * The body following the macro invocation is what actually runs in the test
 * task.  The test task has a priority of `OS_MAIN_TASK_PRIO + 1`, so it yields
 * to the main task.  Thus, tests using this macro typically have the following
 * form:
 *
 *     TEST_CASE_TASK(my_test)
 *     {
 *         enqueue_event_to_main_task();
 *         // Event immediately runs to completion.
 *         TEST_ASSERT(expected_event_result);
 *
 *         // ...
 *     }
 *
 * The `TEST_CASE_TASK()` macro is only usable in self-tests (i.e., tests that
 * are run with `newt test`).
 */
#define TEST_CASE_TASK(case_name) TEST_CASE_TASK_EMIT_(case_name)

#else

#define TEST_CASE_SELF(case_name)                               \
    static_assert(0, "Test `"#case_name"` is a self test.  "    \
                     "It can only be run from `newt test`");    \
    /* Emit case definition anyway to prevent syntax errors. */ \
    TEST_CASE_SELF_EMIT_(case_name)

#define TEST_CASE_TASK(case_name)                               \
    static_assert(0, "Test `"#case_name"` is a self test.  "    \
                     "It can only be run from `newt test`");    \
    /* Emit case definition anyway to prevent syntax errors. */ \
    TEST_CASE_TASK_EMIT_(case_name)

#endif

#define FIRST_AUX(first, ...) first
#define FIRST(...) FIRST_AUX(__VA_ARGS__, _)

#define NUM(...) ARG10(__VA_ARGS__, N, N, N, N, N, N, N, N, 1, _)
#define ARG10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, ...) a10

#define REST_OR_0(...) REST_OR_0_AUX(NUM(__VA_ARGS__), __VA_ARGS__)
#define REST_OR_0_AUX(qty, ...) REST_OR_0_AUX_INNER(qty, __VA_ARGS__)
#define REST_OR_0_AUX_INNER(qty, ...) REST_OR_0_AUX_##qty(__VA_ARGS__)
#define REST_OR_0_AUX_1(first) 0
#define REST_OR_0_AUX_N(first, ...) __VA_ARGS__

#define XSTR(s) STR(s)
#ifndef STR
#define STR(s) #s
#endif

#if MYNEWT_VAL(TESTUTIL_SYSTEM_ASSERT)

#define TEST_ASSERT_FULL(fatal, expr, ...) (assert(expr))

#else

#define TEST_ASSERT_FULL(fatal, expr, ...) do                 \
{                                                             \
    if (!(expr)) {                                            \
        tu_case_fail_assert((fatal), __FILE__,                \
                            __LINE__, XSTR(expr),             \
                            __VA_ARGS__);                     \
    }                                                         \
} while (0)

#endif

#define TEST_ASSERT(...)                                      \
    TEST_ASSERT_FULL(0, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))

#define TEST_ASSERT_FATAL(...)                                \
    TEST_ASSERT_FULL(1, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))

#define TEST_PASS(...)                                        \
    tu_case_pass_manual(__FILE__, __LINE__, __VA_ARGS__);

#if MYNEWT_VAL(TEST)
#define ASSERT_IF_TEST(expr) assert(expr)
#else
#define ASSERT_IF_TEST(expr)
#endif

#ifdef __cplusplus
}
#endif

#endif

/**
 *   @} OSTestutil
 * @} OSSys
 */


text:
function initializeMap(cntxtPath) {
    contextPath = cntxtPath;
    var latlng;
    var zoom = 15;
    latlng = new google.maps.LatLng(39.168486, -86.523455);

    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: true,
        zoomControl: true,
        scaleControl: false,
        mapTypeControl: false,
        disableDoubleClickZoom: false
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, 'click', selectPoint);

    mapService = new gmaps.ags.MapService(arcGisServerUrl);
    var agsType = new gmaps.ags.MapType(arcGisServerUrl, {name: 'ArcGIS', opacity: 1.0});
    map.overlayMapTypes.insertAt(0, agsType);
    google.maps.event.addListenerOnce(mapService, 'load', function () {
        $('#findButton').removeAttr('disabled');
    });

    iw = new google.maps.InfoWindow();

    initializePoi();
}

function initializePoi() {
    var poiJson = $('#poiJson').val();
    if (poiJson.length) {
        var obj = jQuery.parseJSON(poiJson);
        if (obj) {
            $('#poiId').val(obj.poiId);
            $('#poiName').val(obj.name);
            $('#poiOfficialName').val(obj.officialName);
            $('#description').val(obj.description);
            $('#shortDescription').val(obj.shortDescription);
            $('#poiVersion').val(obj.versionNumber);
            $('#latitude').val(obj.latitude);
            $('#longitude').val(obj.longitude);
            $('#url').val(obj.url);
            $('#thumbnailUrl').val(obj.thumbnailUrl);
            $('#fbLikeUrl').val(obj.fbLikeUrl);
            if (obj.fbLikeButtonEnabled == 'T') {
                $('#fbLikeButtonEnabled').attr('checked', 'checked');
            } else {
                $('#fbLikeButtonEnabled').removeAttr('checked');
            }
            for (var i = 0; i < obj.permissions.length; i++) {
                var permission = obj.permissions[i];
                addPermissionGroup(permission.groupName, permission.type == 'E');
            }

            for (var i = 0; i < obj.media.length; i++) {
                var media = obj.media[i];
                if (media.type == imageType) {
                    loadImageToList(media.url, media.title, media.caption);
                } else if (media.type == audioType) {
                    loadAudioToList(media.oggVorbisUrl, media.mp3Url, media.wavUrl, media.title, media.caption);
                } else if (media.type == videoType) {
                    loadVideoToList(media.oggUrl, media.mp4Url, media.webMUrl, media.youTubeUrl, media.title, media.caption);
                }
            }

            place = new Object();
            place.name = obj.name;
            place.officialName = obj.officialName;
            place.location = new google.maps.LatLng(obj.latitude, obj.longitude);
            place.id = obj.locationId;
            place.type = obj.type;
            place.media = obj.media;
            place.description = obj.description;
            place.shortDescription = obj.shortDescription;
            place.url = obj.url;
            place.thumbnailUrl = obj.thumbnailUrl;
            place.fbLikeUrl = obj.fbLikeUrl == 'T';
            place.permissions = obj.permissions;
            if (obj.phoneNumbers) {
                place.phoneNumbers = new Array();
                for (var i = 0; i < obj.phoneNumbers.length; i++) {
                    var number = obj.phoneNumbers[i];
                    var phoneNumber = new Object();
                    phoneNumber.value = number.number;
                    phoneNumber.name = number.name;
                    place.phoneNumbers.push(phoneNumber);
                }
                populatePhoneNumbers(place.phoneNumbers);
            }
            if (obj.emailAddresses) {
                place.emailAddresses = new Array();
                for (var p = 0; p < obj.emailAddresses.length; p++) {
                    var email = obj.emailAddresses[p];
                    var emailAddress = new Object();
                    emailAddress.address = email.address;
                    emailAddress.name = email.name;
                    place.emailAddresses.push(emailAddress);
                }
                populateEmailAddresses(place.emailAddresses);
            }
            google.maps.event.addListenerOnce(map, "tilesloaded", function () {
                setTempMarker(place);
                map.panTo(place.location);
            });
        }
    }
}

function savePoi() {
    if (validatePOI()) {
        var poi = new Object();

        poi.id = $('#poiId').val();
        poi.locationId = tempMarker.place.id;
        poi.type = tempMarker.place.type;
        poi.name = $('#poiName').val();
        poi.officialName = $('#poiOfficialName').val();
        poi.description = $('#description').val();
        poi.shortDescription = $('#shortDescription').val();
        poi.version = $('#poiVersion').val();
        poi.location = new Object();
        poi.location.latitude = $('#latitude').val();
        poi.location.longitude = $('#longitude').val();
        poi.url = $('#url').val();
        poi.thumbnailUrl = $('#thumbnailUrl').val();
        poi.fbLikeUrl = $('#fbLikeUrl').val();
        poi.fbLikeButtonEnabled = $('#fbLikeButtonEnabled').attr('checked') ? true : false;
        addSelectedMediaToPoi(poi);
        addPhoneNumbersToPoi(poi);
        addEmailAddressesToPoi(poi);

        var permissions = [];
        $('#viewPermissionsList li').each(function (index, element) {
            var group = $('span.group', element).text();
            var permission = new Object();
            permission.group = group;
            permission.type = 'V';
            permissions.push(permission);
        });
        $('#editPermissionsList li').each(function (index, element) {
            var group = $('span.group', element).text();
            var permission = new Object();
            permission.group = group;
            permission.type = 'E';
            permissions.push(permission);
        });
        poi.permissions = permissions;

        $('#data').val(JSON.stringify(poi));
        $("#postForm").submit();
    }
}

function validatePOI() {
    if (!tempMarker || !tempMarker.place) {
        alert('You must choose a location.');
        return false;
    }
    if ($('#fbLikeButtonEnabled').attr('checked') && !$('#fbLikeUrl').val()) {
        alert('A URL for the Like Button is required.');
        return false;
    }
    if (!$('#editPermissionsList li').length) {
        alert('You must include at least one ADS group with editing permissions.');
        return false;
    }
    var pointName = $('#poiName').val();
    var pointOfficialName = $('#poiOfficialName').val();
    if (!pointName.length || !pointOfficialName.length) {
        alert('Please name this location.');
        return false;
    }
    if (pointName.length > 256 || pointOfficialName.length > 256) {
        alert('Location names must be less than or equal to 256 characters.');
        return false;
    }
    if (tempMarker.place.name && tempMarker.place.location) return true;
    else return false;
}

function selectPoint(event) {
    if (isSelectingPoint) {
        updateSelectedPlace(event.latLng);
    }

    if (isSelectingVenue) {
        selectedPlace = null;
        if (tempMarker) {
            tempMarker.setMap(null);
        }
        findFoursquareVenues(event.latLng);
    }
}

function updateSelectedPlace(latLng) {
    selectedPlace = new Object();
    selectedPlace.location = latLng;
    selectedPlace.type = customPointType;
    setTempMarker(selectedPlace);
}

function selectBuilding(number) {
    if (number > 0) {
        var place = places[number - 1]; // 'select:' is index 0, so number 1 = places[0]
        setTempMarker(place)
        selectedPlace = place;
        map.panTo(place.location);
    }
}

function setTempMarker(place) {
    if (!tempMarker) {
        tempMarker = new google.maps.Marker({
            position: place.location,
            map: map,
            draggable: false,
            icon: tempMarkerImage
        });
        google.maps.event.addListener(tempMarker, 'click', function () {
            showIW();
        });
    } else {
        tempMarker.setPosition(place.location);
    }
    tempMarker.setTitle(place.name);
    tempMarker.place = place;
    $('#latitude').val(place.location.lat());
    $('#longitude').val(place.location.lng());
    $('#poiName').val(place.name);
    $('#url').val(place.url);
}

function showIW() {
    var content = '';
    if ($('#poiName').val()) {
        content += '
' + $('#poiName').val() + '
';
    } else {

    }
    if ($('#shortDescription').val()) {
        content += $('#shortDescription').val();
    }
    if ($('#url').val()) {
        content += '
' + $('#url').val() + '
';
    }
    if (content) {
        iw.setContent(content);
        iw.open(map, tempMarker);
    }
}

function changeSelectorTabs(event, ui) {
    clearSearchResults();
    var $tabs = $('#selector').tabs();
    var selected = $tabs.tabs('option', 'selected');
    if (selected == 1) { //Select A Point is the second tab
        changeMode('select');
    } else if (selected == 2) { //Select A Foursquare Venue is the third tab
        changeMode('venue');
    } else {
        changeMode();
    }
}

function changeMode(mode) {
    if (mode === 'select') {
        isEditing = false;
        isFineTuning = false;
        isSelectingPoint = true;
        isSelectingVenue = false;
    } else if (mode === 'venue') {
        isEditing = false;
        isFineTuning = false;
        isSelectingPoint = false;
        isSelectingVenue = true;
    } else {
        isEditing = false;
        isFineTuning = false;
        isSelectingPoint = false;
        isSelectingVenue = false;
    }
}

function updateSelectedPOIs() {
    var $tabs = $('#wizard').tabs();
    var selected = $tabs.tabs('option', 'selected');
    if (selected == 3) { //Save is the fourth tab
        var list = '';
        for (var i = 0; i < markers.length; i++) {
            list += '
' + (i + 1) + '. ' + markers[i].building.name + '
'
        }
        $('#selectedPOIs').html(list);
    }
}


text:
require "test_helper"

class EncryptableTest < ActiveSupport::TestCase
  include Support::Assertions
  include Support::Factories
  include Support::Swappers

  def encrypt_password(admin, pepper=Admin.pepper, stretches=Admin.stretches, encryptor=Admin.encryptor_class)
    encryptor.digest('123456', stretches, admin.password_salt, pepper)
  end

  test 'should generate salt while setting password' do
    assert_present create_admin.password_salt
  end

  test 'should not change password salt when updating' do
    admin = create_admin
    salt = admin.password_salt
    admin.expects(:password_salt=).never
    admin.save!
    assert_equal salt, admin.password_salt
  end

  test 'should generate a base64 hash using SecureRandom for password salt' do
    swap_with_encryptor Admin, :sha1 do
      SecureRandom.expects(:base64).with(15).returns('01lI').once
      salt = create_admin.password_salt
      assert_not_equal '01lI', salt
      assert_equal 4, salt.size
    end
  end

  test 'should not generate salt if password is blank' do
    assert_blank create_admin(:password => nil).password_salt
    assert_blank create_admin(:password => '').password_salt
  end

  test 'should encrypt password again if password has changed' do
    admin = create_admin
    encrypted_password = admin.encrypted_password
    admin.password = admin.password_confirmation = 'new_password'
    admin.save!
    assert_not_equal encrypted_password, admin.encrypted_password
  end

  test 'should respect encryptor configuration' do
    swap_with_encryptor Admin, :sha512 do
      admin = create_admin
      assert_equal admin.encrypted_password, encrypt_password(admin, Admin.pepper, Admin.stretches, Devise::Encryptable::Encryptors::Sha512)
    end
  end

  test 'should not validate password when salt is nil' do
    admin = create_admin
    admin.password_salt = nil
    admin.save
    assert_not admin.valid_password?('123456')
  end

  test 'required_fields should contain the fields that Devise uses' do
    assert_same_content Devise::Models::Encryptable.required_fields(Admin), [
      :password_salt
    ]
  end
end


text:
<?php
declare(strict_types=1);

namespace Yproximite\Api\Message\Location;

use Yproximite\Api\Message\MessageInterface;
use Yproximite\Api\Message\LocaleAwareMessageTrait;
use Yproximite\Api\Model\Location\LocationTranslation;

/**
 * Class LocationTranslationMessage
 */
class LocationTranslationMessage implements MessageInterface
{
    use LocaleAwareMessageTrait;

    /**
     * @var string
     */
    private $title;

    /**
     * @var string|null
     */
    private $openingHours;

    /**
     * @param LocationTranslation $translation
     *
     * @return self
     */
    public static function createFromLocationTranslation(LocationTranslation $translation): self
    {
        $message = new self();
        $message->setLocale($translation->getLocale());
        $message->setTitle($translation->getTitle());
        $message->setOpeningHours($translation->getOpeningHours());

        return $message;
    }

    /**
     * @return string
     */
    public function getTitle(): string
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle(string $title)
    {
        $this->title = $title;
    }

    /**
     * @return null|string
     */
    public function getOpeningHours()
    {
        return $this->openingHours;
    }

    /**
     * @param null|string $openingHours
     */
    public function setOpeningHours($openingHours)
    {
        $this->openingHours = $openingHours;
    }

    /**
     * {@inheritdoc}
     */
    public function build()
    {
        return [
            'title'        => $this->getTitle(),
            'openingHours' => $this->getOpeningHours(),
        ];
    }
}


text:
using System.Linq;
using System.Reflection;

namespace Core
{
  public static class IProjectInfoExtensions
  {
    ///
    /// returns the project info
    ///
    /// works when this pre build event is added to the project (and the generated file is compiled):
    /// echo namespace $(ProjectName){ public  static class  ProjectInfo{ public static readonly string ProjectDir = @"$(ProjectDir)";  }} > $(ProjectDir)\ProjectInfo.cs
    ///
    /// <param name="assembly"></param>
    /// <returns></returns>
    public static IProjectInfo GetProjectInfo(this Assembly assembly)
    {
      var info = new ProjectInfo() { Assembly = assembly };
      var infoType = assembly.GetExportedTypes().SingleOrDefault(t => t.Name == "ProjectInfo");
      if (infoType == null) return info;
      var field = infoType.GetField("ProjectDir");
      if (field == null) return info;
      var value = field.GetValue(null);
      info.ProjectDir = value as string;
      return info;
    }

  }
}


text:
<?php

namespace Respect\Validation\Rules;

class VowelTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerForValidVowels
     */
    public function testValidDataWithVowelsShouldReturnTrue($validVowels, $additional = '')
    {
        $validator = new Vowel($additional);
        $this->assertTrue($validator->validate($validVowels));
    }

    /**
     * @dataProvider providerForInvalidVowels
     * @expectedException Respect\Validation\Exceptions\VowelException
     */
    public function testInvalidVowelsShouldFailAndThrowVowelException($invalidVowels, $additional = '')
    {
        $validator = new Vowel($additional);
        $this->assertFalse($validator->validate($invalidVowels));
        $this->assertFalse($validator->assert($invalidVowels));
    }

    /**
     * @dataProvider providerForInvalidParams
     * @expectedException Respect\Validation\Exceptions\ComponentException
     */
    public function testInvalidConstructorParamsShouldThrowComponentExceptionUponInstantiation($additional)
    {
        $validator = new Vowel($additional);
    }

    /**
     * @dataProvider providerAdditionalChars
     */
    public function testAdditionalCharsShouldBeRespected($additional, $query)
    {
        $validator = new Vowel($additional);
        $this->assertTrue($validator->validate($query));
    }

    public function providerAdditionalChars()
    {
        return array(
            array('!@#$%^&*(){}', '!@#$%^&*(){} aeo iu'),
            array('[]?+=/\\-_|"\',<>.', "[]?+=/\\-_|\"',<>. \t \n aeo iu"),
        );
    }

    public function providerForInvalidParams()
    {
        return array(
            array(new \stdClass()),
            array(array()),
            array(0x2),
        );
    }

    public function providerForValidVowels()
    {
        return array(
            array(''),
            array('a'),
            array('e'),
            array('i'),
            array('o'),
            array('u'),
            array('aeiou'),
            array('aei ou'),
            array("\na\t"),
            array('uoiea'),
        );
    }

    public function providerForInvalidVowels()
    {
        return array(
            array(null),
            array('16'),
            array('F'),
            array('g'),
            array('Foo'),
            array(-50),
            array('basic'),
        );
    }
}


text:
#include <aws/devicefarm/model/ListDevicePoolsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DeviceFarm::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListDevicePoolsRequest::ListDevicePoolsRequest() :
    m_arnHasBeenSet(false),
    m_type(DevicePoolType::NOT_SET),
    m_typeHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String ListDevicePoolsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_arnHasBeenSet)
  {
   payload.WithString("arn", m_arn);

  }

  if(m_typeHasBeenSet)
  {
   payload.WithString("type", DevicePoolTypeMapper::GetNameForDevicePoolType(m_type));
  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("nextToken", m_nextToken);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection ListDevicePoolsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DeviceFarm_20150623.ListDevicePools"));
  return headers;

}


text:
yarn:
	yarn && node server.js

npm:
	npm install && node server.js


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var socket_io = require('socket.io');
var routes = require('./routes/index');

var app = express();
var io = socket_io();
app.io = io;

var sockets = require('./modules/sockets')(app.io);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
//app.engine('html', require('ejs').renderFile);
//app.set('view options', { layout: 'other' });

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  <title>Jasmine Spec Runner</title>

  <link rel="shortcut icon" type="image/png" href="lib/jasmine-1.3.1/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="lib/jasmine-1.3.1/jasmine.css">

  <textarea id="in"></textarea>
  <button id="sub">转换</button>


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'planner-footer',
    templateUrl: 'planner.footer.component.html',
    styleUrls: ['planner.footer.component.css']
})

export class PlannerFooterComponent {

    @Output() onTimeSelection = new EventEmitter<number> ();
    @Output() onPrint = new EventEmitter();

    onTimeSelectionEvent(interval: number) {
        console.log('Selected time: ', interval);
        this.onTimeSelection.emit(interval);
    }

    onPrintEvent () {
        console.log('Print Planner');
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package joglus.example1.glsl;

import javax.media.opengl.GL3;

/**
 *
 * @author gbarbieri
 */
public class Colored extends glsl.GLSLProgramObject {

    private int projectionUL;
    private int modelViewUL;

    public Colored(GL3 gl3, String shadersFilepath, String vertexShader, String fragmentShader) {
        super(gl3, shadersFilepath, vertexShader, fragmentShader);

        projectionUL = gl3.glGetUniformLocation(getProgramId(), "projection");
        modelViewUL = gl3.glGetUniformLocation(getProgramId(), "modelView");
    }

    public int getProjectionUL() {
        return projectionUL;
    }

    public int getModelViewUL() {
        return modelViewUL;
    }
}


text:
'use strict'

const fs = require('fs')
const ospath = require('path')
const childProcess = require('child_process')

class MockServer {
  constructor (listener) {
    // we need to use "fork" to spawn a new Node.js process otherwise we will create a deadlock.
    this.childProcess = childProcess.fork(ospath.join(__dirname, 'bin', 'mock-server.js'))
    this.childProcess.on('message', (msg) => {
      if (msg.event === 'started') {
        // auto-configure
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/foo.adoc',
            reply: {
              status: 200,
              headers: { 'content-type': 'text/plain' },
              body: 'Foo'
            }
          }
        })
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/include-lines.adoc',
            reply: {
              status: 200,
              headers: { 'content-type': 'text/plain' },
              body: `First line
Second line
Third line
Fourth line
`
            }
          }
        })
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/dir/bar.adoc',
            reply: {
              status: 200,
              headers: { 'content-type': 'text/plain' },
              body: 'Bar'
            }
          }
        })
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/include-tag.adoc',
            reply: {
              status: 200,
              headers: { 'content-type': 'text/plain' },
              body: `// tag::a[]
tag-a
// end::a[]
// tag::b[]
tag-b
// end::b[]
`
            }
          }
        })
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/dir/1.0.0/release.adoc',
            reply: {
              status: 200,
              headers: { 'content-type': 'text/plain' },
              body: `= Release note

- Emojis
- JavaScript client
- New Dashboard
`
            }
          }
        })
        this.childProcess.send({
          event: 'configure',
          data: {
            method: 'GET',
            path: '/cat.png',
            reply: {
              status: 200,
              headers: { 'content-type': 'image/png' },
              body: fs.readFileSync(ospath.join(__dirname, '..', 'fixtures', 'images', 'cat.png'), 'binary')
            }
          }
        })
      }
    })
    if (listener) {
      this.childProcess.on('message', listener)
    }
  }

  async close () {
    return new Promise((resolve, reject) => {
      this.childProcess.on('message', (msg) => {
        if (msg.event === 'exiting') {
          resolve()
        }
      })
      this.childProcess.send({ event: 'exit' })
    })
  }

  registerFiles (files) {
    for (const file of files) {
      const webPath = file.webPath
      const path = file.path
      this.childProcess.send({
        event: 'configure',
        data: {
          method: 'GET',
          path: webPath,
          reply: {
            status: 200,
            headers: { 'content-type': file.mimetype },
            body: fs.readFileSync(path, file.mimetype === 'image/png' || file.mimetype === 'image/jpg' ? 'binary' : 'utf8')
          }
        }
      })
    }
  }
}

module.exports = MockServer


text:
import {Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef, NgModule} from '@angular/core';
import {FILTER} from '../../shared/services/caman-filter-names.service';
import {ImageFilter} from '../../shared/services/image-filter.service';
import {PhotoBoothStatus} from '../../shared/services/photo-booth-status.service';

@Component({
	moduleId: module.id,
	selector: 'pb-image-filter',
	templateUrl: 'filter-carousel.component.html',
	styleUrls: ['filter-carousel.component.css']
})
export class FilterCarousel implements OnInit, OnDestroy, AfterViewInit {
	private _subscription: any;
	public filters: Array<string> = FILTER;
	public isFilterMode: boolean

	@ViewChild('filtersHolder') filterHolder: ElementRef;

	constructor(
		private _photoBoothStatus: PhotoBoothStatus,
		private _imageFilter: ImageFilter
	) {}
	applyFilter(filter: string) {
		this._imageFilter.applyFilter(filter);
	}
	ngOnInit() {
		this.setIsFilterMode();
		this._subscription = this._photoBoothStatus.stausChange$.subscribe(
			status => {
				this.setIsFilterMode();
			}
		);
	}
	//after the view is initilized we apply the sample filters to the preview images
	ngAfterViewInit(){
		var filterImages = this.filterHolder.nativeElement.querySelectorAll('.filter-holder canvas');
		//TODO move to a separate function
		for (var i = 0; i < filterImages.length; i++){
			this._imageFilter.addFilter(
				filterImages[i],
				'assets/images/filter_image.jpg',
				filterImages[i].getAttribute('data-filter_name')
			);
		}
	}
	ngOnDestroy() {
		this._subscription.unsubscribe();
	}
	setIsFilterMode(){
		this.isFilterMode = this._photoBoothStatus.isFilterMode;
	}
}


text:
// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "xfa/fxbarcode/cbc_ean8.h"

#include "xfa/fxbarcode/oned/BC_OnedEAN8Writer.h"

CBC_EAN8::CBC_EAN8() : CBC_OneCode(new CBC_OnedEAN8Writer) {}

CBC_EAN8::~CBC_EAN8() {}

CFX_WideString CBC_EAN8::Preprocess(const CFX_WideStringC& contents) {
  CFX_WideString encodeContents =
      static_cast<CBC_OnedEAN8Writer*>(m_pBCWriter.get())
          ->FilterContents(contents);
  int32_t length = encodeContents.GetLength();
  if (length <= 7) {
    for (int32_t i = 0; i < 7 - length; i++)
      encodeContents = FX_WCHAR('0') + encodeContents;

    CFX_ByteString byteString = encodeContents.UTF8Encode();
    int32_t checksum = static_cast<CBC_OnedEAN8Writer*>(m_pBCWriter.get())
                           ->CalcChecksum(byteString);
    encodeContents += FX_WCHAR(checksum - 0 + '0');
  }
  if (length > 8)
    encodeContents = encodeContents.Mid(0, 8);

  return encodeContents;
}

bool CBC_EAN8::Encode(const CFX_WideStringC& contents,
                      bool isDevice,
                      int32_t& e) {
  if (contents.IsEmpty()) {
    e = BCExceptionNoContents;
    return false;
  }
  BCFORMAT format = BCFORMAT_EAN_8;
  int32_t outWidth = 0;
  int32_t outHeight = 0;
  CFX_WideString encodeContents = Preprocess(contents);
  CFX_ByteString byteString = encodeContents.UTF8Encode();
  m_renderContents = encodeContents;
  uint8_t* data = static_cast<CBC_OnedEAN8Writer*>(m_pBCWriter.get())
                      ->Encode(byteString, format, outWidth, outHeight, e);
  if (e != BCExceptionNO)
    return false;
  static_cast<CBC_OneDimWriter*>(m_pBCWriter.get())
      ->RenderResult(encodeContents.AsStringC(), data, outWidth, isDevice, e);
  FX_Free(data);
  if (e != BCExceptionNO)
    return false;
  return true;
}

bool CBC_EAN8::RenderDevice(CFX_RenderDevice* device,
                            const CFX_Matrix* matrix,
                            int32_t& e) {
  static_cast<CBC_OneDimWriter*>(m_pBCWriter.get())
      ->RenderDeviceResult(device, matrix, m_renderContents.AsStringC(), e);
  if (e != BCExceptionNO)
    return false;
  return true;
}

bool CBC_EAN8::RenderBitmap(CFX_DIBitmap*& pOutBitmap, int32_t& e) {
  static_cast<CBC_OneDimWriter*>(m_pBCWriter.get())
      ->RenderBitmapResult(pOutBitmap, m_renderContents.AsStringC(), e);
  if (e != BCExceptionNO)
    return false;
  return true;
}

BC_TYPE CBC_EAN8::GetType() {
  return BC_EAN8;
}


text:
<?php
declare(strict_types=1);

class_alias(
    'Cake\Controller\ControllerFactory',
    'Cake\Http\ControllerFactory'
);
deprecationWarning(
    'Use Cake\Controller\ControllerFactory instead of Cake\Http\ControllerFactory.'
);


text:
/*
 * JBox2D - A Java Port of Erin Catto's Box2D
 *
 * JBox2D homepage: http://jbox2d.sourceforge.net/
 * Box2D homepage: http://www.box2d.org
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 * claim that you wrote the original software. If you use this software
 * in a product, an acknowledgment in the product documentation would be
 * appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 * misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 */

package org.jbox2d.collision;

//Updated to rev 56 of b2PairManager.h

public abstract class PairCallback {
    // This should return the new pair user data. It is okay if the
    // user data is null.
    public abstract Object pairAdded(Object proxyUserData1,
            Object proxyUserData2);

    // This should free the pair's user data. In extreme circumstances, it is
    // possible
    // this will be called with null pairUserData because the pair never
    // existed.
    public abstract void pairRemoved(Object proxyUserData1,
            Object proxyUserData2, Object pairUserData);
}


text:
using FluentAssertions;
using IntroductionToEventSourcing.GettingStateFromEvents.Tools;
using Xunit;

namespace IntroductionToEventSourcing.GettingStateFromEvents;

// EVENTS
public record ShoppingCartOpened(
    Guid ShoppingCartId,
    Guid ClientId
);

public record ProductItemAddedToShoppingCart(
    Guid ShoppingCartId,
    PricedProductItem ProductItem
);

public record ProductItemRemovedFromShoppingCart(
    Guid ShoppingCartId,
    PricedProductItem ProductItem
);

public record ShoppingCartConfirmed(
    Guid ShoppingCartId,
    DateTime ConfirmedAt
);

public record ShoppingCartCanceled(
    Guid ShoppingCartId,
    DateTime CanceledAt
);

// VALUE OBJECTS
public record PricedProductItem(
    Guid ProductId,
    int Quantity,
    decimal UnitPrice
)
{
    public decimal TotalAmount => Quantity * UnitPrice;
}

public enum ShoppingCartStatus
{
    Pending = 1,
    Confirmed = 2,
    Canceled = 4
}

public class ShoppingCartDetails
{
    public Guid Id { get; set; }
    public Guid ClientId { get; set; }
    public ShoppingCartStatus Status { get; set; }
    public IList<PricedProductItem> ProductItems { get; set; } = new List<PricedProductItem>();
    public DateTime? ConfirmedAt { get; set; }
    public DateTime? CanceledAt { get; set; }
    public decimal TotalPrice { get; set; }
    public decimal TotalItemsCount { get; set; }
}

public class ShoppingCartShortInfo
{
    public Guid Id { get; set; }
    public Guid ClientId { get; set; }
    public decimal TotalPrice { get; set; }
    public decimal TotalItemsCount { get; set; }
}

public class ProjectionsTests
{
    [Fact]
    [Trait("Category", "SkipCI")]
    public void GettingState_ForSequenceOfEvents_ShouldSucceed()
    {
        var shoppingCartId = Guid.NewGuid();

        var clientId = Guid.NewGuid();
        var shoesId = Guid.NewGuid();
        var tShirtId = Guid.NewGuid();
        var dressId = Guid.NewGuid();
        var trousersId = Guid.NewGuid();

        var twoPairsOfShoes = new PricedProductItem(shoesId, 2, 100);
        var pairOfShoes = new PricedProductItem(shoesId, 1, 100);
        var tShirt = new PricedProductItem(tShirtId, 1, 50);
        var dress = new PricedProductItem(dressId, 3, 150);
        var trousers = new PricedProductItem(trousersId, 1, 300);

        var cancelledShoppingCartId = Guid.NewGuid();
        var otherClientShoppingCartId = Guid.NewGuid();
        var otherConfirmedShoppingCartId = Guid.NewGuid();
        var otherPendingShoppingCartId = Guid.NewGuid();
        var otherClientId = Guid.NewGuid();

        var logPosition = 0ul;

        var events = new EventEnvelope[]
        {
            // first confirmed
            new EventEnvelope<ShoppingCartOpened>(new ShoppingCartOpened(shoppingCartId, clientId),
                EventMetadata.For(1, ++logPosition)),
            new EventEnvelope<ProductItemAddedToShoppingCart>(
                new ProductItemAddedToShoppingCart(shoppingCartId, twoPairsOfShoes),
                EventMetadata.For(2, ++logPosition)),
            new EventEnvelope<ProductItemAddedToShoppingCart>(
                new ProductItemAddedToShoppingCart(shoppingCartId, tShirt), EventMetadata.For(3, ++logPosition)),
            new EventEnvelope<ProductItemRemovedFromShoppingCart>(
                new ProductItemRemovedFromShoppingCart(shoppingCartId, pairOfShoes),
                EventMetadata.For(4, ++logPosition)),
            new EventEnvelope<ShoppingCartConfirmed>(new ShoppingCartConfirmed(shoppingCartId, DateTime.UtcNow),
                EventMetadata.For(5, ++logPosition)),

            // cancelled
            new EventEnvelope<ShoppingCartOpened>(new ShoppingCartOpened(cancelledShoppingCartId, clientId),
                EventMetadata.For(1, ++logPosition)),
            new EventEnvelope<ProductItemAddedToShoppingCart>(
                new ProductItemAddedToShoppingCart(cancelledShoppingCartId, dress),
                EventMetadata.For(2, ++logPosition)),
            new EventEnvelope<ShoppingCartCanceled>(new ShoppingCartCanceled(cancelledShoppingCartId, DateTime.UtcNow),
                EventMetadata.For(3, ++logPosition)),

            // confirmed but other client
            new EventEnvelope<ShoppingCartOpened>(new ShoppingCartOpened(otherClientShoppingCartId, otherClientId),
                EventMetadata.For(1, ++logPosition)),
            new EventEnvelope<ProductItemAddedToShoppingCart>(
                new ProductItemAddedToShoppingCart(otherClientShoppingCartId, dress),
                EventMetadata.For(2, ++logPosition)),
            new EventEnvelope<ShoppingCartConfirmed>(
                new ShoppingCartConfirmed(otherClientShoppingCartId, DateTime.UtcNow),
                EventMetadata.For(3, ++logPosition)),

            // second confirmed
            new EventEnvelope<ShoppingCartOpened>(new ShoppingCartOpened(otherConfirmedShoppingCartId, clientId),
                EventMetadata.For(1, ++logPosition)),
            new EventEnvelope<ProductItemAddedToShoppingCart>(
                new ProductItemAddedToShoppingCart(otherConfirmedShoppingCartId, trousers),
                EventMetadata.For(2, ++logPosition)),
            new EventEnvelope<ShoppingCartConfirmed>(
                new ShoppingCartConfirmed(otherConfirmedShoppingCartId, DateTime.UtcNow),
                EventMetadata.For(3, ++logPosition)),

            // first pending
            new EventEnvelope<ShoppingCartOpened>(new ShoppingCartOpened(otherPendingShoppingCartId, clientId),
                EventMetadata.For(1, ++logPosition))
        };

        var eventBus = new EventStore();
        var database = new Database();

        // TODO:
        // 1. Register here your event handlers using `eventBus.Register`.
        // 2. Store results in database.
        eventBus.Append(events);

        // first confirmed
        var shoppingCart = database.Get<ShoppingCartDetails>(shoppingCartId)!;
        shoppingCart.Should().NotBeNull();
        shoppingCart.Id.Should().Be(shoppingCartId);
        shoppingCart.ClientId.Should().Be(clientId);
        shoppingCart.Status.Should().Be(ShoppingCartStatus.Confirmed);
        shoppingCart.ProductItems.Should().HaveCount(2);
        shoppingCart.ProductItems.Should().Contain(pairOfShoes);
        shoppingCart.ProductItems.Should().Contain(tShirt);

        var shoppingCartShortInfo = database.Get<ShoppingCartShortInfo>(shoppingCartId);
        shoppingCartShortInfo.Should().BeNull();

        // cancelled
        shoppingCart = database.Get<ShoppingCartDetails>(cancelledShoppingCartId)!;
        shoppingCart.Should().NotBeNull();
        shoppingCart.Id.Should().Be(cancelledShoppingCartId);
        shoppingCart.ClientId.Should().Be(clientId);
        shoppingCart.Status.Should().Be(ShoppingCartStatus.Canceled);
        shoppingCart.ProductItems.Should().HaveCount(1);
        shoppingCart.ProductItems.Should().Contain(dress);

        shoppingCartShortInfo = database.Get<ShoppingCartShortInfo>(cancelledShoppingCartId)!;
        shoppingCartShortInfo.Should().BeNull();

        // confirmed but other client
        shoppingCart = database.Get<ShoppingCartDetails>(otherClientShoppingCartId)!;
        shoppingCart.Should().NotBeNull();
        shoppingCart.Id.Should().Be(otherClientShoppingCartId);
        shoppingCart.ClientId.Should().Be(otherClientId);
        shoppingCart.Status.Should().Be(ShoppingCartStatus.Confirmed);
        shoppingCart.ProductItems.Should().HaveCount(1);
        shoppingCart.ProductItems.Should().Contain(dress);

        shoppingCartShortInfo = database.Get<ShoppingCartShortInfo>(otherClientShoppingCartId);
        shoppingCartShortInfo.Should().BeNull();

        // second confirmed
        shoppingCart = database.Get<ShoppingCartDetails>(otherConfirmedShoppingCartId)!;
        shoppingCart.Should().NotBeNull();
        shoppingCart.Id.Should().Be(otherConfirmedShoppingCartId);
        shoppingCart.ClientId.Should().Be(clientId);
        shoppingCart.Status.Should().Be(ShoppingCartStatus.Confirmed);
        shoppingCart.ProductItems.Should().HaveCount(1);
        shoppingCart.ProductItems.Should().Contain(trousers);

        shoppingCartShortInfo = database.Get<ShoppingCartShortInfo>(otherConfirmedShoppingCartId);
        shoppingCartShortInfo.Should().BeNull();

        // first pending
        shoppingCart = database.Get<ShoppingCartDetails>(otherPendingShoppingCartId)!;
        shoppingCart.Should().NotBeNull();
        shoppingCart.Id.Should().Be(otherPendingShoppingCartId);
        shoppingCart.ClientId.Should().Be(clientId);
        shoppingCart.Status.Should().Be(ShoppingCartStatus.Pending);
        shoppingCart.ProductItems.Should().BeEmpty();

        shoppingCartShortInfo = database.Get<ShoppingCartShortInfo>(otherPendingShoppingCartId)!;
        shoppingCartShortInfo.Should().NotBeNull();
        shoppingCartShortInfo.Id.Should().Be(otherPendingShoppingCartId);
        shoppingCartShortInfo.ClientId.Should().Be(clientId);
    }
}


text:
package il

// Type represents a core type in the il system.
type Type uint32

const (
	// Unknown represents a type that is unknown.
	Unknown Type = iota

	// Void represents the void type.
	Void

	// String represents the string type.
	String

	// Integer represents a 64-bit signed integer.
	Integer

	// Double represents a 64-bit signed floating point number.
	Double

	// Bool represents a boolean value.
	Bool

	// StringMap represents a map[string]string value.
	StringMap
)

var typeNames = map[Type]string{
	Unknown:   "unknown",
	Void:      "void",
	String:    "string",
	Integer:   "integer",
	Double:    "double",
	Bool:      "bool",
	StringMap: "stringmap",
}

var typesByName = map[string]Type{
	"void":      Void,
	"string":    String,
	"integer":   Integer,
	"double":    Double,
	"bool":      Bool,
	"stringmap": StringMap,
}

func (t Type) String() string {
	return typeNames[t]
}

// GetType returns the type with the given name, if it exists.
func GetType(name string) (Type, bool) {
	t, f := typesByName[name]
	return t, f
}


text:
title: Xmas Opening Times
date: 2017-12-18 16:35:00 Z
---

Saturday 23rd --10-3 Christmas Eve 12-3.30 Boxing Day 10-4 normal service then resumes


text:
package commands

import (
	"fmt"
	"strings"
	"syscall"

	"github.com/rancher/machine/libmachine"
)

func cmdScp(c CommandLine, api libmachine.API) error {
	args := c.Args()
	if len(args) != 2 {
		c.ShowHelp()
		return errWrongNumberArguments
	}

	src := args[0]
	dest := args[1]

	hostInfoLoader := &storeHostInfoLoader{api}

	cmd, err := getScpCmd(src, dest, c.Bool("recursive"), c.Bool("delta"), c.Bool("quiet"), hostInfoLoader)
	if err != nil {
		return err
	}

	// Default argument escaping is not valid for scp.exe with quoted arguments, so we do it ourselves
	// see golang/go#15566
	cmd.SysProcAttr = &syscall.SysProcAttr{}
	cmd.SysProcAttr.CmdLine = fmt.Sprintf("%s %s", cmd.Path, strings.Join(cmd.Args, " "))

	return runCmdWithStdIo(*cmd)
}


text:
package org.apache.doris.persist;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;

import org.apache.doris.common.io.Text;
import org.apache.doris.common.io.Writable;
import com.google.common.collect.Lists;

public class ClusterInfo implements Writable {

    private String clusterName;
    private long clusterId;
    private int instanceNum;

    private String newClusterName;
    private long newClusterId;
    private int newInstanceNum;

    private List<Long> expandBackendIds = Lists.newArrayList();

    public ClusterInfo() {
        this.clusterName = "";
        this.clusterId = 0L;
        this.instanceNum = 0;
        this.newClusterName = "";
        this.newClusterId = 0L;
        this.newInstanceNum = 0;
    }

    public ClusterInfo(String clusterName, long clusterId) {
        this.clusterName = clusterName;
        this.clusterId = clusterId;
        this.instanceNum = 0;
        this.newClusterName = "";
        this.newClusterId = 0L;
        this.newInstanceNum = 0;
    }

    public ClusterInfo(String clusterName, long clusterId, List<Long> expandBackendIds) {
        this.clusterName = clusterName;
        this.clusterId = clusterId;
        this.expandBackendIds = expandBackendIds;
        this.instanceNum = 0;
        this.newClusterName = "";
        this.newClusterId = 0L;
        this.newInstanceNum = 0;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        Text.writeString(out, clusterName);
        out.writeLong(clusterId);
        out.writeInt(instanceNum);
        out.writeInt(expandBackendIds.size());
        for (long id : expandBackendIds) {
            out.writeLong(id);
        }
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        clusterName = Text.readString(in);
        clusterId = in.readLong();
        instanceNum = in.readInt();
        int count = in.readInt();
        while (count-- > 0) {
            expandBackendIds.add(in.readLong());
        }
    }

    public String getClusterName() {
        return clusterName;
    }

    public long getClusterId() {
        return clusterId;
    }

    public int getInstanceNum() {
        return instanceNum;
    }

    public String getNewClusterName() {
        return newClusterName;
    }

    public int getNewInstanceNum() {
        return newInstanceNum;
    }

    public List<Long> getBackendIdList() {
        return expandBackendIds;
    }
}


text:
using namespace CppCommon;
using namespace CppServer::Asio;

namespace {

class EchoSSLService : public Service
{
public:
    using Service::Service;

protected:
    void onThreadInitialize() override { thread_initialize = true; }
    void onThreadCleanup() override { thread_cleanup = true; }
    void onStarted() override { started = true; }
    void onStopped() override { stopped = true; }
    void onIdle() override { idle = true; }
    void onError(int error, const std::string& category, const std::string& message) override { errors = true; }

public:
    std::atomic<bool> thread_initialize{false};
    std::atomic<bool> thread_cleanup{false};
    std::atomic<bool> started{false};
    std::atomic<bool> stopped{false};
    std::atomic<bool> idle{false};
    std::atomic<bool> errors{false};
};

class EchoSSLClient : public SSLClient
{
public:
    using SSLClient::SSLClient;

    static std::shared_ptr<SSLContext> CreateContext()
    {
        auto context = std::make_shared<SSLContext>(asio::ssl::context::tlsv12);
        context->set_default_verify_paths();
        context->set_root_certs();
        context->set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
        context->load_verify_file("../tools/certificates/ca.pem");
        return context;
    }

protected:
    void onConnected() override { connected = true; }
    void onHandshaked() override { handshaked = true; }
    void onDisconnected() override { disconnected = true; }
    void onError(int error, const std::string& category, const std::string& message) override { errors = true; }

public:
    std::atomic<bool> connected{false};
    std::atomic<bool> handshaked{false};
    std::atomic<bool> disconnected{false};
    std::atomic<bool> errors{false};
};

class EchoSSLSession : public SSLSession
{
public:
    using SSLSession::SSLSession;

protected:
    void onConnected() override { connected = true; }
    void onHandshaked() override { handshaked = true; }
    void onDisconnected() override { disconnected = true; }
    void onReceived(const void* buffer, size_t size) override { SendAsync(buffer, size); }
    void onError(int error, const std::string& category, const std::string& message) override { errors = true; }

public:
    std::atomic<bool> connected{false};
    std::atomic<bool> handshaked{false};
    std::atomic<bool> disconnected{false};
    std::atomic<bool> errors{false};
};

class EchoSSLServer : public SSLServer
{
public:
    using SSLServer::SSLServer;

    static std::shared_ptr<SSLContext> CreateContext()
    {
        auto context = std::make_shared<SSLContext>(asio::ssl::context::tlsv12);
        context->set_password_callback([](size_t max_length, asio::ssl::context::password_purpose purpose) -> std::string { return "qwerty"; });
        context->use_certificate_chain_file("../tools/certificates/server.pem");
        context->use_private_key_file("../tools/certificates/server.pem", asio::ssl::context::pem);
        context->use_tmp_dh_file("../tools/certificates/dh4096.pem");
        return context;
    }

protected:
    std::shared_ptr<SSLSession> CreateSession(const std::shared_ptr<SSLServer>& server) override { return std::make_shared<EchoSSLSession>(server); }

protected:
    void onStarted() override { started = true; }
    void onStopped() override { stopped = true; }
    void onConnected(std::shared_ptr<SSLSession>& session) override { connected = true; }
    void onHandshaked(std::shared_ptr<SSLSession>& session) override { handshaked = true; ++clients; }
    void onDisconnected(std::shared_ptr<SSLSession>& session) override { disconnected = true; --clients; }
    void onError(int error, const std::string& category, const std::string& message) override { errors = true; }

public:
    std::atomic<bool> started{false};
    std::atomic<bool> stopped{false};
    std::atomic<bool> connected{false};
    std::atomic<bool> handshaked{false};
    std::atomic<bool> disconnected{false};
    std::atomic<size_t> clients{0};
    std::atomic<bool> errors{false};
};

} // namespace

TEST_CASE("SSL server test", "[CppServer][SSL]")
{
    const std::string address = "127.0.0.1";
    const int port = 2222;

    // Create and start Asio service
    auto service = std::make_shared<EchoSSLService>();
    REQUIRE(service->Start());
    while (!service->IsStarted())
        Thread::Yield();

    // Create and prepare a new SSL server context
    auto server_context = EchoSSLServer::CreateContext();

    // Create and start Echo server
    auto server = std::make_shared<EchoSSLServer>(service, server_context, port);
    REQUIRE(server->Start());
    while (!server->IsStarted())
        Thread::Yield();

    // Create and prepare a new SSL client context
    auto client_context = EchoSSLServer::CreateContext();

    // Create and connect Echo client
    auto client = std::make_shared<EchoSSLClient>(service, client_context, address, port);
    REQUIRE(client->ConnectAsync());
    while (!client->IsConnected() || !client->IsHandshaked() || (server->clients != 1))
        Thread::Yield();

    // Send a message to the Echo server
    client->SendAsync("test");

    // Wait for all data processed...
    while (client->bytes_received() != 4)
        Thread::Yield();

    // Disconnect the Echo client
    REQUIRE(client->DisconnectAsync());
    while (client->IsConnected() || client->IsHandshaked() || (server->clients != 0))
        Thread::Yield();

    // Stop the Echo server
    REQUIRE(server->Stop());
    while (server->IsStarted())
        Thread::Yield();

    // Stop the Asio service
    REQUIRE(service->Stop());
    while (service->IsStarted())
        Thread::Yield();

    // Check the Asio service state
    REQUIRE(service->thread_initialize);
    REQUIRE(service->thread_cleanup);
    REQUIRE(service->started);
    REQUIRE(service->stopped);
    REQUIRE(!service->idle);
    REQUIRE(!service->errors);

    // Check the Echo server state
    REQUIRE(server->started);
    REQUIRE(server->stopped);
    REQUIRE(server->connected);
    REQUIRE(server->handshaked);
    REQUIRE(server->disconnected);
    REQUIRE(server->bytes_sent() == 4);
    REQUIRE(server->bytes_received() == 4);
    REQUIRE(!server->errors);

    // Check the Echo client state
    REQUIRE(client->connected);
    REQUIRE(client->handshaked);
    REQUIRE(client->disconnected);
    REQUIRE(client->bytes_sent() == 4);
    REQUIRE(client->bytes_received() == 4);
    REQUIRE(!client->errors);
}

TEST_CASE("SSL server multicast test", "[CppServer][SSL]")
{
    const std::string address = "127.0.0.1";
    const int port = 2223;

    // Create and start Asio service
    auto service = std::make_shared<EchoSSLService>();
    REQUIRE(service->Start(true));
    while (!service->IsStarted())
        Thread::Yield();

    // Create and prepare a new SSL server context
    auto server_context = EchoSSLServer::CreateContext();

    // Create and start Echo server
    auto server = std::make_shared<EchoSSLServer>(service, server_context, port);
    REQUIRE(server->Start());
    while (!server->IsStarted())
        Thread::Yield();

    // Create and prepare a new SSL client context
    auto client_context = EchoSSLClient::CreateContext();

    // Create and connect Echo client
    auto client1 = std::make_shared<EchoSSLClient>(service, client_context, address, port);
    REQUIRE(client1->ConnectAsync());
    while (!client1->IsConnected() || !client1->IsHandshaked() || (server->clients != 1))
        Thread::Yield();

    // Multicast some data to all clients
    server->Multicast("test");

    // Wait for all data processed...
    while (client1->bytes_received() != 4)
        Thread::Yield();

    // Create and connect Echo client
    auto client2 = std::make_shared<EchoSSLClient>(service, client_context, address, port);
    REQUIRE(client2->ConnectAsync());
    while (!client2->IsConnected() || !client2->IsHandshaked() || (server->clients != 2))
        Thread::Yield();

    // Multicast some data to all clients
    server->Multicast("test");

    // Wait for all data processed...
    while ((client1->bytes_received() != 8) || (client2->bytes_received() != 4))
        Thread::Yield();

    // Create and connect Echo client
    auto client3 = std::make_shared<EchoSSLClient>(service, client_context, address, port);
    REQUIRE(client3->ConnectAsync());
    while (!client3->IsConnected() || !client3->IsHandshaked() || (server->clients != 3))
        Thread::Yield();

    // Multicast some data to all clients
    server->Multicast("test");

    // Wait for all data processed...
    while ((client1->bytes_received() != 12) || (client2->bytes_received() != 8) || (client3->bytes_received() != 4))
        Thread::Yield();

    // Disconnect the Echo client
    REQUIRE(client1->DisconnectAsync());
    while (client1->IsConnected() || client1->IsHandshaked() || (server->clients != 2))
        Thread::Yield();

    // Multicast some data to all clients
    server->Multicast("test");

    // Wait for all data processed...
    while ((client1->bytes_received() != 12) || (client2->bytes_received() != 12) || (client3->bytes_received() != 8))
        Thread::Yield();

    // Disconnect the Echo client
    REQUIRE(client2->DisconnectAsync());
    while (client2->IsConnected() || client2->IsHandshaked() || (server->clients != 1))
        Thread::Yield();

    // Multicast some data to all clients
    server->Multicast("test");

    // Wait for all data processed...
    while ((client1->bytes_received() != 12) || (client2->bytes_received() != 12) || (client3->bytes_received() != 12))
        Thread::Yield();

    // Disconnect the Echo client
    REQUIRE(client3->DisconnectAsync());
    while (client3->IsConnected() || client3->IsHandshaked() || (server->clients != 0))
        Thread::Yield();

    // Stop the Echo server
    REQUIRE(server->Stop());
    while (server->IsStarted())
        Thread::Yield();

    // Stop the Asio service
    REQUIRE(service->Stop());
    while (service->IsStarted())
        Thread::Yield();

    // Check the Asio service state
    REQUIRE(service->thread_initialize);
    REQUIRE(service->thread_cleanup);
    REQUIRE(service->started);
    REQUIRE(service->stopped);
    REQUIRE(service->idle);
    REQUIRE(!service->errors);

    // Check the Echo server state
    REQUIRE(server->started);
    REQUIRE(server->stopped);
    REQUIRE(server->connected);
    REQUIRE(server->handshaked);
    REQUIRE(server->disconnected);
    REQUIRE(server->bytes_sent() == 36);
    REQUIRE(server->bytes_received() == 0);
    REQUIRE(!server->errors);

    // Check the Echo client state
    REQUIRE(client1->bytes_sent() == 0);
    REQUIRE(client2->bytes_sent() == 0);
    REQUIRE(client3->bytes_sent() == 0);
    REQUIRE(client1->bytes_received() == 12);
    REQUIRE(client2->bytes_received() == 12);
    REQUIRE(client3->bytes_received() == 12);
    REQUIRE(!client1->errors);
    REQUIRE(!client2->errors);
    REQUIRE(!client3->errors);
}

TEST_CASE("SSL server random test", "[CppServer][SSL]")
{
    const std::string address = "127.0.0.1";
    const int port = 2224;

    // Create and start Asio service
    auto service = std::make_shared<EchoSSLService>();
    REQUIRE(service->Start());
    while (!service->IsStarted())
        Thread::Yield();

    // Create and prepare a new SSL server context
    auto server_context = EchoSSLServer::CreateContext();

    // Create and start Echo server
    auto server = std::make_shared<EchoSSLServer>(service, server_context, port);
    REQUIRE(server->Start());
    while (!server->IsStarted())
        Thread::Yield();

    // Test duration in seconds
    const int duration = 10;

    // Create and prepare a new SSL client context
    auto client_context = EchoSSLClient::CreateContext();

    // Clients collection
    std::vector<std::shared_ptr<EchoSSLClient>> clients;

    // Start random test
    auto start = std::chrono::high_resolution_clock::now();
    while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start).count() < duration)
    {
        // Disconnect all clients
        if ((rand() % 1000) == 0)
        {
            server->DisconnectAll();
        }
        // Create a new client and connect
        else if ((rand() % 100) == 0)
        {
            if (clients.size() < 100)
            {
                // Create and connect Echo client
                auto client = std::make_shared<EchoSSLClient>(service, client_context, address, port);
                clients.emplace_back(client);
                client->ConnectAsync();
                while (!client->IsHandshaked())
                    Thread::Yield();
            }
        }
        // Connect/Disconnect the random client
        else if ((rand() % 100) == 0)
        {
            if (!clients.empty())
            {
                size_t index = rand() % clients.size();
                auto client = clients.at(index);
                if (client->IsHandshaked())
                {
                    client->DisconnectAsync();
                    while (client->IsConnected())
                        Thread::Yield();
                }
                else if (!client->IsConnected())
                {
                    client->ConnectAsync();
                    while (!client->IsHandshaked())
                        Thread::Yield();
                }
            }
        }
        // Reconnect the random client
        else if ((rand() % 100) == 0)
        {
            if (!clients.empty())
            {
                size_t index = rand() % clients.size();
                auto client = clients.at(index);
                if (client->IsHandshaked())
                {
                    client->ReconnectAsync();
                    while (!client->IsHandshaked())
                        Thread::Yield();
                }
            }
        }
        // Multicast a message to all clients
        else if ((rand() % 10) == 0)
        {
            server->Multicast("test");
        }
        // Send a message from the random client
        else if ((rand() % 1) == 0)
        {
            if (!clients.empty())
            {
                size_t index = rand() % clients.size();
                auto client = clients.at(index);
                if (client->IsHandshaked())
                    client->SendAsync("test");
            }
        }

        // Sleep for a while...
        Thread::Sleep(1);
    }

    // Disconnect clients
    for (auto& client : clients)
    {
        client->DisconnectAsync();
        while (client->IsConnected())
            Thread::Yield();
    }

    // Stop the Echo server
    REQUIRE(server->Stop());
    while (server->IsStarted())
        Thread::Yield();

    // Stop the Asio service
    REQUIRE(service->Stop());
    while (service->IsStarted())
        Thread::Yield();

    // Check the Echo server state
    REQUIRE(server->started);
    REQUIRE(server->stopped);
    REQUIRE(server->connected);
    REQUIRE(server->handshaked);
    REQUIRE(server->disconnected);
    REQUIRE(server->bytes_sent() > 0);
    REQUIRE(server->bytes_received() > 0);
    REQUIRE(!server->errors);
}


text:
INSERT INTO `lh_chat_config` (`identifier`, `value`, `type`, `explain`, `hidden`)
VALUES ('list_online_operators', '0', '0', 'List online operators, 0 - no, 1 - yes.', '0');


text:
package com.google.javascript.jscomp.parsing.parser.trees;

import com.google.javascript.jscomp.parsing.parser.util.SourceRange;
import javax.annotation.Nullable;

/** Tree for public comptuted property fields */
public class ComputedPropertyFieldTree extends ParseTree {
  public final ParseTree property;
  public final boolean isStatic;
  @Nullable public final ParseTree initializer;

  public ComputedPropertyFieldTree(
      SourceRange location, ParseTree property, boolean isStatic, ParseTree initializer) {
    super(ParseTreeType.COMPUTED_PROPERTY_FIELD, location);
    this.property = property;
    this.isStatic = isStatic;
    this.initializer = initializer;
  }
}


text:
namespace Mirage.Urbanization.ZoneConsumption.Base
{
    public interface IConsumeAreaOperation
    {
        IGetCanOverrideWithResult CanOverrideWithResult { get; }
        void Apply();
        string Description { get; }
    }
}


text:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../helpers/start-app';
import { stubRequest } from 'ember-cli-fake-server';
import { orgId, rolesHref, usersHref, invitationsHref, securityOfficerId,
         securityOfficerHref } from '../../helpers/organization-stub';

let application;
let teamUrl = `/gridiron/${orgId}/admin/setup/team`;
let userId = 'basic-user-1';
let developerId = 'developer-user-2';
let basicRoleId = 'basic-role-1';
let developerRoleId = 'developer-role-2';
let platformOwnerId = 'platform-owner-role-3';
let complianceOwnerId = 'compliance-owner-role-4';
let users = [
  {
    id: userId,
    name: 'Basic User',
    email: 'basicuser@asdf.com',
    _links: {
      self: { href: `/users/${userId}` }
    }
  },
  {
    id: developerId,
    name: 'Developer User',
    email: 'developeruser@asdf.com',
    _links: {
      self: { href: `/users/${developerId}` }
    }
  },
  {
    id: securityOfficerId,
    name: 'Security Officer User',
    email: 'securityofficeruser@asdf.com',
    _links: {
      self: { href: `/users/${securityOfficerId}` }
    }
  }
];

let roles = [
  {
    id: basicRoleId,
    type: 'platform_user',
    name: 'Basic Role',
    _links: {
      self: { href: `/roles/${basicRoleId}` },
      users: { href: `/roles/${basicRoleId}/users`}
    }
  },
  {
    id: developerRoleId,
    type: 'platform_user',
    name: 'Developer Role',
    _links: {
      self: { href: `/roles/${developerRoleId}` },
      users: { href: `/roles/${developerRoleId}/users`}
    }
  },
  {
    id: platformOwnerId,
    type: 'platform_owner',
    name: 'Platform Owner',
    _links: {
      self: { href: `/roles/${platformOwnerId}` },
      users: { href: `/roles/${platformOwnerId}/users`}
    }
  },
  {
    id: complianceOwnerId,
    type: 'compliance_owner',
    name: 'Compliance Owner',
    _links: {
      self: { href: `/roles/${complianceOwnerId}` },
      users: { href: `/roles/${complianceOwnerId}/users`}
    }
  }
];

let invitations = [
  {
    id: 'invite-1',
    role_id: basicRoleId,
    inviter_id: users[0].id,
    email: 'newuser1@aptible.com',
    created_at: '2015-11-03T20:34:06.963Z'
  },
  {
    id: 'invite-2',
    role_id: basicRoleId,
    inviter_id: users[0].id,
    email: 'newuser2@aptible.com',
    created_at: '2015-11-03T20:34:06.963Z'
  }
];

let permissions = [
  {
    id: '1',
    scope: 'manage',
    _links: {
      role: { href: `/roles/${developerRoleId}` }
    }
  },
  {
    id: '2',
    scope: 'read',
    _links: {
      role: { href: `/roles/${basicRoleId}` }
    }
  }
];

module('Acceptance: Setup: Team', {
  beforeEach() {
    application = startApp();
  },

  afterEach() {
    Ember.run(application, 'destroy');
  }
});

test('You are redirected to correct step if not ready for team step', function(assert) {
  stubCurrentAttestations({ workforce_roles: [] });
  stubProfile({ currentStep: 'organization' });
  stubRequests();
  signInAndVisit(teamUrl);

  andThen(() => {
    assert.equal(currentPath(), 'requires-authorization.gridiron.gridiron-organization.gridiron-admin.gridiron-setup.organization', 'redirected to organization step');
  });
});

test('Clicking back should return you to previous step', function(assert) {
  stubCurrentAttestations({ workforce_roles: [], workforce_locations: [] });
  stubProfile({ currentStep: 'team' });
  stubRequests();
  signInAndVisit(teamUrl);

  stubRequest('put', `/organization_profiles/${orgId}`, function(request) {
    let json = this.json(request);
    json.id = orgId;
    return this.success(json);
  });

  andThen(() => {
    find('.spd-nav-back').click();
  });

  andThen(() => {
    assert.equal(currentPath(), 'requires-authorization.gridiron.gridiron-organization.gridiron-admin.gridiron-setup.locations', 'returned to locations step');
  });
});

function stubRequests() {
  stubValidOrganization({ features: ['spd'] });
  stubSchemasAPI();
  stubCriterionDocuments({});
  stubStacks();
  stubCriteria();

  stubRequest('get', `/roles/${developerRoleId}/users`, function() {
    return this.success({ _embedded: { users: [users[1]] }});
  });

  stubRequest('get', rolesHref, function() {
    return this.success({ _embedded: { roles } });
  });

  stubRequest('get', usersHref, function() {
    return this.success({ _embedded: { users }});
  });

  stubRequest('get', invitationsHref, function() {
    return this.success({ _embedded: { invitations }});
  });

  stubRequest('get', securityOfficerHref, function() {
    return this.success(users[2]);
  });

  stubRequest('get', '/permissions', function() {
    return this.success({ _embedded: { permissions }});
  });
}