text:
using CppAD::AD;

// TODO: Set the timestep length and duration
size_t N = 10;
double dt = 0.1;

// This value assumes the model presented in the classroom is used.
//
// It was obtained by measuring the radius formed by running the vehicle in the
// simulator around in a circle with a constant steering angle and velocity on a
// flat terrain.
//
// Lf was tuned until the the radius formed by the simulating the model
// presented in the classroom matched the previous radius.
//
// This is the length from front to CoG that has a similar radius.
const double Lf = 2.67;

const double ref_cte = 0;
const double ref_epsi = 0;
const double ref_v = 100;

const size_t x_start = 0;
const size_t y_start = x_start + N;
const size_t psi_start = y_start + N;
const size_t v_start = psi_start + N;
const size_t cte_start = v_start + N;
const size_t epsi_start = cte_start + N;
const size_t delta_start = epsi_start + N;
const size_t a_start = delta_start + N - 1;

class FG_eval {
 public:
  // Fitted polynomial coefficients
  Eigen::VectorXd coeffs;
  FG_eval(Eigen::VectorXd coeffs) { this->coeffs = coeffs; }

  typedef CPPAD_TESTVECTOR(AD<double>) ADvector;
  void operator()(ADvector& fg, const ADvector& vars) {
    // TODO: implement MPC
    // `fg` a vector of the cost constraints, `vars` is a vector of variable values (state & actuators)
    // NOTE: You'll probably go back and forth between this function and
    // the Solver function below.

    // The cost is stored is the first element of `fg`.
    // Any additions to the cost should be added to `fg[0]`.
    fg[0] = 0;

     // The part of the cost based on the reference state.
    for( int i = 0; i < N; i++ ) {
      fg[0] += 1000*CppAD::pow(vars[cte_start + i] - ref_cte, 2);
      fg[0] += 1000*CppAD::pow(vars[epsi_start + i] - ref_epsi, 2);
      fg[0] += CppAD::pow(vars[v_start + i] - ref_v, 2);
    }

    // Minimize the use of actuators.
    for (int i = 0; i< N - 1; i++) {
      fg[0] += 50*CppAD::pow(vars[delta_start + i], 2);
      fg[0] += 50*CppAD::pow(vars[a_start + i], 2);
    }

    // Minimize the value gap between sequential actuations.
    // (how smooth the actuations are)
    for (int i = 0; i < N - 2; i++) {
      fg[0] += 250000*CppAD::pow(vars[delta_start + i + 1] - vars[delta_start + i], 2);
      fg[0] += 5000*CppAD::pow(vars[a_start + i + 1] - vars[a_start + i], 2);
    }

    // Initial constraints.
    fg[1 + x_start] = vars[x_start];
    fg[1 + y_start] = vars[y_start];
    fg[1 + psi_start] = vars[psi_start];
    fg[1 + v_start] = vars[v_start];
    fg[1 + cte_start] = vars[cte_start];
    fg[1 + epsi_start] = vars[epsi_start];

    for (int t = 1; t < N; t++) {
      // The state at time t+1 .
      AD<double> x1 = vars[x_start + t];
      AD<double> y1 = vars[y_start + t];
      AD<double> psi1 = vars[psi_start + t];
      AD<double> v1 = vars[v_start + t];
      AD<double> cte1 = vars[cte_start + t];
      AD<double> epsi1 = vars[epsi_start + t];

      // The state at time t.
      AD<double> x0 = vars[x_start + t - 1];
      AD<double> y0 = vars[y_start + t - 1];
      AD<double> psi0 = vars[psi_start + t - 1];
      AD<double> v0 = vars[v_start + t - 1];
      AD<double> cte0 = vars[cte_start + t - 1];
      AD<double> epsi0 = vars[epsi_start + t - 1];

      // Only consider the actuation at time t.
      AD<double> delta0 = vars[delta_start + t - 1];
      AD<double> a0 = vars[a_start + t - 1];

      AD<double> f0 = coeffs[0] + coeffs[1] * x0 + coeffs[2] * CppAD::pow(x0, 2) + coeffs[3] * CppAD::pow(x0, 3);
      AD<double> psides0 = CppAD::atan(coeffs[1] + 2 * coeffs[2] * x0 + 3 * coeffs[3] * CppAD::pow(x0, 2));

      // Here's `x` to get you started.
      // The idea here is to constraint this value to be 0.
      //
      // Recall the equations for the model:
      // x_[t] = x[t-1] + v[t-1] * cos(psi[t-1]) * dt
      // y_[t] = y[t-1] + v[t-1] * sin(psi[t-1]) * dt
      // psi_[t] = psi[t-1] + v[t-1] / Lf * delta[t-1] * dt
      // v_[t] = v[t-1] + a[t-1] * dt
      // cte[t] = f(x[t-1]) - y[t-1] + v[t-1] * sin(epsi[t-1]) * dt
      // epsi[t] = psi[t] - psides[t-1] + v[t-1] * delta[t-1] / Lf * dt
      fg[1 + x_start + t] = x1 - (x0 + v0 * CppAD::cos(psi0) * dt);
      fg[1 + y_start + t] = y1 - (y0 + v0 * CppAD::sin(psi0) * dt);
      fg[1 + psi_start + t] = psi1 - (psi0 - v0 / Lf * delta0 * dt);
      fg[1 + v_start + t] = v1 - (v0 + a0 * dt);
      fg[1 + cte_start + t] = cte1 - ((f0 - y0) + (v0 * CppAD::sin(epsi0) * dt));
      fg[1 + epsi_start + t] = epsi1 - ((psi0 - psides0) - v0 / Lf * delta0 * dt);
    }
  }
};

//
// MPC class definition implementation.
//
MPC::MPC() {}
MPC::~MPC() {}

vector<double> MPC::Solve(Eigen::VectorXd state, Eigen::VectorXd coeffs) {
  bool ok = true;
  // size_t i;
  typedef CPPAD_TESTVECTOR(double) Dvector;

  const double x = state[0];
  const double y = state[1];
  const double psi = state[2];
  const double v = state[3];
  const double cte = state[4];
  const double epsi = state[5];

  // TODO: Set the number of model variables (includes both states and inputs).
  // For example: If the state is a 4 element vector, the actuators is a 2
  // element vector and there are 10 timesteps. The number of variables is:
  //
  // 4 * 10 + 2 * 9
  const size_t n_vars = N * 6 + (N - 1) * 2;
  // TODO: Set the number of constraints
  const size_t n_constraints = N * 6;

  // Initial value of the independent variables.
  // SHOULD BE 0 besides initial state.
  Dvector vars(n_vars);
  for (int i = 0; i < n_vars; i++) {
    vars[i] = 0;
  }

  Dvector vars_lowerbound(n_vars);
  Dvector vars_upperbound(n_vars);
  // TODO: Set lower and upper limits for variables.
  // Set the initial variable values

  // Set all non-actuators upper and lower limits
  // to the max negative and positive values.
  for ( int i = 0; i < delta_start; i++ ) {
    vars_lowerbound[i] = -1.0e19;
    vars_upperbound[i] = 1.0e19;
  }

  // The upper and lower limits of delta are set to -25 to 25
  // degrees (values in radians).
  for ( int i = delta_start; i < a_start; i++ ) {
    vars_lowerbound[i] = -0.436332*Lf;
    vars_upperbound[i] = 0.43632*Lf;
  }

  // Actuator limits.
  for ( int i = a_start; i < n_vars; i++ ) {
    vars_lowerbound[i] = -1.0;
    vars_upperbound[i] = 1.0;
  }

  // Lower and upper limits for the constraints
  // Should be 0 besides initial state.
  Dvector constraints_lowerbound(n_constraints);
  Dvector constraints_upperbound(n_constraints);
  for (int i = 0; i < n_constraints; i++) {
    constraints_lowerbound[i] = 0;
    constraints_upperbound[i] = 0;
  }

  constraints_lowerbound[x_start] = x;
  constraints_lowerbound[y_start] = y;
  constraints_lowerbound[psi_start] = psi;
  constraints_lowerbound[v_start] = v;
  constraints_lowerbound[cte_start] = cte;
  constraints_lowerbound[epsi_start] = epsi;

  constraints_upperbound[x_start] = x;
  constraints_upperbound[y_start] = y;
  constraints_upperbound[psi_start] = psi;
  constraints_upperbound[v_start] = v;
  constraints_upperbound[cte_start] = cte;
  constraints_upperbound[epsi_start] = epsi;

  // object that computes objective and constraints
  FG_eval fg_eval(coeffs);

  //
  // NOTE: You don't have to worry about these options
  //
  // options for IPOPT solver
  std::string options;
  // Uncomment this if you'd like more print information
  options += "Integer print_level  0\n";
  // NOTE: Setting sparse to true allows the solver to take advantage
  // of sparse routines, this makes the computation MUCH FASTER. If you
  // can uncomment 1 of these and see if it makes a difference or not but
  // if you uncomment both the computation time should go up in orders of
  // magnitude.
  options += "Sparse  true        forward\n";
  options += "Sparse  true        reverse\n";
  // NOTE: Currently the solver has a maximum time limit of 0.5 seconds.
  // Change this as you see fit.
  options += "Numeric max_cpu_time          0.5\n";

  // place to return solution
  CppAD::ipopt::solve_result<Dvector> solution;

  // solve the problem
  CppAD::ipopt::solve<Dvector, FG_eval>(
      options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound,
      constraints_upperbound, fg_eval, solution);

  // Check some of the solution values
  ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success;

  // Cost
  // auto cost = solution.obj_value;
  // std::cout << "Cost " << cost << std::endl;

  // TODO: Return the first actuator values. The variables can be accessed with
  // `solution.x[i]`.
  //
  // {...} is shorthand for creating a vector, so auto x1 = {1.0,2.0}
  // creates a 2 element double vector.
  vector<double> result;

  result.push_back(solution.x[delta_start]);
  result.push_back(solution.x[a_start]);

  for ( int i = 0; i < N - 2; i++ ) {
    result.push_back(solution.x[x_start + i + 1]);
    result.push_back(solution.x[y_start + i + 1]);
  }
  return result;
}


text:
import { factory } from '../../../utils/factory.js'
import { DimensionError } from '../../../error/DimensionError.js'

const name = 'matAlgo13xDD'
const dependencies = ['typed']

export const createMatAlgo13xDD = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
  /**
   * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
   * Callback function invoked MxN times.
   *
   * C(i,j,...z) = f(Aij..z, Bij..z)
   *
   * @param {Matrix}   a                 The DenseMatrix instance (A)
   * @param {Matrix}   b                 The DenseMatrix instance (B)
   * @param {Function} callback          The f(Aij..z,Bij..z) operation to invoke
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
   */
  return function matAlgo13xDD (a, b, callback) {
    // a arrays
    const adata = a._data
    const asize = a._size
    const adt = a._datatype
    // b arrays
    const bdata = b._data
    const bsize = b._size
    const bdt = b._datatype
    // c arrays
    const csize = []

    // validate dimensions
    if (asize.length !== bsize.length) { throw new DimensionError(asize.length, bsize.length) }

    // validate each one of the dimension sizes
    for (let s = 0; s < asize.length; s++) {
      // must match
      if (asize[s] !== bsize[s]) { throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')') }
      // update dimension in c
      csize[s] = asize[s]
    }

    // datatype
    let dt
    // callback signature to use
    let cf = callback

    // process data types
    if (typeof adt === 'string' && adt === bdt) {
      // datatype
      dt = adt
      // callback
      cf = typed.find(callback, [dt, dt])
    }

    // populate cdata, iterate through dimensions
    const cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []

    // c matrix
    return a.createDenseMatrix({
      data: cdata,
      size: csize,
      datatype: dt
    })
  }

  // recursive function
  function _iterate (f, level, s, n, av, bv) {
    // initialize array for this level
    const cv = []
    // check we reach the last level
    if (level === s.length - 1) {
      // loop arrays in last level
      for (let i = 0; i < n; i++) {
        // invoke callback and store value
        cv[i] = f(av[i], bv[i])
      }
    } else {
      // iterate current level
      for (let j = 0; j < n; j++) {
        // iterate next level
        cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j])
      }
    }
    return cv
  }
})

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include "tasks.h"
#include "bgfetcher.h"
#include "ep_bucket.h"
#include "ep_engine.h"
#include "executorpool.h"
#include "flusher.h"
#include "warmup.h"

#include <climits>
#include <type_traits>

#include <phosphor/phosphor.h>

static const double WORKLOAD_MONITOR_FREQ(5.0);

bool FlusherTask::run() {
    return flusher->step(this);
}

CompactTask::CompactTask(EPBucket& bucket,
                         const CompactionConfig& c,
                         uint64_t purgeSeqno,
                         const void* ck,
                         bool completeBeforeShutdown)
    : GlobalTask(&bucket.getEPEngine(),
                 TaskId::CompactVBucketTask,
                 0,
                 completeBeforeShutdown),
      bucket(bucket),
      compactionConfig(c),
      purgeSeqno(purgeSeqno),
      cookie(ck) {
    desc = "Compact DB file " +
           std::to_string(compactionConfig.db_file_id.get());
}

bool CompactTask::run() {
    TRACE_EVENT1("ep-engine/task",
                 "CompactTask",
                 "file_id",
                 compactionConfig.db_file_id.get());

    /**
     * MB-30015: Check to see if tombstones that have invalid
     * data needs to be retained. The goal is to try and retain
     * the erroneous tombstones especially in customer environments
     * for further analysis
     */
    compactionConfig.retain_erroneous_tombstones =
                             bucket.isRetainErroneousTombstones();
    return bucket.doCompact(compactionConfig, purgeSeqno, cookie);
}

bool StatSnap::run() {
    TRACE_EVENT0("ep-engine/task", "StatSnap");
    engine->getKVBucket()->snapshotStats();
    if (runOnce) {
        return false;
    }
    ExecutorPool::get()->snooze(uid, 60);
    return true;
}

MultiBGFetcherTask::MultiBGFetcherTask(EventuallyPersistentEngine* e,
                                       BgFetcher* b)
    : GlobalTask(e,
                 TaskId::MultiBGFetcherTask,
                 /*sleeptime*/ INT_MAX,
                 /*completeBeforeShutdown*/ false),
      bgfetcher(b) {
}

bool MultiBGFetcherTask::run() {
    TRACE_EVENT0("ep-engine/task", "MultiBGFetcherTask");
    return bgfetcher->run(this);
}

bool VKeyStatBGFetchTask::run() {
    TRACE_EVENT2("ep-engine/task",
                 "VKeyStatBGFetchTask",
                 "cookie",
                 cookie,
                 "vb",
                 vbucket.get());
    engine->getKVBucket()->completeStatsVKey(cookie, key, vbucket, bySeqNum);
    return false;
}

WorkLoadMonitor::WorkLoadMonitor(EventuallyPersistentEngine *e,
                                 bool completeBeforeShutdown) :
    GlobalTask(e, TaskId::WorkLoadMonitor, WORKLOAD_MONITOR_FREQ,
               completeBeforeShutdown) {
    prevNumMutations = getNumMutations();
    prevNumGets = getNumGets();
}

size_t WorkLoadMonitor::getNumMutations() {
    return engine->getEpStats().numOpsStore +
           engine->getEpStats().numOpsDelete +
           engine->getEpStats().numOpsSetMeta +
           engine->getEpStats().numOpsDelMeta +
           engine->getEpStats().numOpsSetRetMeta +
           engine->getEpStats().numOpsDelRetMeta;
}

size_t WorkLoadMonitor::getNumGets() {
    return engine->getEpStats().numOpsGet +
           engine->getEpStats().numOpsGetMeta;
}

bool WorkLoadMonitor::run() {
    size_t curr_num_mutations = getNumMutations();
    size_t curr_num_gets = getNumGets();
    auto delta_mutations = static_cast<double>(curr_num_mutations -
                                                 prevNumMutations);
    auto delta_gets = static_cast<double>(curr_num_gets - prevNumGets);
    double total_delta_ops = delta_gets + delta_mutations;
    double read_ratio = 0;

    if (total_delta_ops) {
        read_ratio = delta_gets / total_delta_ops;
        if (read_ratio < 0.4) {
            engine->getWorkLoadPolicy().setWorkLoadPattern(WRITE_HEAVY);
        } else if (read_ratio >= 0.4 && read_ratio <= 0.6) {
            engine->getWorkLoadPolicy().setWorkLoadPattern(MIXED);
        } else {
            engine->getWorkLoadPolicy().setWorkLoadPattern(READ_HEAVY);
        }
    }
    prevNumMutations = curr_num_mutations;
    prevNumGets = curr_num_gets;

    snooze(WORKLOAD_MONITOR_FREQ);
    if (engine->getEpStats().isShutdown) {
        return false;
    }
    return true;
}


text:
import * as R from '../ramda/dist/index';

declare const object_number_to_boolean: (x: object, y: number) => boolean;
declare const object_array: object[];
declare const number_array: number[];

// @dts-jest:pass:snap
R.innerJoin(object_number_to_boolean, object_array);
// @dts-jest:pass:snap
R.innerJoin(object_number_to_boolean, object_array, number_array);
// @dts-jest:pass:snap
R.innerJoin(object_number_to_boolean)(object_array)(number_array);


text:
module FHIR
    module Deserializer
        module DeviceObservationReport
        include FHIR::Formats::Utilities
        include FHIR::Deserializer::Utilities
            def parse_xml_entry_DeviceObservationReportVirtualDeviceChannelMetricComponent(entry)
                return nil unless entry
                model = FHIR::DeviceObservationReport::DeviceObservationReportVirtualDeviceChannelMetricComponent.new
                self.parse_element_data(model, entry)
                set_model_data(model, 'observation', FHIR::ResourceReference.parse_xml_entry(entry.at_xpath('./fhir:observation')))
                model
            end

            def parse_xml_entry_DeviceObservationReportVirtualDeviceChannelComponent(entry)
                return nil unless entry
                model = FHIR::DeviceObservationReport::DeviceObservationReportVirtualDeviceChannelComponent.new
                self.parse_element_data(model, entry)
                set_model_data(model, 'code', FHIR::CodeableConcept.parse_xml_entry(entry.at_xpath('./fhir:code')))
                set_model_data(model, 'metric', entry.xpath('./fhir:metric').map {|e| parse_xml_entry_DeviceObservationReportVirtualDeviceChannelMetricComponent(e)})
                model
            end

            def parse_xml_entry_DeviceObservationReportVirtualDeviceComponent(entry)
                return nil unless entry
                model = FHIR::DeviceObservationReport::DeviceObservationReportVirtualDeviceComponent.new
                self.parse_element_data(model, entry)
                set_model_data(model, 'code', FHIR::CodeableConcept.parse_xml_entry(entry.at_xpath('./fhir:code')))
                set_model_data(model, 'channel', entry.xpath('./fhir:channel').map {|e| parse_xml_entry_DeviceObservationReportVirtualDeviceChannelComponent(e)})
                model
            end

            def parse_xml_entry(entry)
                return nil unless entry
                model = self.new
                self.parse_element_data(model, entry)
                self.parse_resource_data(model, entry)
                set_model_data(model, 'instant', parse_date_time(entry.at_xpath('./fhir:instant/@value').try(:value)))
                set_model_data(model, 'identifier', FHIR::Identifier.parse_xml_entry(entry.at_xpath('./fhir:identifier')))
                set_model_data(model, 'source', FHIR::ResourceReference.parse_xml_entry(entry.at_xpath('./fhir:source')))
                set_model_data(model, 'subject', FHIR::ResourceReference.parse_xml_entry(entry.at_xpath('./fhir:subject')))
                set_model_data(model, 'virtualDevice', entry.xpath('./fhir:virtualDevice').map {|e| parse_xml_entry_DeviceObservationReportVirtualDeviceComponent(e)})
                model
            end
        end
    end
end


text:
//
//  DataGen.h
//
//  centiman TPCC
//
//  Primitives for generating random initial data for TPCC
//
//  Created by Alan Demers on 10/16/12.
//  Copyright (c) 2012 ademers. All rights reserved.
//

#ifndef __TPCC__DataGen__
#define __TPCC__DataGen__

#include <string.h>
#include "tpcc/RNG2.h"

namespace TPCC {

class DataGen : public RNG2 {

public:

    /*
     * non-uniform random numbers (2.1.6)
     */
	unsigned NURand(unsigned A, unsigned x, unsigned y, unsigned C) {
		return ( (((select(A+1) | uniformInt(x, y+1)) + C) % (y-x+1)) + x );
	}

    static unsigned const A_for_C_LAST = 255;
    static unsigned C_for_C_LAST;

    static unsigned const A_for_C_ID = 1023;
    static unsigned C_for_C_ID;

    static unsigned const A_for_OL_I_ID = 8191;
    static unsigned C_for_OL_I_ID;

    void chooseCValues();

    /*
     * random field values (4.3)
     */
	char randomAlphanumericChar() {
		return (char)(uniformInt(32, 127));
	}

    unsigned randomAlphanumericString( char * b, unsigned min, unsigned lim ) {
        unsigned len = uniformInt(min, lim);
        for( int i = 0; i < (int)len; i++ ) b[i] = randomAlphanumericChar();
        return len;
    }

	char randomNumericChar() {
		return (char)(uniformInt('0', 1+'9'));
	}

    unsigned randomNumericString( char * b, unsigned min, unsigned lim ) {
        unsigned len = uniformInt(min, lim);
        for( int i = 0; i < (int)len; i++ ) b[i] = randomNumericChar();
        return len;
    }

    unsigned randomCustomerName( char * b, unsigned n /*, unsigned C */ );

    void randomZipCode( char * b ) {
        (void)randomNumericString(b, 4, 5);
        memcpy(b+4, "11111", 5);
    }

    uint32_t * randomPermutation(uint32_t n);
        // returns an array containing the permutation;
        // the caller is responsible for freeing it.

	DataGen( int32_t seed ) : RNG2(seed) {}
	~DataGen() {}
}; // DataGen

}; // TPCC

#endif /* __TPCC__DataGen__ */


text:
var controllers = require('./controllers');
var mid = require('./middleware');
var path = require('path');

var router = function(app){
    app.get("/login", mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage);
    app.post("/login", mid.requiresSecure, mid.requiresLogout, controllers.Account.login);
    app.get("/signup", mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage);
    app.post("/signup", mid.requiresSecure, mid.requiresLogout, controllers.Account.signup);
    app.get("/logout", mid.requiresLogin, controllers.Account.logout);
	app.get("/leaderboard", mid.requiresLogin, controllers.Account.leaderboard);
    app.get("/profile", mid.requiresLogin, controllers.Account.profile);
	app.get("/game", mid.requiresLogin, controllers.Lobby.play);
	//app.get("/game", mid.requiresLogin, function(req, res){res.sendFile(path.join(__dirname + '/views/index.html'));});
    app.get("/lobbies", mid.requiresLogin, controllers.Lobby.lobbyPage);
    app.post("/lobbies", mid.requiresLogin, controllers.Lobby.create);
    app.get("/killer/:name",  mid.requiresLogin, controllers.Lobby.deleteLobby);
    app.get("/quit/:owner",  mid.requiresLogin, controllers.Lobby.removeLobby);
    app.get("/", mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage);

};

module.exports = router;


text:
r	<input disabled="disabled" readonly="true" dojoAttachPoint="Rval" size="1">

g	<input disabled="disabled" readonly="true" dojoAttachPoint="Gval" size="1">

b	<input disabled="disabled" readonly="true" dojoAttachPoint="Bval" size="1">

h	<input dojoAttachPoint="Hval"size="1" disabled="disabled" readonly="true"> °

s	<input dojoAttachPoint="Sval" size="1" disabled="disabled" readonly="true"> %

v	<input dojoAttachPoint="Vval" size="1"disabled="disabled" readonly="true"> %

			hex: <input dojoAttachPoint="hexCode, focusNode" size="6" class="dojoxColorPickerHexCode">


text:
require('../test_helper');

import fs = require('fs');
import glob = require('glob');
import rimraf = require('rimraf');

import Typhen = require('../../src/index');

describe('Error Test', () => {
  var errorFileNames = glob.sync('./test/fixtures/typings/errors/**/*.ts');

  errorFileNames.forEach((errorFileName) => {
    context(errorFileName.replace('./test/fixtures/typings/errors/', ''), () => {
      var plugin = Typhen.loadPlugin('./test/fixtures/plugin/typhen-test', {
        author: 'shiwano'
      });

      before((done) => {
        rimraf('./.tmp/generated', done);
      });

      it('should raise error', (done) => {
        Typhen.run({
          plugin: plugin,
          src: errorFileName,
          dest: '.tmp/generated'
        }).catch(e => {
          done();
        });
      });

      it('should not generate anything', (done) => {
        glob('./.tmp/generated/**/*.md', (err, fileNames) => {
          assert(fileNames.length === 0);
          done();
        });
      });
    });
  });
});


text:
package book.chapter05;

import java.util.ArrayList;
import java.util.List;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.ACL;

/**
 * Description: ZooKeepre ACL权限控制 测试
 *
 * @author nileader / nileader@gmail.com
 * @Date Feb 2, 2012
 */
public class DemoAuth2 implements Watcher {

    final static String SERVER_LIST = "127.0.0.1:2182";

    final static String PATH = "/yinshi_auth_test";
    final static String authentication_type = "digest";

    final static String correctAuthentication = "taokeeper:true";

    static ZkClient zkClient = null;

    public static void main(String[] args) throws Exception {

        List<ACL> acls = new ArrayList<ACL>(1);
        for (ACL ids_acl : Ids.CREATOR_ALL_ACL) {
            acls.add(ids_acl);
        }

        try {
            //zkClient = new ZkClient(SERVER_LIST, 50000);
            //zkClient.addAuthInfo(authentication_type, correctAuthentication.getBytes());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            //zkClient.createPersistent(PATH, acls, "init content");
            //System.out.println("使用授权key:" + correctAuthentication + "创建节点:" + PATH + ", 初始内容是: init content");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 获取数据
        getDataByNoAuthentication();
        getDataByBadAuthentication();
        getDataByCorrectAuthentication();

        zkClient.close();
    }

    /** 获取数据:采用错误的密码 */
    static void getDataByBadAuthentication() {
        String prefix = "[使用错误的授权信息]";
        try {
            System.out.println(prefix + "获取数据:" + PATH);
            zkClient = new ZkClient(SERVER_LIST, 50000);
            zkClient.addAuthInfo(authentication_type, "error".getBytes());
            System.out.println(prefix + "成功获取数据:" + zkClient.readData(PATH));
        } catch (Exception e) {
            System.err.println(prefix + "获取数据失败,原因:" + e.getMessage());
        }
    }

    /** 获取数据:不采用密码 */
    static void getDataByNoAuthentication() {
        String prefix = "[不使用任何授权信息]";
        try {
            System.out.println(prefix + "获取数据:" + PATH);
            zkClient = new ZkClient(SERVER_LIST, 50000);
            System.out.println(prefix + "成功获取数据:" + zkClient.readData(PATH));
        } catch (Exception e) {
            System.err.println(prefix + "获取数据失败,原因:" + e.getMessage());
        }
    }

    /** 采用正确的密码 */
    static void getDataByCorrectAuthentication() {
        String prefix = "[使用正确的授权信息]";
        try {
            System.out.println(prefix + "获取数据:" + PATH);
            zkClient = new ZkClient(SERVER_LIST, 50000);
            zkClient.addAuthInfo(authentication_type, correctAuthentication.getBytes());
            System.out.println(prefix + "成功获取数据:" + zkClient.readData(PATH));
        } catch (Exception e) {
            System.out.println(prefix + "获取数据失败,原因:" + e.getMessage());
        }
    }

    @Override
    public void process(WatchedEvent event) {
        // TODO Auto-generated method stub

    }

}


text:
Example of simulating a simple linear neuron with a diffusing sodium
concentration. An event injecting more Na into the centre is fired at t=0. The
measured concentrations will be written to disk further analysis.

 |    |  Option  | Meaning                         | Default     |
 |----|----------|---------------------------------|-------------|
 | -t | --tfinal | Length of the simulation period | 1 ms        |
 | -d | --dt     | Simulation time step            | 0.01 ms     |
 | -s | --ds     | Sampling interval               | 0.1 ms      |
 | -g | --gpu    | Use GPU id, enabled if >=0      | -1          |
 | -l | --length | Length of stick                 | 30 um       |
 | -x | --dx     | Discretisation                  | 1 um        |
 | -i | --Xi     | Initial Na concentration        | 0 mM        |
 | -b | --beta   | Na diffusivity                  | 0.005 m^2/s |
 | -o | --output | Save samples                    | log.csv     |


text:
package plainFP

import scala.language.higherKinds
import scala.util.Random

case class Config(
  host: String,
  port: Int,

  dbUrl: String,
  dbUser: String,
  dbPassword: String,

  smtpServer: String,
  smtpUser: String,
  smtpPassword: String,
  smtpFrom: String,

  personNameToUppercase: Boolean
)

case class Person(id: String, name: String, email: String, age: Int)
extends Entity

case class Request(message: String)
case class Response(message: String)

class WebServer(host: String, port: Int) {
  var count = 0

  def close = { println("WebServer has closed") }

  def listen(callback: Request => Response): Boolean = {
    val request = Request(count.toString)
    println(s" => $request")
    val response = callback(Request(count.toString))
    count = count + 1
    println(s"<= $response")
    count < 3
  }
}

trait Entity
case object GetEntityFailed extends Failure
case object UpdateEntityFailed extends Failure

class DBServer(url: String, user: String, password: String) {
  def close = { println("DBServer has closed") }

  def getEntity[T <: Entity](id: String): Either[Failure, T] = {
    val entity = Person(
      id,
      "John Doe",
      "john@doe.com",
      27 + Integer.parseInt(id)
    ).asInstanceOf[T]
    println(s"getEntity: id $id entity $entity")
    if (Random.nextInt(100) < 10) Left(GetEntityFailed)
    else Right(entity)
  }

  def updateEntity[T <: Entity](entity: T): Either[Failure, T] = {
    println(s"updateEntity: $entity")
    if (Random.nextInt(100) < 20) Left(UpdateEntityFailed)
    else Right(entity)
  }
}

case class Mail(from: String, to: String, subject: String, content: String)

case object SendMailFailed extends Failure

class SmtpServer(smtpServer: String, smtpUser: String, smtpPassword: String) {
  def close = { println("SmtpServer has closed") }

  def sendMail(mail: Mail): Either[Failure, Boolean] = {
    println(s"sendMail: $mail")
    if (Random.nextInt(100) < 20) Left(SendMailFailed)
    else Right(true)
  }
}

trait Failure

object Common {
  def map[A, B](f: A => B): Either[Failure, A] => Either[Failure, B] = {
    x => x.map(f)
  }

  def flatMap[A, B](f: A => Either[Failure, B]):
    Either[Failure, A] => Either[Failure, B] =
  {
    x => x.flatMap(f)
  }

  //implicit class Function1Option2[-T1, R](f: T1 => Either[Failure, R])
    //extends Function1[T1, Either[Failure, R]]
  //{
    //def apply(x: T1): Either[Failure, R] = f(x)

    //def ~>[A](g: (R) => A): (T1) => Either[Failure, A] = x => apply(x).map(g)
    //def ~~>[A](g: (R) => Either[Failure, A]): (T1) => Either[Failure, A] =
      //x => apply(x).flatMap(g)
  //}
}


text:
(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/myapp/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);


text:
struct MIDIRunloopSource;
struct MIDIRunloop;

struct MIDIRunloopSourceDelegate {
  void *info;
  int (*read)( void * info, int nfds, fd_set * readfds );
  int (*write)( void * info, int nfds, fd_set * readfds );
  int (*timeout)( void * info, struct timespec * elapsed );
};

struct MIDIRunloopDelegate {
  void *info;
  int (*schedule_read)( void * info, int fd );
  int (*schedule_write)( void * info, int fd );
  int (*schedule_timeout)( void * info, struct timespec * );
  int (*clear_read)( void * info, int fd );
  int (*clear_write)( void * info, int fd );
  int (*clear_timeout)( void * info );
};

struct MIDIRunloopSource * MIDIRunloopSourceCreate( struct MIDIRunloopSourceDelegate * delegate );
void MIDIRunloopSourceDestroy( struct MIDIRunloopSource * source );
void MIDIRunloopSourceRetain( struct MIDIRunloopSource * source );
void MIDIRunloopSourceRelease( struct MIDIRunloopSource * source );

int MIDIRunloopSourceInvalidate( struct MIDIRunloopSource * source );
int MIDIRunloopSourceWait( struct MIDIRunloopSource * source );

int MIDIRunloopSourceScheduleRead( struct MIDIRunloopSource * source, int fd );
int MIDIRunloopSourceClearRead( struct MIDIRunloopSource * source, int fd );
int MIDIRunloopSourceScheduleWrite( struct MIDIRunloopSource * source, int fd );
int MIDIRunloopSourceClearWrite( struct MIDIRunloopSource * source, int fd );
int MIDIRunloopSourceScheduleTimeout( struct MIDIRunloopSource * source, struct timespec * timeout );
int MIDIRunloopSourceClearTimeout( struct MIDIRunloopSource * source );

struct MIDIRunloop * MIDIRunloopCreate( struct MIDIRunloopDelegate * delegate );
void MIDIRunloopDestroy( struct MIDIRunloop * runloop );
void MIDIRunloopRetain( struct MIDIRunloop * runloop );
void MIDIRunloopRelease( struct MIDIRunloop * runloop );

int MIDIRunloopAddSource( struct MIDIRunloop * runloop, struct MIDIRunloopSource * source );
int MIDIRunloopRemoveSource( struct MIDIRunloop * runloop, struct MIDIRunloopSource * source );

int MIDIRunloopStart( struct MIDIRunloop * runloop );
int MIDIRunloopStop( struct MIDIRunloop * runloop );
int MIDIRunloopStep( struct MIDIRunloop * runloop );

#endif