text:
from distutils.core import setup
from ttag import get_version

setup(
    name='django-ttag',
    version=get_version(),
    description="A template tag constructor library for Django.",
    long_description=open('README.rst').read(),
    author='Chris Beaven',
    author_email='chris@lincolnloop.com',
    license='MIT',
    url='http://github.com/lincolnloop/django-ttag',
    packages=[
        'ttag',
        'ttag.tests',
        'ttag.tests.setup',
        'ttag.helpers',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
)


text:
const { hooks } = require('mostly-feathers-mongoose');
const { cache } = require('mostly-feathers-cache');

module.exports = function (options = {}) {
  return {
    before: {
      all: [
        hooks.authenticate('jwt', options.auth),
        cache(options.cache)
      ],
      create: [
        hooks.addRouteObject('primary', { service: 'documents' })
      ],
      remove: [
        hooks.addRouteObject('primary', { service: 'documents' })
      ]
    },
    after: {
      all: [
        cache(options.cache),
        hooks.responder()
      ]
    }
  };
};

redpajama_set_name: RedPajamaGithub


text:
using Xamarin.Forms;

namespace GlowingBrain.DataCapture.Views
{
	public class GBDatePicker : DatePicker
	{
	}
}


text:
template <class Container>
void testSetInsert()
{
  typedef typename Container::value_type ValueTp;
  typedef Container C;
  typedef std::pair<typename C::iterator, bool> R;
  ConstructController* cc = getConstructController();
  cc->reset();
  {
    CHECKPOINT("Testing C::insert(const value_type&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&>();
    assert(c.insert(v).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      assert(c.insert(v2).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::insert(value_type&)");
    Container c;
    ValueTp v(42);
    cc->expect<const ValueTp&>();
    assert(c.insert(v).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      assert(c.insert(v2).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::insert(value_type&&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&&>();
    assert(c.insert(std::move(v)).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      assert(c.insert(std::move(v2)).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::insert(const value_type&&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&>();
    assert(c.insert(std::move(v)).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      assert(c.insert(std::move(v2)).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::insert(std::initializer_list<ValueTp>)");
    Container c;
    std::initializer_list<ValueTp> il = { ValueTp(1), ValueTp(2) };
    cc->expect<ValueTp const&>(2);
    c.insert(il);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      c.insert(il);
    }
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type const&");
    Container c;
    const ValueTp ValueList[] = { ValueTp(1), ValueTp(2), ValueTp(3) };
    cc->expect<ValueTp const&>(3);
    c.insert(std::begin(ValueList), std::end(ValueList));
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      c.insert(std::begin(ValueList), std::end(ValueList));
    }
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type&&");
    Container c;
    ValueTp ValueList[] = { ValueTp(1), ValueTp(2) , ValueTp(3) };
    cc->expect<ValueTp&&>(3);
    c.insert(std::move_iterator<ValueTp*>(std::begin(ValueList)),
             std::move_iterator<ValueTp*>(std::end(ValueList)));
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp ValueList2[] = { ValueTp(1), ValueTp(2) , ValueTp(3) };
      c.insert(std::move_iterator<ValueTp*>(std::begin(ValueList2)),
               std::move_iterator<ValueTp*>(std::end(ValueList2)));
    }
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type&");
    Container c;
    ValueTp ValueList[] = { ValueTp(1), ValueTp(2) , ValueTp(3) };
    cc->expect<ValueTp const&>(3);
    c.insert(std::begin(ValueList), std::end(ValueList));
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      c.insert(std::begin(ValueList), std::end(ValueList));
    }
  }
}

template <class Container>
void testSetEmplace()
{
  typedef typename Container::value_type ValueTp;
  typedef Container C;
  typedef std::pair<typename C::iterator, bool> R;
  ConstructController* cc = getConstructController();
  cc->reset();
  {
    CHECKPOINT("Testing C::emplace(const value_type&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&>();
    assert(c.emplace(v).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      assert(c.emplace(v2).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::emplace(value_type&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&>();
    assert(c.emplace(v).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      assert(c.emplace(v2).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::emplace(value_type&&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&&>();
    assert(c.emplace(std::move(v)).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      assert(c.emplace(std::move(v2)).second == false);
    }
  }
  {
    CHECKPOINT("Testing C::emplace(const value_type&&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&&>();
    assert(c.emplace(std::move(v)).second);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      assert(c.emplace(std::move(v2)).second == false);
    }
  }
}

template <class Container>
void testSetEmplaceHint()
{
  typedef typename Container::value_type ValueTp;

  typedef Container C;
  typedef typename C::iterator It;
  ConstructController* cc = getConstructController();
  cc->reset();
  {
    CHECKPOINT("Testing C::emplace_hint(p, const value_type&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&>();
    It ret = c.emplace_hint(c.end(), v);
    assert(ret != c.end());
    assert(c.size() == 1);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      It ret2 = c.emplace_hint(c.begin(), v2);
      assert(&(*ret2) == &(*ret));
      assert(c.size() == 1);
    }
  }
  {
    CHECKPOINT("Testing C::emplace_hint(p, value_type&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&>();
    It ret = c.emplace_hint(c.end(), v);
    assert(ret != c.end());
    assert(c.size() == 1);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      It ret2 = c.emplace_hint(c.begin(), v2);
      assert(&(*ret2) == &(*ret));
      assert(c.size() == 1);
    }
  }
  {
    CHECKPOINT("Testing C::emplace_hint(p, value_type&&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&&>();
    It ret = c.emplace_hint(c.end(), std::move(v));
    assert(ret != c.end());
    assert(c.size() == 1);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      ValueTp v2(42);
      It ret2 = c.emplace_hint(c.begin(), std::move(v2));
      assert(&(*ret2) == &(*ret));
      assert(c.size() == 1);
    }
  }
  {
    CHECKPOINT("Testing C::emplace_hint(p, const value_type&&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&&>();
    It ret = c.emplace_hint(c.end(), std::move(v));
    assert(ret != c.end());
    assert(c.size() == 1);
    assert(!cc->unchecked());
    {
      DisableAllocationGuard g;
      const ValueTp v2(42);
      It ret2 = c.emplace_hint(c.begin(), std::move(v2));
      assert(&(*ret2) == &(*ret));
      assert(c.size() == 1);
    }
  }
}

template <class Container>
void testMultisetInsert()
{
  typedef typename Container::value_type ValueTp;
  typedef Container C;
  ConstructController* cc = getConstructController();
  cc->reset();
  {
    CHECKPOINT("Testing C::insert(const value_type&)");
    Container c;
    const ValueTp v(42);
    cc->expect<const ValueTp&>();
    c.insert(v);
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(value_type&)");
    Container c;
    ValueTp v(42);
    cc->expect<const ValueTp&>();
    c.insert(v);
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(value_type&&)");
    Container c;
    ValueTp v(42);
    cc->expect<ValueTp&&>();
    c.insert(std::move(v));
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(std::initializer_list<ValueTp>)");
    Container c;
    std::initializer_list<ValueTp> il = { ValueTp(1), ValueTp(2) };
    cc->expect<ValueTp const&>(2);
    c.insert(il);
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type const&");
    Container c;
    const ValueTp ValueList[] = { ValueTp(1), ValueTp(2), ValueTp(3) };
    cc->expect<ValueTp const&>(3);
    c.insert(std::begin(ValueList), std::end(ValueList));
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type&&");
    Container c;
    ValueTp ValueList[] = { ValueTp(1), ValueTp(2) , ValueTp(3) };
    cc->expect<ValueTp&&>(3);
    c.insert(std::move_iterator<ValueTp*>(std::begin(ValueList)),
             std::move_iterator<ValueTp*>(std::end(ValueList)));
    assert(!cc->unchecked());
  }
  {
    CHECKPOINT("Testing C::insert(Iter, Iter) for *Iter = value_type&");
    Container c;
    ValueTp ValueList[] = { ValueTp(1), ValueTp(2) , ValueTp(3) };
    cc->expect<ValueTp&>(3);
    c.insert(std::begin(ValueList), std::end(ValueList));
    assert(!cc->unchecked());
  }
}

#endif


text:
A partial internal DSL compiler.

Lexing/Parsing responsibilities are handled by a combination of the Ruby interpreter itself (Ruby already lexes and parses itself) and a recorder to capture undefined Ruby methods, via *method_missing*, as an Abstract Syntax Tree (AST).

You supply the code generator.

## Assumptions.

* People love libraries with DSLs like Sinatra and ActiveRecord and Babushka and AASM and (name your favourite Ruby library).
* What they love about these is the small amount of Ruby syntax required to get a whole lot done.
* They love that they can contextualise their definitions (that make the libraries do things) with natural Ruby syntax such as blocks.
* To enable these kinds of libraries the use of so-called 'meta-programming' constructs are required (instance_eval, instance_exec).
* Clever but inexperienced Ruby programmers often make very useful libraries with wonderful APIs but horrible internals

## Goals.

* Decouple the language definition of an internal DSL from its implementation
* Allow library authors to dream up APIs and implement them without entering Ruby metaprogramming hell (it is a real place).

## Example
    class Feature < Test::Unit::TestCase
      # Configuring lispy to geenrate an AST for our language

      PROC_KEYWORDS = [:Given, :When, :Then, :And]
      KEYWORDS = [:Scenario, :Tag] + PROC_KEYWORDS

      extend YourDSL
      record_your_dsl :only => KEYWORDS, :retain_blocks_for => PROC_KEYWORDS

      # Using our language
      Scenario "this gets lispyified" do
        Given "something" do
        end

        Then "test something exists" do
          fail "ohai"
        end
      end
    end

    # Barfing out the AST for the above
    require 'rubygems'
    require 'awesome_print'
    ap Feature.output

    # Example 'interpreter' for the AST generated above
    # Executes the block on the Given and Then from above sequentially
    # Spike on how an acceptance testing DSL could work
    Feature.class_eval do
      def test_something
        scenario = Feature.output.expressions.first
        steps = scenario.scope.expressions
        instance_eval &steps[0].proc
        instance_eval &steps[1].proc
      end
    end

     OUTPUTS:
     ➜  example git:(no_more_last_last_last) ✗ ruby feature.rb
     {
                :file => "feature.rb",
         :expressions => [
             [0] {
                 :symbol => :Scenario,
                   :args => "this gets lispyified",
                 :lineno => "14",
                   :proc => nil,
                  :scope => {
                     :expressions => [
                         [0] {
                             :symbol => :Given,
                               :args => "something",
                             :lineno => "15",
                               :proc => #<Proc:0x000001010e9140@feature.rb:15>,
                              :scope => nil
                         },
                         [1] {
                             :symbol => :Then,
                               :args => "test something exists",
                             :lineno => "18",
                               :proc => #<Proc:0x000001010e8ec0@feature.rb:18>,
                              :scope => nil
                         }
                     ]
                 }
             }
         ]
     }
     Loaded suite feature
     Started
     E
     Finished in 0.006305 seconds.

       1) Error:
     test_something(Feature):
     RuntimeError: ohai
         feature.rb:19:in `block (2 levels) in <class:Feature>'
         feature.rb:34:in `instance_eval'
         feature.rb:34:in `test_something'

     1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

## Credits

* Lispy concept and original impl by Ryan Allen (http://github.com/ryan-allen/lispy)
* Rewritten and extended by Evan Light (http://github.com/elight/yourdsl)

## License.

Released under the MIT license (see MIT-LICENSE).


text:
var createElement = ( function createElement() {

  "use strict";

  function InitCreateElement( name, val, result ) {

    if ( typeof name === "undefined" ) {
      return false;
    }
    if ( typeof val === "undefined" ) {
      val = "";
    }
    if ( typeof result === "undefined" ) {
      result = "";
    }

    var ret = document.createElement( name ),
        i;

    if ( val.length > 1 && (val[0] === "[" && val[val.length - 1] === "]") ) {

      var values = val.split("][");
      values[0] = values[0].substr(1);
      values[values.length - 1] = values[values.length - 1].substr(0, values[values.length - 1].length - 1);
      i = 0;
      var valuesLen = values.length;

      for ( i; i < valuesLen; i++ ) {

        var key,
            width = "",
            colonIndex = values[i].indexOf(":");

        if ( colonIndex > 0 ) {

          key = values[i].substr( 0, colonIndex );
          width = values[i].substr( colonIndex + 1 );

        } else {

          key = values[i].substr( 0 );

        }

        ret.setAttribute( key, width );

      }

    }
    if ( Array.isArray( result ) ) {

      i = 0;

      for ( i; i < result.length; i++ ) {

        if ( result[i].tagName ) {

          ret.appendChild( result[i] );

        } else {

          ret.appendChild( document.createTextNode( result[i] ) );

        }

      }

    } else {

      if ( result.tagName ) {

        ret.appendChild( result );

      } else {

        ret.innerHTML = result;

      }

    }

    return ret;

  }

  return InitCreateElement;

})( this );


text:
using System;

namespace Braintree
{
    /// <summary>
    /// A class for building transaction requests with manual key entry.
    /// </summary>
    /// <example>
    /// A payment reader card details request can be constructed as follows:
    /// <code>
    /// PaymentReaderCardDetailsRequest createRequest = new PaymentReaderCardDetailsRequest
    /// {
    ///     EncryptedCardData = "8F34DFB312DC79C24FD5320622F3E11682D79E6B0C0FD881",
    ///     KeySerialNumber = "FFFFFF02000572A00005",
    /// }
    /// </code>
    /// </example>
    public class PaymentReaderCardDetailsRequest : Request
    {
        public string EncryptedCardData { get; set; }
        public string KeySerialNumber { get; set; }

        public override string ToXml()
        {
            return ToXml("payment-reader-card-details");
        }

        public override string ToXml(string root)
        {
            return BuildRequest(root).ToXml();
        }

        protected virtual RequestBuilder BuildRequest(string root)
        {
            return new RequestBuilder(root).
                AddElement("encrypted-card-data", EncryptedCardData).
                AddElement("key-serial-number", KeySerialNumber);
        }
    }
}


text:
use std::convert::From;

use crate::sunsaver::{ArrayFault, ChargeState, LoggedResponse, LoggedResponseDay, SunSaverResponse};

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponse {
    generation: ApiStatusResponseGeneration,
    storage: ApiStatusResponseStorage,
    load: ApiStatusResponseLoad,
    temperature: ApiStatusResponseTemperature,
    faults: ApiStatusResponseFaults,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponseGeneration {
    solar_input_voltage_filtered: f32,
    calculated_generation_power: f32,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponseStorage {
    battery_voltage_filtered: f32,
    battery_charge_current_filtered: f32,
    battery_charge_power_calculated: f32,
    charge_state: ChargeState,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponseLoad {
    load_voltage_filtered: f32,
    load_current_filtered: f32,
    load_power_calculated: f32,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponseTemperature {
    heatsink_temperature: i8,
    battery_temperature: i8,
    ambient_temperature: i8,
    remote_temperature: i8,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiStatusResponseFaults {
    array: ArrayFault,
}

impl From<SunSaverResponse> for ApiStatusResponse {
    fn from(response: SunSaverResponse) -> Self {
        let battery_voltage_filtered = response.battery_voltage_filtered();
        let battery_charge_current_filtered = response.battery_charge_current_filtered();
        let load_voltage_filtered = response.load_voltage_filtered();
        let load_current_filtered = response.load_current_filtered();
        let solar_input_voltage_filtered = response.solar_input_voltage_filtered();

        let generation = ApiStatusResponseGeneration {
            solar_input_voltage_filtered,
            calculated_generation_power: (load_current_filtered + battery_charge_current_filtered) * solar_input_voltage_filtered,
        };
        let storage = ApiStatusResponseStorage {
            battery_voltage_filtered,
            battery_charge_current_filtered,
            battery_charge_power_calculated: battery_voltage_filtered * battery_charge_current_filtered,
            charge_state: response.charge_state(),
        };
        let load = ApiStatusResponseLoad {
            load_voltage_filtered,
            load_current_filtered,
            load_power_calculated: load_voltage_filtered * load_current_filtered,
        };
        let temperature = ApiStatusResponseTemperature {
            heatsink_temperature: response.heatsink_temperature(),
            battery_temperature: response.battery_temperature(),
            ambient_temperature: response.ambient_temperature(),
            remote_temperature: response.remote_temperature(),
        };
        let faults = ApiStatusResponseFaults {
            array: response.array_fault(),
        };
        ApiStatusResponse {
            generation,
            storage,
            load,
            temperature,
            faults,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiLoggedResponse {
    days: Vec<ApiLoggedDayResponse>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ApiLoggedDayResponse {
    hourmeter: u32,
    battery_voltage_min: f32,
    battery_voltage_max: f32,
    battery_charge_daily: f32,
    load_charge_daily: f32,
    array_voltage_max: f32,
}

impl From<LoggedResponse> for ApiLoggedResponse {
    fn from(response: LoggedResponse) -> Self {
        let days = response.days.into_iter().map(ApiLoggedDayResponse::from).collect();
        ApiLoggedResponse { days }
    }
}

impl From<LoggedResponseDay> for ApiLoggedDayResponse {
    fn from(response: LoggedResponseDay) -> Self {
        ApiLoggedDayResponse {
            hourmeter: response.hourmeter,
            battery_voltage_min: response.battery_voltage_min(),
            battery_voltage_max: response.battery_voltage_max(),
            battery_charge_daily: response.battery_charge_daily(),
            load_charge_daily: response.load_charge_daily(),
            array_voltage_max: response.array_voltage_max(),
        }
    }
}

#[cfg(test)]
mod test {
    use serde_json;

    use super::*;
    use crate::sunsaver::ArrayFault;

    #[test]
    fn api_statusresponse_faults() {
        let native = ApiStatusResponseFaults { array: ArrayFault::empty() };
        let json = serde_json::to_string(&native).unwrap();
        assert_eq!(
            json,
            "{\"array\":{\
             \"OVERCURENT\":false,\
             \"FETS_SHORTED\":false,\
             \"SOFTWARE_BUGS\":false,\
             \"BATTERY_HVD\":false,\
             \"ARRAY_HVD\":false,\
             \"EEPROM_EDIT\":false,\
             \"RTS_SHORTED\":false,\
             \"RTS_DISCONECTED\":false,\
             \"INTERNAL_TEMP_SENSOR_FAIL\":false\
             }}"
        );
    }
}


text:
/**
 * Created by thog on 8/24/15.
 */

var mysql = require("mysql");
var connection = mysql.createConnection(require("./config/database"));
init  = function()
{
    connection.connect(function(err){
        if(!err) {
            console.log("Database is connected ... \n\n");
        } else {
            console.log("Error connecting database ... \n\n");
        }
    });
};

exports.init = init;


text:
/**
 * Test dependencies.
 */

var start = require('./common')
  , mongoose = start.mongoose
  , assert = require('assert')
  , random = require('../lib/utils').random
  , Query = require('../lib/query')
  , Schema = mongoose.Schema
  , SchemaType = mongoose.SchemaType
  , CastError = SchemaType.CastError
  , ValidatorError = SchemaType.ValidatorError
  , ValidationError = mongoose.Document.ValidationError
  , ObjectId = Schema.ObjectId
  , DocumentObjectId = mongoose.Types.ObjectId
  , DocumentArray = mongoose.Types.DocumentArray
  , EmbeddedDocument = mongoose.Types.Embedded
  , MongooseArray = mongoose.Types.Array
  , MongooseError = mongoose.Error;

/**
 * Setup.
 */

var Comments = new Schema();

Comments.add({
    title     : String
  , date      : Date
  , body      : String
  , comments  : [Comments]
});

var BlogPost = new Schema({
    title     : String
  , author    : String
  , slug      : String
  , date      : Date
  , meta      : {
        date      : Date
      , visitors  : Number
    }
  , published : Boolean
  , mixed     : {}
  , numbers   : [Number]
  , owners    : [ObjectId]
  , comments  : [Comments]
});

var collection = 'mapreduce_' + random();
mongoose.model('MapReduce', BlogPost);

describe('model: mapreduce:', function(){
  it('works', function(done){
    var db = start()
      , MR = db.model('MapReduce', collection)

    var id = new mongoose.Types.ObjectId;
    var authors = 'aaron guillermo brian nathan'.split(' ');
    var num = 10;
    var docs = [];
    for (var i = 0; i< num; ++i)
      docs.push({ author: authors[i%authors.length], owners: [id], published: true });

    //mongoose.set('debug', true);
    MR.create(docs, function (err) {
      assert.ifError(err);

      var o = {
          map: function () { emit(this.author, 1) }
        , reduce: function (k, vals) { return vals.length }
      }

      MR.mapReduce(o, function (err, ret, stats) {
        assert.ifError(err);
        assert.ok(Array.isArray(ret));
        assert.ok(stats);
        ret.forEach(function (res) {
          if ('aaron' == res._id) assert.equal(3, res.value);
          if ('guillermo' == res._id) assert.equal(3, res.value);
          if ('brian' == res._id) assert.equal(2, res.value);
          if ('nathan' == res._id) assert.equal(2, res.value);
        });

        var o = {
            map: function () { emit(this.author, 1) }
          , reduce: function (k, vals) { return vals.length }
          , query: { author: 'aaron', published: 1, owners: id }
        }

        MR.mapReduce(o, function (err, ret, stats) {
          assert.ifError(err);

          assert.ok(Array.isArray(ret));
          assert.equal(1, ret.length);
          assert.equal('aaron', ret[0]._id);
          assert.equal(3, ret[0].value);
          assert.ok(stats);

          modeling();
        });
      });

      function modeling () {
        var o = {
            map: function () { emit(this.author, 1) }
          , reduce: function (k, vals) { return vals.length }
          , out: { replace: '_mapreduce_test_' + random() }
        }

        MR.mapReduce(o, function (err, ret, stats) {
          assert.ifError(err);

          // ret is a model
          assert.ok(!Array.isArray(ret));
          assert.equal('function', typeof ret.findOne);
          assert.equal('function', typeof ret.mapReduce);

          // queries work
          ret.where('value').gt(1).sort({_id: 1}).exec(function (err, docs) {
            assert.ifError(err);
            assert.equal('aaron', docs[0]._id);
            assert.equal('brian', docs[1]._id);
            assert.equal('guillermo', docs[2]._id);
            assert.equal('nathan', docs[3]._id);

            // update casting works
            ret.findOneAndUpdate({ _id: 'aaron' }, { published: true }, function (err, doc) {
              db.close();
              assert.ifError(err);
              assert.ok(doc);
              assert.equal('aaron', doc._id);
              assert.equal(true, doc.published);
              done();
            });
          });
        });
      }
    });

  })
});


text:
'use strict';

// This is an example of an INVALID router, as it doesn't export a function.

exports.router = {};


text: <title>Todo List</title>


text:
We have a 1 year roadmap (estimation) with the following versions. You'll notice that as we're developing in agile mode, we've chosen to create and present groups of features but no date of delivery (feature-driven release planning : http://www.scrum-institute.org/Release_Planning.php). This roadmap doesn't take into account the bugs which could be opened during this timeframe. Depending on the severity of these bugs, we'll be able to fix shortly after their discovery and include those fixes in specific Hotfix versions or include these bugs in the roadmap.

The 2.x releases have been focused on quality and stability and covered by Unit tests + functional tests.

The 3.x and 4.x releases have been focused on the REST layer of AbeCMS.

The 5.x releases will focus on the transformation of AbeCMS to a full featured Content marketing Services platform.

## Roadmap of the next 5.x releases
X- Look&feel of the users menu
- the Themes concept is fully integrated (we must be able to chose a theme (composed by templates) from the admin)
- the drag&drop of partials is fully integrated and included in the default editor.
- the documentation is up to date
- Notifications are fully functional and documented
- AI images, video and NLP for text and summaries included by default
- Add netlify as a static deployment stack
- micro-services (mail, form, search engine ready to use and documented)
-

- templates and partials will be uploadable
- Video training will be produced
- Refactor the REST layer:
  - Usage of oAuth2 for REST routes
- Add robots.txt + URL redirection features in Abe

- We should be able to sync data, templates, ... from a distant Abe install
- Add a -d (--dev) option to Abe CLI so that we can have livereload and debug features during template dev

## Changelog
See the complete [changelog](./CHANGELOG.md)

### 3.0.0
See the complete [v3.0.0 release notes](./version3.md)

### 2.16.*

### 2.15.*
- The order by statement in abe type="data" is now fully usable on any property of the json post. usage of order by date ASC is deprecated. Please use order by abe_meta.date ASC instead. And you can now limit a set of record without having to use the 'where' statement
- abe type="import" are not usable in a {{#each}} statement for technical reasons. But you can reproduce this behavior by using the array notation in an import. ie. {{abe type="import" file="myPartial/{{list[].id}}"}} This is particularly useful when you propose a contributor to select several partials in a list (with the {{#each}} notation + type="data). You can then display these selected partials with this array style notation.

### 2.14.*
- Abe type="data" are now usable in {{#each x}} statements. This was a long awaited feature.

### 2.13.*
- The manager has been fully ajaxified ; A dedicated REST route is available making the performance on frontend much more efficient. the stateful manager of Abe has become responsible of pagination of articles (huge performance boost)
- New core features for the array class (facet + nested sort)

### 2.12.*
- 150 handlebars helpers are now available for template designers
- The engine now detects abe tags with more accuracy and more performance
- The abe type="file" is available (your users will be able to upload files)
- The "hint" attribute (which produces a comment under the fields in the editor) is now part of the core
- The load testing scenarii have been open sourced (based on Locust)

### 2.11.*
- Abe type="import": Can now include variables
- Abe admin: Role Workflow management has been improved
- Functional tests are now available !
- Unit testing covers more than 60% of the code :)

### 2.10.*
- Template designer : isEditor variable can be used in a template
- Bugfixes

### 2.9.*
- Only bugfixes concerning User management

### 2.8.*
- New plugin system for Abe. It's now based on npm !
- Integrating user authentication and authorization Management inside Abe !
- Integrating Image cropping and resizing into Abe !
- Improving Unit tests

### 2.7.*
- New statement in Abe type="data": the display attribute can contain multiple variables (useful when used with autocomplete feature)

### 2.6.*
- Template designer: Precontrib is available for template designers. It will be possible to define specific slug structure from a template.
- Template designer: 2 new handlebars helpers. uppercase and lowercase
- Reference files editor available on admin !
- Manager: On publish and unpublish, we only add/update or remove the concerned file. Huge performance improvement on save steps !
- Dev: It's now possible to use Abe under Windows

### 2.5.*
- New statement in Abe type="data" AQL format: A select may now contain "IN" or "NOT IN" with variables usage (you can reference another data type).
- New attribute in Abe type="data": prefill gives the possibility on the editor to "refill" fields already filled in.
- Adding unit tests
- New command: generate-posts.js giving you the possibility to export data from Abe on the command line
- The Abe editor is now compatible with Firefox

### 2.4.*
- The first unit tests are implemented
- Quality control with esLint added
- Continuous Integration with [Travis](https://travis-ci.org/abecms/abecms)
- Unit test coverage added : [coveralls](https://coveralls.io/github/abecms/abecms?branch=master)
- Select data becomes a first class citizen in Manager => perf X50 on page display including templates with select statements

### 2.3.*
- don't block response when upload image file size reaches a predefined limit
- allow video upload
- New handlebars helper : isTrue() (cf. doc)
- Replacing `Sql.deep_value_array` with `eval` in abe-sql.js resulting in a performance boost on request calculation
- precompilation of templates added as configurable option resulting in a performance boost on page display
- Removing pagination option from Abe

### 2.2.*
- ExecuteQuery becomes asynchronous

### 2.1
- New handlebars helper : truncate() (cf. doc)

### 2.0
- The plugins have been put in their respective repository. It's now possible to install plugins directly from Abe config file and command `abe install`.
- Abe becomes a stateful app. A manager is created to handle the file list which is updated on events (CRUD) resulting in a major boost of performance.

### 1.8.x
This version will be the last in the 1.x series.
- Performance improvements: The overall performance of Abe has been optimized. The "Order By" statement in select statement in the type="data" has been deeply improved. Furthermore, the front was requesting twice the same content (to populate left and main content). It has been fixed.

### 1.7.x
New features :
- Duplicate : It's now possible to create a new content form an existing one.
- Routes refactoring : Each action sent to the Abe engine has its own route
- Routes refactoring : A new route /list-url display the whole list of available routes exposed by Abe
- Routes refactoring : publish-all is a new route triggering the republication of all already published content without modifying the modification date of these contents. This is the first attempt to address the possibility of updating linked content when publishing a content.
- Content metadata updatable : It's now possible to change the path, the name or the template of an existing file
- Debugging : It's now possible to trigger logs by adding a parameter in the url


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.Entity;
using System.Linq;

namespace Verasoft.EF.Tracking.Tests
{
    [TestClass]
    public class UnitTest1
    {
        private const string UT_ProjectName = "UnitTest-Project1";
        private const string UT_DepartmentName = "UnitTest-Department1";

        [TestInitialize]
        public void TestInitialize()
        {
            TrackingContext.Current.ClearSubscriptions();
        }

        [TestMethod]
        public void AfterSaveChanges_Entity_RelatedEntity_Added()
        {
            string result = string.Empty;
            string resultFormat = "AfterSaveChanges_Entity_RelatedEntity_Added_{0}_{1}";

            TrackingContext.Current.Subscribe<EFTrackingContext>(TrackingEvent.AfterSaveChanges, (s) =>
                {
                    s.For<Project>()
                        .Where(x => x.Departments, RelatedEntityTrackingTypes.Added)
                        .Perform((content, item) =>
                            {
                                result = string.Format(resultFormat, item.Entity.Name, item.RelatedEntity.Name);
                            });
                });

            using(var db = new EFTrackingContext())
            {
                var project = db.Projects.SingleOrDefault(x=>x.Name == UT_ProjectName);
                if (project == null)
                {
                    project = new Project { Name = UT_ProjectName };
                    db.Projects.Add(project);
                    db.SaveChanges();
                }

                var department = new Department{ Name = UT_DepartmentName};
                project.Departments.Add(department);
                db.SaveChanges();

                Assert.AreEqual(string.Format(resultFormat, project.Name, department.Name), result, "AfterSaveChanges_Entity_RelatedEntity_Added - Failed");
            }
        }

        [TestMethod]
        public void AfterSaveChanges_Entity_RelatedEntity_Deleted()
        {
            bool deleted = false;

            TrackingContext.Current.Subscribe<EFTrackingContext>(TrackingEvent.AfterSaveChanges, (s) =>
            {
                s.For<Project>()
                    .Where(x => x.Departments, RelatedEntityTrackingTypes.Deleted)
                    .Perform((content, item) =>
                    {
                        deleted = true;
                    });
            });

            using (var db = new EFTrackingContext())
            {
                var project = db.Projects.SingleOrDefault(x => x.Name == UT_ProjectName);
                if (project == null)
                {
                    project = new Project { Name = UT_ProjectName };
                    db.Projects.Add(project);
                    db.SaveChanges();
                }

                var department = project.Departments.SingleOrDefault(x => x.Name == UT_DepartmentName);
                if (department == null)
                {
                    department = new Department { Name = UT_DepartmentName };
                    project.Departments.Add(department);
                    db.SaveChanges();
                }

                project.Departments.Remove(department);
                db.SaveChanges();

                Assert.IsTrue(deleted, "AfterSaveChanges_Entity_RelatedEntity_Deleted - Failed");
            }
        }

        [TestMethod]
        public void AfterSaveChanges_Entity_Modified()
        {
            string result = "";

            TrackingContext.Current.Subscribe<EFTrackingContext>(TrackingEvent.AfterSaveChanges, (s) =>
            {
                s.For<Project>()
                    .Where(x=>x.Name)
                    .Perform((content, item) =>
                    {
                        result = string.Format("{0}--{1}", item.OriginalValue, item.CurrentValue);
                    });
            });

            using (var db = new EFTrackingContext())
            {
                var project = db.Projects.SingleOrDefault(x => x.Name == UT_ProjectName);
                if (project == null)
                {
                    project = new Project { Name = UT_ProjectName };
                    db.Projects.Add(project);
                    db.SaveChanges();
                }

                var token = DateTime.Now.ToString("yyyyMMddHHmmss");
                project.Name = UT_ProjectName + "_" + token;
                db.SaveChanges();

                Assert.AreEqual(string.Format("{0}--{1}", UT_ProjectName, project.Name), result, "AfterSaveChanges_Entity_Modified - Failed");
            }
        }

        [TestMethod]
        public void AfterSaveChanges_Entity_Ignore_Modified()
        {
            int result = 0;

            TrackingContext.Current.Subscribe<EFTrackingContext>(TrackingEvent.AfterSaveChanges, (s) =>
            {
                s.For<Project>()
                    .Where(EntityTrackingTypes.Modified)
                    .Perform((content, item) =>
                    {
                        result++;
                    });
            });

            using (var db = new EFTrackingContext())
            {
                var project = db.Projects.SingleOrDefault(x => x.Name == UT_ProjectName);
                if (project == null)
                {
                    project = new Project { Name = UT_ProjectName };
                    db.Projects.Add(project);
                    db.SaveChanges();
                }

                var token1 = DateTime.Now.ToString("Test1_yyyyMMddHHmmss");
                project.Name = UT_ProjectName + "_" + token1;
                db.SaveChanges();

                Assert.AreEqual(1, result, "AfterSaveChanges_Entity_Ignore_Modified - Failed");

                var token2 = DateTime.Now.ToString("Test2_yyyyMMddHHmmss");
                project.Name = UT_ProjectName + "_" + token2;
                db.SaveChanges((x) =>
                    {
                        x.IgnoreEntity<EFTrackingContext, Project>(EntityTrackingTypes.Modified);
                    });

                Assert.AreEqual(1, result, "AfterSaveChanges_Entity_Ignore_Modified - Failed");
            }
        }
    }
}


text:
<?php
namespace TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures;

/**
 * Fixture for an original class
 */
class OriginalClassFixture
{
}


text:
using MongoDB.Bson.Serialization;
using MongoDB.Driver.GeoJsonObjectModel;
using NUnit.Framework;

namespace MongoDB.Driver.Tests.GeoJsonObjectModel
{
    public class GeoJson2DCoordinatesTests
    {
        [Test]
        public void TestDeserializeDoubles()
        {
            var json = "[1.0, 2.0]";
            var coordinates = BsonSerializer.Deserialize<GeoJson2DCoordinates>(json);
            Assert.AreEqual(1.0, coordinates.X);
            Assert.AreEqual(2.0, coordinates.Y);
        }

        [Test]
        public void TestDeserializeInts()
        {
            var json = "[1, 2]";
            var coordinates = BsonSerializer.Deserialize<GeoJson2DCoordinates>(json);
            Assert.AreEqual(1.0, coordinates.X);
            Assert.AreEqual(2.0, coordinates.Y);
        }
    }
}


text:
using UnityEngine;
using System;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;

namespace LSystem
{
    [ExecuteInEditMode]
    public class LSystem : MonoBehaviour
    {
        public enum ProcessingState
        {
            None,
            ConstructingString,
            CallingInterpreter
        }

        public ProcessingState currentState = ProcessingState.None;

        public List<Symbol> symbols;
        public string axiom;
        public List<Rule> rules;

        public string current = "";
        public int iterationCount = 0;

        public bool debugLogging = false;

        //Progress variables for UI
        private int currentStep = 0;
        private int currentChar = 0;
        private int stringLength = 0;

        private Thread processingThread;

        public int CurrentStep { get { return currentStep; } }
        public int CurrentChar { get { return currentChar; } }
        public int StringLength { get { return stringLength; } }

        Symbol CharToSymbol(char c)
        {
            Symbol retval = null;
            symbols.ForEach((Symbol s) =>
            {
                if (s.symbol == c)
                    retval = s;
            });

            return retval;
        }

        void Update()
        {
            if (currentState == ProcessingState.CallingInterpreter)
            {
                CallInterpreter();
            }
        }

        public void Process()
        {
            if (processingThread != null && processingThread.IsAlive)
            {
                PrintDebugLog("LSystem::Process() - Old thread is still alive, Aborting...");
                processingThread.Abort();
            }

            PrintDebugLog("LSystem::Process() - Starting new thread...");
            processingThread = new Thread(() =>
            {
                Step(iterationCount);
            });
            processingThread.Start();
            //Step(steps);
        }

        public void StopProcess()
        {
            if (processingThread != null && processingThread.IsAlive)
            {
                PrintDebugLog("LSystem::StopProcess() - Aborting the thread...");
                processingThread.Abort();
                processingThread.Join(100);
            }

            currentStep = 0;
            stringLength = 0;
            currentChar = char.MinValue;
        }

        void Step(int n)
        {
            PrintDebugLog("LSystem::Step() - Starting string construction.");

            currentState = ProcessingState.ConstructingString;

            for (int j = 0; j < n; j++)
            {
                currentStep = j + 1;

                Interpreter interp = (Interpreter)symbols[0].interpreter;
                if (interp != null)
                    interp.EmptyValues();

                if (current == "") current = axiom;

                string newCurrent = "";
                for (int i = 0; i < current.Length; i++)
                {
                    currentChar = i;
                    try
                    {
                        newCurrent += ApplyRules(current, i);
                    }
                    catch (ArgumentOutOfRangeException e)
                    {
                        PrintDebugLog("LSystem::Step() - Error on applying rules: " + e);
                    }
                }

                current = newCurrent;
                stringLength = current.Length;
            }

            PrintDebugLog("LSystem::Step() - String construction finished.");

            currentState = ProcessingState.CallingInterpreter;

            CallInterpreter();
        }

        void CallInterpreter()
        {
            currentState = ProcessingState.None;

            PrintDebugLog("LSystem::Step() - Starting the interpreter calls.");

            for (int i = 0; i < current.Length; i++)
            {
                currentChar = i;
                stringLength = current.Length;

                Symbol s = CharToSymbol(current[i]);
                if (s != null && s.interpreterMethod != "Null")
                {
                    typeof(Interpreter)
                        .GetMethod(s.interpreterMethod, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
                        .Invoke(s.interpreter, new object[0]);

                    //sInterp.SendMessage(s.interpreterMethod, SendMessageOptions.DontRequireReceiver);
                }
            }

            PrintDebugLog("LSystem::Step() - The interpreter calls finished.");
        }

        string ApplyRules(string _str, int _index)
        {
            char c = _str[_index];

            List<Rule> relevantRules = new List<Rule>();
            for (int i = 0; i < rules.Count; i++)
            {
                if (rules[i].predecessor == c)
                    relevantRules.Add(rules[i]);
            }

            if (relevantRules == null || relevantRules.Count <= 0) return c.ToString();

            PrintDebugLog("LSystem::ApplyRules() - index: " + _index + ", Relevant rules found: " + relevantRules.Count + ", Predecessor: " + c);
            for (int i = 0; i < relevantRules.Count; i++)
            {
                PrintDebugLog("i = " + i + ": " + relevantRules[i].ToString());
            }

            //Context check
            for (int i = relevantRules.Count - 1; i >= 0; i--)
            {
                //Without contexts the rule passes
                if (relevantRules[i].contextCount == 0)
                    continue;

                PrintDebugLog("LSystem::ApplyRules() - Checking rule " + relevantRules[i].ToString());

                //One context is given
                if (relevantRules[i].contextCount == 1)
                {
                    bool givenContextIsLeft;
                    if (relevantRules[i].leftContext != "")
                        givenContextIsLeft = true;
                    else
                        givenContextIsLeft = false;

                    PrintDebugLog("LSystem::ApplyRules() - One context given, it is " + (givenContextIsLeft ? "left" : "right"));

                    if (givenContextIsLeft)
                    {
                        if (CheckLeftContext(relevantRules[i], _str, _index))
                        {
                            PrintDebugLog("LSystem::ApplyRules() - Left context matched.");
                            continue;
                        }
                    }
                    else
                    {
                        if (CheckRightContext(relevantRules[i], _str, _index))
                        {
                            PrintDebugLog("LSystem::ApplyRules() - Right context matched.");
                            continue;
                        }
                    }
                }

                //Both contexts are given
                if (relevantRules[i].contextCount == 2)
                {
                    bool leftMatches = CheckLeftContext(relevantRules[i], _str, _index);
                    bool rightMatches = CheckRightContext(relevantRules[i], _str, _index);

                    if (relevantRules[i].contextSensitivity == Rule.ContextSensitivity.OR)
                    {
                        if (leftMatches || rightMatches)
                        {
                            PrintDebugLog("LSystem::ApplyRules() - OR sensitivity: One context matched, " + " Left: " + leftMatches + ", Right: " + rightMatches);
                            continue;
                        }
                    }

                    if (relevantRules[i].contextSensitivity == Rule.ContextSensitivity.AND)
                    {
                        if (leftMatches && rightMatches)
                        {
                            PrintDebugLog("LSystem::ApplyRules() - AND sensitivity: One context matched, " + " Left: " + leftMatches + ", Right: " + rightMatches);
                            continue;
                        }
                    }
                }

                PrintDebugLog("LSystem::ApplyRules() - Removing rule " + relevantRules[i].ToString());
                relevantRules.Remove(relevantRules[i]);
            }

            PrintDebugLog("LSystem::ApplyRules() - index: " + _index + ", Relevant rules left: " + relevantRules.Count + ", Predecessor: " + c);

            //If rules with context passed, use them only for probability checks
            List<Rule> relevantRulesWithContext = new List<Rule>();
            for (int i = 0; i < relevantRules.Count; i++)
            {
                if (relevantRules[i].contextCount > 0)
                    relevantRulesWithContext.Add(relevantRules[i]);
            }

            if (relevantRulesWithContext.Count > 0)
            {
                PrintDebugLog("LSystem::ApplyRules() - Rules with context passed, using them only for probability.");
                relevantRules = relevantRulesWithContext;
            }

            Rule chosen = null;

            if (relevantRules.Count > 0)
            {
                if (relevantRules.Count == 1)
                {
                    chosen = relevantRules[0];
                }
                else
                {
                    //Probability
                    float sumWeights = 0f;
                    relevantRules.ForEach(r => sumWeights += r.probability);

                    System.Random rObj = new System.Random(Guid.NewGuid().GetHashCode());
                    float rand = (float)rObj.NextDouble() * sumWeights;
                    PrintDebugLog("LSystem::ApplyRules() - Probability random value: " + rand);

                    for (int i = 0; i < relevantRules.Count; i++)
                    {
                        if (rand < relevantRules[i].probability)
                        {
                            chosen = relevantRules[i];
                            break;
                        }
                        rand -= relevantRules[i].probability;
                    }

                    if (chosen == null)
                    {
                        Debug.LogError("LSystem::ApplyRules() - Chosen rule null after probability! Something is wrong! Random was " + rand);
                    }
                }
            }
            else
            {
                PrintDebugLog("LSystem::ApplyRules() - None of the relevant rules applied.");
                return c.ToString();
            }

            PrintDebugLog("LSystem::ApplyRules() - index: " + _index + ", Chosen rule: " + chosen.ToString());
            return chosen.successsor;
        }

        bool CheckLeftContext(Rule _rule, string _str, int _index)
        {
            if (_index - _rule.leftContext.Length > 0 && _str.Length > _rule.leftContext.Length)
            {
                string leftContextInStr = _str.Substring(_index - _rule.leftContext.Length, _rule.leftContext.Length);
                bool leftContextMatch = leftContextInStr.CompareTo(_rule.leftContext) == 0;
                if (leftContextInStr != "")
                {
                    PrintDebugLog("LSystem::CheckLeftContext() - Left context: " + _rule.leftContext);
                    PrintDebugLog("LSystem::CheckLeftContext() - Left context in current: " + leftContextInStr);
                }

                return leftContextMatch;
            }

            return false;
        }

        bool CheckRightContext(Rule _rule, string _str, int _index)
        {
            if (_index + _rule.rightContext.Length + 1 < _str.Length)
            {
                string rightContextInStr = _str.Substring(_index + 1, _rule.rightContext.Length);
                bool rightContextMatch = rightContextInStr.CompareTo(_rule.rightContext) == 0;
                if (rightContextInStr != "")
                {
                    PrintDebugLog("LSystem::CheckRightContext() - Right context: " + _rule.rightContext);
                    PrintDebugLog("LSystem::CheckRightContext() - Right context in current: " + rightContextInStr);
                }

                return rightContextMatch;
            }

            return false;
        }

        void PrintDebugLog(string msg)
        {
            if (debugLogging)
                Debug.Log(msg);
        }
    }
}


text:
"use strict";

/**
 * Gulp usage file for the whole project.
 */

var gulp = require("gulp");
var ts = require("gulp-typescript");
var eventStream = require("event-stream");
var tslint = require("gulp-tslint");
var sequence = require("run-sequence").use(gulp);
var babel = require("gulp-babel");
var path = require("path");

var typeScriptSource = ["./src/main/typescript/**/*.ts" ];
var typeScriptDestination = "./src/main/resources/static/js/";

// TYPESCRIPT COMPILATION
gulp.task("typescript", function() {
    return gulp
        .src( typeScriptSource )
        // Pipe source to lint
       // .pipe(tslint())
       // .pipe(tslint.report("verbose"))
        // Push through to compiler
        .pipe(ts({
            typescript: require("typescript"),
            declarationFiles: false,
            noImplicitAny: true,
            noExternalResolve: false,
            removeComments: true,
            target: "es6",
            showErrors: true
        }))
        // Through babel (es6->es5)
        .pipe(babel({
            comments: false,
            presets: [ "es2015" ]
        }))
        .pipe(gulp.dest(typeScriptDestination));

});

/**
 * Run with: 'gulp w'
 */
gulp.task("w", function() {
    gulp.watch(typeScriptSource, [ "typescript" ]);
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <base href="<?php echo $system['siteRoot'];?>" />

    <title><?php echo $r['pageTitle'];?> - LikyhCMS管理系统</title>
    <link href="plugin/cms/style/common.css" rel="stylesheet"/>
    <?php if($r['component']&CmsView::TYPE_FORM){ ?>
        <link href="plugin/cms/style/form.css" rel="stylesheet"/>
    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_TABLE){ ?>
        <link href="plugin/cms/style/table.css" rel="stylesheet"/>
    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_ITEM_LIST){ ?>

    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_STATE){ ?>

    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_JQUERY){ ?>

    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_DATETIME){ ?>

    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_EDITOR){ ?>

    <?php } ?>
    <?php if($r['component']&CmsView::TYPE_MAP){ ?>

    <?php } ?>

            <div class="title <?php echo $r['logoCopyright']?"show":"hidden";?>">@LikyhCMS

LikyhCMS管理系统

        <?php echo $r['userInfoHtml']; ?>

        <?php echo $r['navHtml']; ?>

            <?php import_tpl('plugin/cms/contentTitle.php'); ?>
            <?php echo $r['controlHtml']; ?>

                <?php import_tpl($r['sourceTpl']);?>

    <?php import_tpl('plugin/cms/footer.php'); ?>


text:
<?php
/**
 * Created by PhpStorm.
 * User: sz
 * Date: 24.04.15
 * Time: 13:27
 */

namespace modules\contract\models\query;

use modules\contract\models\Contract;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class ContractQuery extends ActiveQuery
{

    public function city($cityId = null){
        return $this->innerJoinWith([
            'city' => function($query) use($cityId){
                if($cityId)
                    $query->andWhere(['city.ID' => $cityId]);
            }
        ]);
    }

    public function state($stateId = null){
        return $this->innerJoinWith([
            'city.state' => function($query) use($stateId){
                if($stateId)
                    $query->andWhere(['state.id' => $stateId]);
            }
        ]);
    }

    public function country($countryId = null){
        return $this->innerJoinWith([
            'city.country' => function($query) use($countryId){
                $query->from('country c1');
                if($countryId)
                    $query->andWhere(['c1.id' => $countryId]);
            },
            'city.state.country' => function($query) use($countryId){
                $query->from('country c2');
                if($countryId)
                    $query->andWhere(['c2.id' => $countryId]);
            }
        ]);
    }

    /*
     * Избранные контракты для контракта $contractId
     * */
    public function favorite($contractId){
        return $this->innerJoinWith([
            'favoriteCompanies' => function($query) use($contractId){
                $query->andWhere(['contract_id' => $contractId]);
            }
        ]);
    }

    public function competitors($contract){
        $directions = ArrayHelper::getColumn($contract->directions, 'id');
        $this->innerJoinWith([
            'directions' => function($query) use($directions){
                $query->andWhere([
                    'direction.id' => $directions
                ]);
            }
        ])->andWhere([
            'contract.city_id' => $contract->city_id,
        ])->andWhere([
            '<>', 'contract.id', $contract->id
        ]);
        return $this;
    }

}


text:
package im.actor.runtime.actors.mailbox;

import im.actor.runtime.actors.dispatch.AbstractDispatchQueue;
import im.actor.runtime.actors.dispatch.DispatchResult;
import im.actor.runtime.actors.mailbox.collections.EnvelopeRoot;

/**
 * Queue of multiple mailboxes for MailboxesDispatcher
 */
public class MailboxesQueue extends AbstractDispatchQueue<Envelope> {

    private EnvelopeRoot envelopeRoot;

    public MailboxesQueue() {
        envelopeRoot = new EnvelopeRoot(this);
    }

    public EnvelopeRoot getEnvelopeRoot() {
        return envelopeRoot;
    }

    public void unlockMailbox(Mailbox mailbox) {
        envelopeRoot.attachCollection(mailbox.getEnvelopes());
    }

    public void disconnectMailbox(Mailbox mailbox) {
        envelopeRoot.detachCollection(mailbox.getEnvelopes());
    }

    public void notifyQueueChanged() {
        super.notifyQueueChanged();
    }

    @Override
    public DispatchResult dispatch(long time) {
        EnvelopeRoot.FetchResult res = envelopeRoot.fetchCollection(time);
        if (res == null) {
            return delay(FOREVER);
        }

        if (res.getEnvelope() != null) {
            DispatchResult result = result(res.getEnvelope());
            res.recycle();
            return result;
        } else {
            DispatchResult result = delay(res.getDelay());
            res.recycle();
            return result;
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace CJia.Health.Web.UI
{
    public partial class ReadBorrowView : CJia.Health.Tools.Page, CJia.Health.Views.Web.IReadBorrowView
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (OnLoadBorrow != null && Session["User"] != null)
                {
                    readBorrowArgs.UserData = Session["User"] as DataTable;
                    OnLoadBorrow(null, readBorrowArgs);
                }
            }
        }

        protected override object CreatePresenter()
        {
            return new Presenters.Web.ReadBorrowPresenter(this);
        }

        Views.Web.ReadBorrowArgs readBorrowArgs = new Views.Web.ReadBorrowArgs();
        public event EventHandler<Views.Web.ReadBorrowArgs> OnLoadBorrow;

        public void ExeBindBorrow(DataTable data)
        {
            if (data != null)
            {
                PatientGridView.DataSource = data;
                PatientGridView.DataBind();
                lblMsg.Visible = false;
                Session["BorrowDetailData"] = new DataTable();
                Session["BorrowDetailData"] = data;
            }
            else
            {
                lblMsg.Visible = true;
            }
        }

        protected void gvCity_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "MyPatient")
            {
                string recordNO = e.CommandArgument.ToString();
                DataTable patientData = Session["BorrowDetailData"] as DataTable;
                DataRow[] onePatient = patientData.Select(" RECORDNO='" + recordNO + "'");
                Session["OnePatientData"] = patientData.NewRow();
                Session["OnePatientData"] = onePatient[0];
                string patientName = onePatient[0]["PATIENT_NAME"].ToString() + "「" + onePatient[0]["RECORDNO"].ToString() + "」";
                RunScript("top.myTab.Cts('" + patientName + "','PatientInfoView.aspx',true);");
                //Response.Redirect("PatientInfoView.aspx");
            }
        }

        private void RunScript(string script)
        {
            this.ClientScript.RegisterStartupScript(this.GetType(), script, script, true);
        }

        protected void gvCity_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "currentColor=this.style.backgroundColor;this.style.backgroundColor='#FFE4B5';");//FFE4B5 6ed0ff
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentColor;");
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Core.TestFramework;
using NUnit.Framework;

namespace Azure.Core.Tests
{
    public class ClientTestBaseTests : ClientTestBase
    {
        public ClientTestBaseTests(bool isAsync) : base(isAsync)
        {
            TestDiagnostics = false;
        }

        [Test]
        public void AllowsUsingSyncMethodsWithoutAsyncAlternative()
        {
            TestClient client = InstrumentClient(new TestClient());
            var result = client.Method2();

            Assert.AreEqual("Hello", result);
        }

        [Test]
        public async Task CallsCorrectMethodBasedOnCtorArgument()
        {
            TestClient client = InstrumentClient(new TestClient());
            var result = await client.MethodAsync(123);

            Assert.AreEqual(IsAsync ? "Async 123 False" : "Sync 123 False", result);
        }

        [Test]
        public async Task CallsCorrectGenericParameterMethodBasedOnCtorArgument()
        {
            TestClient client = InstrumentClient(new TestClient());
            var result = await client.MethodGenericAsync(123);

            Assert.AreEqual(IsAsync ? "Async 123 False" : "Sync 123 False", result);
        }

        [Test]
        public async Task WorksWithCancellationToken()
        {
            TestClient client = InstrumentClient(new TestClient());
            var result = await client.MethodAsync(123, new CancellationTokenSource().Token);

            Assert.AreEqual(IsAsync ? "Async 123 True" : "Sync 123 True", result);
        }

        [Test]
        public void ThrowsForInvalidClientTypes()
        {
            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => InstrumentClient(new InvalidTestClient()));
            Assert.AreEqual("Client type contains public non-virtual async method MethodAsync", exception.Message);
        }

        [Test]
        public void ThrowsForSyncCallsInAsyncContext()
        {
            if (IsAsync)
            {
                TestClient client = InstrumentClient(new TestClient());
                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => client.Method(123));
                Assert.AreEqual("Async method call expected for Method", exception.Message);
            }
        }

        [Test]
        public void ThrowsWhenSyncMethodIsNotAvailable()
        {
            if (!IsAsync)
            {
                TestClient client = InstrumentClient(new TestClient());
                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => client.NoAlternativeAsync(123));
                Assert.AreEqual("Unable to find a method with name NoAlternative and System.Int32,System.Threading.CancellationToken parameters." +
                                " Make sure both methods have the same signature including the cancellationToken parameter", exception.Message);
            }
        }

        /// <summary>
        /// Validate the interceptor is ignored when we're using SyncOnly.
        /// </summary>
        [Test]
        [SyncOnly]
        public void SyncOnlyDoesNotIntercept()
        {
            TestClient client = InstrumentClient(new TestClient());
            client.Method(42);
        }

        /// <summary>
        /// Ensure we can resolve sync/async methods that only vary based on
        /// generic type parameters.
        /// </summary>
        [Test]
        public async Task CustomUserSchemaPatternResolves()
        {
            TestClient client = InstrumentClient(new TestClient());
            string responseDataPrefix = IsAsync ? "async" : "sync";
            const string arg = "genericArg";

            // Static schema
            Response<string> staticData = await client.GetDataAsync<string>();
            Assert.AreEqual($"{responseDataPrefix} - static", staticData.GetRawResponse().ReasonPhrase);

            // Static schema with generic arg
            Response<string> staticGenericData = await client.GetDataAsync<string>(arg);
            Assert.AreEqual($"{responseDataPrefix} - static {arg}", staticGenericData.GetRawResponse().ReasonPhrase);

            // Dynamic schema
            Response<object> dynamicData = await client.GetDataAsync();
            Assert.AreEqual($"{responseDataPrefix} - dynamic", dynamicData.GetRawResponse().ReasonPhrase);
        }

        /// <summary>
        /// Ensure failures in sync/async methods that only vary based on
        /// generic type parameters are thrown correctly.
        /// </summary>
        [Test]
        public async Task CustomUserSchemaPatternThrows()
        {
            TestClient client = InstrumentClient(new TestClient());
            string exceptionPrefix = IsAsync ? "async" : "sync";

            // Static schema
            try { await client.GetFailureAsync<string>(); }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual($"{exceptionPrefix} - static", ex.Message);
            }

            // Dynamic schema
            try { await client.GetFailureAsync(); }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual($"{exceptionPrefix} - dynamic", ex.Message);
            }
        }

        [Test]
        public async Task GetClientCallsAreAutoInstrumented()
        {
            TestClient client = InstrumentClient(new TestClient());

            TestClient subClient = client.GetAnotherTestClient();
            var result = await subClient.MethodAsync(123);

            Assert.AreEqual(IsAsync ? "Async 123 False" : "Sync 123 False", result);
        }

        [Test]
        public async Task SubClientPropertyCallsAreAutoInstrumented()
        {
            TestClient client = InstrumentClient(new TestClient());

            TestClientOperations subClient = client.SubProperty;
            var result = await subClient.MethodAsync(123);

            Assert.AreEqual(IsAsync ? "Async 123 False" : "Sync 123 False", result);
        }

        [Test]
        public void CanGetUninstrumentedClient()
        {
            var testClient = new TestClient();
            TestClient client = InstrumentClient(testClient);

            Assert.AreSame(GetOriginal(client), testClient);
        }

        [Test]
        [NonParallelizable]
        public async Task TasksValidateOwnScopes()
        {
            TestDiagnostics = true;

            TestClient client = InstrumentClient(new TestClient());

            var t1 = Task.Run(async () =>
            {
                for (int i = 0; i < 100; ++i)
                {
                    await client.MethodAAsync();
                }
            });

            var t2 = Task.Run(async () =>
            {
                for (int i = 0; i < 100; ++i)
                {
                    await client.MethodBAsync();
                }
            });
            await Task.WhenAll(t1, t2);
        }
    }
}


text:
set names iso88591;

--compare with constant
prepare st1 from 'select position(? in ?)';
execute st1 using 'ab','AB,aB,ab,Ab';
set names iso88591 collate iso88591_en_ci;
execute st1 using 'ABc','abc,AbC,aBc,ABc,ABC';
set names utf8 collate utf8_en_cs;
execute st1 using 'AaB','a,ab,aab,AAb,AaB,aAB';

execute st1 using _iso88591'ABc','abc,AbC,aBc,ABc,ABC';
execute st1 using 'AaB',_euckr'a,ab,aab,AAb,AaB,aAB';

--with subquery
prepare st1 from 'select position(? in (select ? from db_root))';
execute st1 using 'ab','AB,aB,ab,Ab';
set names iso88591 collate iso88591_en_ci;
execute st1 using 'ABc','abc,AbC,aBc,ABc,ABC';
set names utf8 collate utf8_en_cs;
execute st1 using 'AaB','a,ab,aab,AAb,AaB,aAB';

execute st1 using _iso88591'ABc','abc,AbC,aBc,ABc,ABC';
execute st1 using 'AaB',_euckr'a,ab,aab,AAb,AaB,aAB';

drop table if exists t;
create table t(s1 varchar(10) collate utf8_en_ci, s2 enum('ab', 'Ab', 'AB', 'aB') collate iso88591_en_cs);
insert into t values('aB', 1);
insert into t values('Ab', 'aB');

--compare with s1
prepare st2 from 'select s1, position(s1 in ?+?) from t order by 1, 2';
execute st2 using 'a', 'b';
set names utf8 collate utf8_en_ci;
execute st2 using 'A', 'B';
set names utf8 collate utf8_en_cs;
execute st2 using 'A', 'b';
set names euckr;
execute st2 using 'a', 'B';

execute st2 using _iso88591'a', 'b';
execute st2 using _euckr'A', _utf8'b';

--compare with s2
prepare st3 from 'select s2, position(s2 in ?+?) from t order by 1, 2';
execute st3 using 'a', 'b';
set names utf8 collate utf8_en_ci;
execute st3 using 'A', 'B';
set names utf8 collate utf8_en_cs;
execute st3 using 'A', 'b';
set names euckr;
execute st3 using 'a', 'B';

execute st3 using _iso88591'a', 'b';
execute st3 using _euckr'A', _euckr'B';

--session variable
set @a1='aB' collate utf8_en_cs;
set @a2='Ab' collate utf8_en_ci;
set @b1='Ab' collate utf8_en_cs;
set @b2='B' collate iso88591_en_ci;

set names iso88591;
execute st1 using 'a', @a1;
execute st1 using _utf8'Ab', @b2;
execute st1 using _utf8'Ab', @a2;
execute st1 using @b1, @a2;

prepare st2 from 'select position(s1 in ?) from t order by 1';
set names utf8;
execute st2 using @a1;
execute st2 using @b1;

prepare st3 from 'select position(s2 in ?) from t order by 1';
set names euckr;
execute st3 using @b2;
execute st3 using @a2;

drop variable @a1, @a2, @b1, @b2;

deallocate prepare st1;
deallocate prepare st2;
deallocate prepare st3;

drop table t;

set names iso88591;

--+ holdcas off;


text:
/* $Id$ */

#ifndef DNS_CACHE_H
#define DNS_CACHE_H 1

/*****
 ***** Module Info
 *****/

/*! \file dns/cache.h
 * \brief
 * Defines dns_cache_t, the cache object.
 *
 * Notes:
 *\li 	A cache object contains DNS data of a single class.
 *	Multiple classes will be handled by creating multiple
 *	views, each with a different class and its own cache.
 *
 * MP:
 *\li	See notes at the individual functions.
 *
 * Reliability:
 *
 * Resources:
 *
 * Security:
 *
 * Standards:
 */

/***
 ***	Imports
 ***/

#include <isc/lang.h>
#include <isc/stdtime.h>

#include <dns/types.h>

ISC_LANG_BEGINDECLS

/***
 ***	Functions
 ***/

isc_result_t
dns_cache_create(isc_mem_t *cmctx, isc_taskmgr_t *taskmgr,
		 isc_timermgr_t *timermgr, dns_rdataclass_t rdclass,
		 const char *db_type, unsigned int db_argc, char **db_argv,
		 dns_cache_t **cachep);
isc_result_t
dns_cache_create2(isc_mem_t *cmctx, isc_taskmgr_t *taskmgr,
		  isc_timermgr_t *timermgr, dns_rdataclass_t rdclass,
		  const char *cachename, const char *db_type,
		  unsigned int db_argc, char **db_argv, dns_cache_t **cachep);
isc_result_t
dns_cache_create3(isc_mem_t *cmctx, isc_mem_t *hmctx, isc_taskmgr_t *taskmgr,
		  isc_timermgr_t *timermgr, dns_rdataclass_t rdclass,
		  const char *cachename, const char *db_type,
		  unsigned int db_argc, char **db_argv, dns_cache_t **cachep);
/*%<
 * Create a new DNS cache.
 *
 * dns_cache_create2() will create a named cache.
 *
 * dns_cache_create3() will create a named cache using two separate memory
 * contexts, one for cache data which can be cleaned and a separate one for
 * memory allocated for the heap (which can grow without an upper limit and
 * has no mechanism for shrinking).
 *
 * dns_cache_create() is a backward compatible version that internally
 * specifies an empty cache name and a single memory context.
 *
 * Requires:
 *
 *\li	'cmctx' (and 'hmctx' if applicable) is a valid memory context.
 *
 *\li	'taskmgr' is a valid task manager and 'timermgr' is a valid timer
 * 	manager, or both are NULL.  If NULL, no periodic cleaning of the
 * 	cache will take place.
 *
 *\li	'cachename' is a valid string.  This must not be NULL.
 *
 *\li	'cachep' is a valid pointer, and *cachep == NULL
 *
 * Ensures:
 *
 *\li	'*cachep' is attached to the newly created cache
 *
 * Returns:
 *
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 */

void
dns_cache_attach(dns_cache_t *cache, dns_cache_t **targetp);
/*%<
 * Attach *targetp to cache.
 *
 * Requires:
 *
 *\li	'cache' is a valid cache.
 *
 *\li	'targetp' points to a NULL dns_cache_t *.
 *
 * Ensures:
 *
 *\li	*targetp is attached to cache.
 */

void
dns_cache_detach(dns_cache_t **cachep);
/*%<
 * Detach *cachep from its cache.
 *
 * Requires:
 *
 *\li	'cachep' points to a valid cache.
 *
 * Ensures:
 *
 *\li	*cachep is NULL.
 *
 *\li	If '*cachep' is the last reference to the cache,
 *		all resources used by the cache will be freed
 */

void
dns_cache_attachdb(dns_cache_t *cache, dns_db_t **dbp);
/*%<
 * Attach *dbp to the cache's database.
 *
 * Notes:
 *
 *\li	This may be used to get a reference to the database for
 *	the purpose of cache lookups (XXX currently it is also
 * 	the way to add data to the cache, but having a
 * 	separate dns_cache_add() interface instead would allow
 * 	more control over memory usage).
 *	The caller should call dns_db_detach() on the reference
 *	when it is no longer needed.
 *
 * Requires:
 *
 *\li	'cache' is a valid cache.
 *
 *\li	'dbp' points to a NULL dns_db *.
 *
 * Ensures:
 *
 *\li	*dbp is attached to the database.
 */

isc_result_t
dns_cache_setfilename(dns_cache_t *cache, const char *filename);
/*%<
 * If 'filename' is non-NULL, make the cache persistent.
 * The cache's data will be stored in the given file.
 * If 'filename' is NULL, make the cache non-persistent.
 * Files that are no longer used are not unlinked automatically.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li	Various file-related failures
 */

isc_result_t
dns_cache_load(dns_cache_t *cache);
/*%<
 * If the cache has a file name, load the cache contents from the file.
 * Previous cache contents are not discarded.
 * If no file name has been set, do nothing and return success.
 *
 * MT:
 *\li	Multiple simultaneous attempts to load or dump the cache
 * 	will be serialized with respect to one another, but
 *	the cache may be read and updated while the dump is
 *	in progress.  Updates performed during loading
 *	may or may not be preserved, and reads may return
 * 	either the old or the newly loaded data.
 *
 * Returns:
 *
 *\li	#ISC_R_SUCCESS
 *  \li    Various failures depending on the database implementation type
 */

isc_result_t
dns_cache_dump(dns_cache_t *cache);
/*%<
 * If the cache has a file name, write the cache contents to disk,
 * overwriting any preexisting file.  If no file name has been set,
 * do nothing and return success.
 *
 * MT:
 *\li	Multiple simultaneous attempts to load or dump the cache
 * 	will be serialized with respect to one another, but
 *	the cache may be read and updated while the dump is
 *	in progress.  Updates performed during the dump may
 * 	or may not be reflected in the dumped file.
 *
 * Returns:
 *
 *\li	#ISC_R_SUCCESS
 *  \li    Various failures depending on the database implementation type
 */

isc_result_t
dns_cache_clean(dns_cache_t *cache, isc_stdtime_t now);
/*%<
 * Force immediate cleaning of the cache, freeing all rdatasets
 * whose TTL has expired as of 'now' and that have no pending
 * references.
 */

void
dns_cache_setcleaninginterval(dns_cache_t *cache, unsigned int interval);
/*%<
 * Set the periodic cache cleaning interval to 'interval' seconds.
 */

unsigned int
dns_cache_getcleaninginterval(dns_cache_t *cache);
/*%<
 * Get the periodic cache cleaning interval to 'interval' seconds.
 */

isc_uint32_t
dns_cache_getcachesize(dns_cache_t *cache);
/*%<
 * Get the maximum cache size.
 */

const char *
dns_cache_getname(dns_cache_t *cache);
/*%<
 * Get the cache name.
 */

void
dns_cache_setcachesize(dns_cache_t *cache, isc_uint32_t size);
/*%<
 * Set the maximum cache size.  0 means unlimited.
 */

isc_uint32_t
dns_cache_getcachesize(dns_cache_t *cache);
/*%<
 * Get the maximum cache size.
 */

isc_result_t
dns_cache_flush(dns_cache_t *cache);
/*%<
 * Flushes all data from the cache.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 */

isc_result_t
dns_cache_flushname(dns_cache_t *cache, dns_name_t *name);
/*
 * Flushes a given name from the cache.
 *
 * Requires:
 *\li	'cache' to be valid.
 *\li	'name' to be valid.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li	other error returns.
 */

ISC_LANG_ENDDECLS

#endif /* DNS_CACHE_H */


text:
package org.jboss.hal.client.configuration.subsystem.messaging;

import java.util.Map;

import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.core.CrudOperations;
import org.jboss.hal.core.mbui.dialog.AddResourceDialog;
import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.meta.AddressTemplate;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Callback;

import static org.jboss.hal.dmr.ModelDescriptionConstants.EXTERNAL_JMS_QUEUE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.EXTERNAL_JMS_TOPIC;

enum RemoteActiveMQSubResource {

    CONNECTION_FACTORY(Ids.MESSAGING_CONNECTION_FACTORY, Names.CONNECTION_FACTORY,
            ModelDescriptionConstants.CONNECTION_FACTORY, AddressTemplates.CONNECTION_FACTORY_REMOTE_TEMPLATE),

    CONNECTOR(Ids.MESSAGING_CONNECTOR, Names.GENERIC_CONNECTOR,
            ModelDescriptionConstants.CONNECTOR, AddressTemplates.CONNECTOR_REMOTE_TEMPLATE),

    JGROUPS_DISCOVERY_GROUP(Ids.MESSAGING_JGROUPS_DISCOVERY_GROUP, Names.JGROUPS_DISCOVERY_GROUP,
            ModelDescriptionConstants.JGROUPS_DISCOVERY_GROUP, AddressTemplates.JGROUPS_DISCOVERY_GROUP_REMOTE_TEMPLATE),

    SOCKET_DISCOVERY_GROUP(Ids.MESSAGING_SOCKET_DISCOVERY_GROUP, Names.SOCKET_DISCOVERY_GROUP,
            ModelDescriptionConstants.SOCKET_DISCOVERY_GROUP, AddressTemplates.SOCKET_DISCOVERY_GROUP_REMOTE_TEMPLATE),

    EXTERNAL_QUEUE(EXTERNAL_JMS_QUEUE, Names.EXTERNAL_JMS_QUEUE,
            EXTERNAL_JMS_QUEUE, AddressTemplates.EXTERNAL_JMS_QUEUE_TEMPLATE),

    EXTERNAL_TOPIC(EXTERNAL_JMS_TOPIC, Names.EXTERNAL_JMS_TOPIC,
            EXTERNAL_JMS_TOPIC, AddressTemplates.EXTERNAL_JMS_TOPIC_TEMPLATE),

    HTTP_CONNECTOR(Ids.MESSAGING_HTTP_CONNECTOR, Names.HTTP_CONNECTOR,
            ModelDescriptionConstants.HTTP_CONNECTOR, AddressTemplates.HTTP_CONNECTOR_REMOTE_TEMPLATE),

    IN_VM_CONNECTOR(Ids.MESSAGING_IN_VM_CONNECTOR, Names.IN_VM_CONNECTOR,
            ModelDescriptionConstants.IN_VM_CONNECTOR, AddressTemplates.IN_VM_CONNECTOR_REMOTE_TEMPLATE),

    POOLED_CONNECTION_FACTORY(Ids.MESSAGING_POOLED_CONNECTION_FACTORY, Names.POOLED_CONNECTION_FACTORY,
            ModelDescriptionConstants.POOLED_CONNECTION_FACTORY, AddressTemplates.POOLED_CONNECTION_FACTORY_REMOTE_TEMPLATE),

    REMOTE_CONNECTOR(Ids.MESSAGING_REMOTE_CONNECTOR, Names.REMOTE_CONNECTOR,
            ModelDescriptionConstants.REMOTE_CONNECTOR, AddressTemplates.REMOTE_CONNECTOR_REMOTE_TEMPLATE);

    final String baseId;
    final String type;
    final String resource;
    final AddressTemplate template;

    RemoteActiveMQSubResource(final String baseId, final String type, final String resource, final AddressTemplate template) {
        this.baseId = baseId;
        this.type = type;
        this.resource = resource;
        this.template = template;
    }

    void add(MetadataRegistry metadataRegistry, StatementContext statementContext,
            CrudOperations crud, Resources resources, CrudOperations.AddCallback callback) {
        Metadata metadata = metadataRegistry.lookup(template);
        new AddResourceDialog(Ids.build(baseId, Ids.ADD), resources.messages().addResourceTitle(type), metadata,
                (name, model) -> {
                    ResourceAddress address = template.resolve(statementContext, name);
                    crud.add(type, name, address, model, callback);
                }).show();
    }

    void save(Form<NamedNode> form, Map<String, Object> changedValues, MetadataRegistry metadataRegistry,
            StatementContext statementContext, CrudOperations crud, Callback callback) {
        String name = form.getModel().getName();
        ResourceAddress address = template.resolve(statementContext, name);
        Metadata metadata = metadataRegistry.lookup(template);
        crud.save(type, name, address, changedValues, metadata, callback);
    }

    void reset(Form<NamedNode> form, MetadataRegistry metadataRegistry, StatementContext statementContext,
            CrudOperations crud, Callback callback) {
        String name = form.getModel().getName();
        ResourceAddress address = template.resolve(statementContext, name);
        Metadata metadata = metadataRegistry.lookup(template);
        crud.reset(type, name, address, form, metadata, callback);
    }

    void remove(NamedNode item, StatementContext statementContext, CrudOperations crud, Callback callback) {
        String name = item.getName();
        ResourceAddress address = template.resolve(statementContext, name);
        crud.remove(type, name, address, callback);
    }
}


text:
namespace native
{
	static thread_local Thread* _current = nullptr;

	Thread::Thread(const Function<void>& func) : _handle(nullptr), _func(func), _started(false), _id(0)
	{
		start(_func);
	}

	Thread::~Thread()
	{
		while (_handle != nullptr && !_started)
			yield();
	}

	void Thread::start(const Function<void>& func)
	{
		if (_handle != nullptr)
			throw InvalidStateException();

		_func = func;

		// Create the Thread resource with the OS.
		_handle = ::CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(&entryPoint), this, 0, NULL);

		if (_handle == NULL)
			throw InsufficientResourcesException();
	}

	void Thread::join() const
	{
		::WaitForSingleObject(_handle, INFINITE);
	}

	void Thread::sleep(uint32_t milliSeconds)
	{
		if (milliSeconds > MAXDWORD)
			milliSeconds = MAXDWORD;

		::Sleep(milliSeconds);
	}

	void Thread::yield()
	{
		::YieldProcessor();
	}

	Thread* Thread::getCurrent()
	{
		return _current;
	}

	int64_t Thread::getCurrentId()
	{
		return ::GetCurrentThreadId();
	}

	ptrint_t Thread::entryPoint(Thread* thread)
	{
		_current = thread;
		thread->_started = true;

		try
		{
			// Execute the Thread's Function.
			thread->_func();
		}
		catch (...)
		{
			return 1;
		}

		_current = nullptr;
		return 0;
	}
}


text:
namespace autofill {

// Matches a FormStructure if its signature is the same as that of the
// PasswordForm |form|.
MATCHER_P(SignatureIsSameAs,
          form,
          std::string(negation ? "signature isn't " : "signature is ") +
              FormStructure(form.form_data).FormSignatureAsStr()) {
  if (FormStructure(form.form_data).FormSignatureAsStr() ==
      arg.FormSignatureAsStr())
    return true;

  *result_listener << "signature is " << arg.FormSignatureAsStr() << " instead";
  return false;
}

MATCHER_P(SignatureIs,
          signature,
          std::string(negation ? "signature isn't " : "signature is ") +
              base::NumberToString(signature.value())) {
  if (signature == arg.form_signature())
    return true;

  *result_listener << "signature is " << arg.form_signature() << " instead";
  return false;
}

// The matcher argument is a FormStructure.
MATCHER_P(
    SubmissionEventIsSameAs,
    expected_submission_event,
    std::string(negation ? "submission event isn't " : "submission event is ") +
        base::NumberToString(static_cast<int>(expected_submission_event))) {
  FormStructureTestApi test_api(const_cast<FormStructure*>(&arg));
  if (expected_submission_event == test_api.get_submission_event())
    return true;

  *result_listener << "submission event is " << test_api.get_submission_event()
                   << " instead";
  return false;
}

// Consumes a FormFieldData as `arg` and a map of field name (u16string) to
// a ServerFieldType type.
MATCHER_P(UploadedAutofillTypesAre, expected_types, "") {
  size_t fields_matched_type_count = 0;
  bool conflict_found = false;
  for (const auto& field : arg) {
    fields_matched_type_count +=
        base::Contains(expected_types, field->name) ? 1 : 0;
    if (field->possible_types().size() > 1) {
      *result_listener << (conflict_found ? ", " : "") << "Field "
                       << field->name << ": has several possible types";
      conflict_found = true;
    }

    ServerFieldType expected_vote =
        base::Contains(expected_types, field->name)
            ? expected_types.find(field->name)->second
            : UNKNOWN_TYPE;
    ServerFieldType actual_vote = field->possible_types().empty()
                                      ? UNKNOWN_TYPE
                                      : *field->possible_types().begin();
    if (expected_vote != actual_vote) {
      *result_listener << (conflict_found ? ", " : "") << "Field "
                       << field->name << ": expected vote " << expected_vote
                       << " but found " << actual_vote;
      conflict_found = true;
    }
  }
  if (expected_types.size() != fields_matched_type_count) {
    *result_listener << (conflict_found ? ", " : "")
                     << "Some types were expected but not found in the vote";
    return false;
  }

  return !conflict_found;
}

// Consumes a FormFieldData as `arg` and a map of field name (u16string) to
// a ServerFieldTypeSet type.
MATCHER_P(UploadedAutofillTypesAreSet, expected_types, "") {
  size_t fields_matched_type_count = 0;
  bool conflict_found = false;
  for (const auto& field : arg) {
    fields_matched_type_count +=
        base::Contains(expected_types, field->name) ? 1 : 0;
    ServerFieldTypeSet unknown_type_set = {ServerFieldType::UNKNOWN_TYPE};
    ServerFieldTypeSet expected_votes =
        base::Contains(expected_types, field->name)
            ? expected_types.find(field->name)->second
            : unknown_type_set;
    ServerFieldTypeSet actual_votes = field->possible_types().empty()
                                          ? unknown_type_set
                                          : field->possible_types();
    if (expected_votes != actual_votes) {
      *result_listener << (conflict_found ? ", " : "") << "Field "
                       << field->name << ": expected votes " << expected_votes
                       << " but found " << actual_votes;
      conflict_found = true;
    }
  }
  if (expected_types.size() != fields_matched_type_count) {
    *result_listener << (conflict_found ? ", " : "")
                     << "Some types were expected but not found in the vote";
    return false;
  }

  return !conflict_found;
}

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_TEST_UTILS_VOTE_UPLOADS_TEST_MATCHERS_H_


text:
package com.ligadata.keyvaluestore.mapdb

import org.mapdb._;
import com.ligadata.keyvaluestore._
import java.io.File;
import java.nio.ByteBuffer
import org.apache.logging.log4j._
import com.ligadata.Exceptions._
import com.ligadata.Exceptions.StackTrace

/*

No schema setup

 */

class KeyValueHashMapTx(owner: DataStore) extends Transaction {
  var parent: DataStore = owner

  def add(source: IStorage) = { owner.add(source) }
  def put(source: IStorage) = { owner.put(source) }
  def get(key: Key, target: IStorage) = { owner.get(key, target) }
  def get(key: Key, handler: (Value) => Unit) = { owner.get(key, handler) }
  def del(key: Key) = { owner.del(key) }
  def del(source: IStorage) = { owner.del(source) }
  def getAllKeys(handler: (Key) => Unit) = { owner.getAllKeys(handler) }
  def putBatch(sourceArray: Array[IStorage]) = { owner.putBatch(sourceArray) }
  def delBatch(keyArray: Array[Key]) = { owner.delBatch(keyArray) }
}

class KeyValueHashMap(parameter: PropertyMap) extends DataStore {
  var path = parameter.getOrElse("path", ".")
  var keyspace = parameter.getOrElse("schema", "default")
  var table = parameter.getOrElse("table", "default")

  val InMemory = parameter.getOrElse("inmemory", "false").toBoolean
  val withTransactions = parameter.getOrElse("withtransaction", "false").toBoolean

  val loggerName = this.getClass.getName
  val logger = LogManager.getLogger(loggerName)

  var db: DB = null

  if (InMemory == true) {
    db = DBMaker.newMemoryDB()
      .make()
  } else {
    val dir = new File(path);
    if (!dir.exists()){
      // attempt to create the directory here
      dir.mkdir();
    }
    db = DBMaker.newFileDB(new File(path + "/" + keyspace + ".hdb"))
      .closeOnJvmShutdown()
      .mmapFileEnable()
      .transactionDisable()
      .commitFileSyncDisable()
      .make()
  }

  var map = db.createHashMap(table)
    .hasher(Hasher.BYTE_ARRAY)
    .makeOrGet[Array[Byte], Array[Byte]]()

  def add(source: IStorage) =
    {
      map.putIfAbsent(source.Key.toArray[Byte], source.Value.toArray[Byte])
      if (withTransactions)
        db.commit() //persist changes into disk
    }

  def put(source: IStorage) =
    {
      map.put(source.Key.toArray[Byte], source.Value.toArray[Byte])
      if (withTransactions)
        db.commit() //persist changes into disk
    }

  def putBatch(sourceArray: Array[IStorage]) =
    {
      sourceArray.foreach( source => {
	map.put(source.Key.toArray[Byte], source.Value.toArray[Byte])
      })
      if (withTransactions)
	db.commit() //persist changes into disk
    }

  def delBatch(keyArray: Array[Key]) =
  {
    keyArray.foreach( k => {
      map.remove(k.toArray[Byte])
    })
    if (withTransactions)
      db.commit() //persist changes into disk
  }

  def get(key: Key, handler: (Value) => Unit) =
    {
      val buffer = map.get(key.toArray[Byte])

      // Construct the output value
      val value = new Value
      if (buffer != null) {
        value ++= buffer
      } else {
        throw new KeyNotFoundException("Key Not found")
      }

      handler(value)
    }

  def get(key: Key, target: IStorage) =
    {
      val buffer = map.get(key.toArray[Byte])

      // Construct the output value
      val value = new Value
      if (buffer != null) {
        value ++= buffer
      } else {
        throw new KeyNotFoundException("Key Not found")
      }

      target.Construct(key, value)
    }

  def del(key: Key) =
    {
      map.remove(key.toArray[Byte])
      if (withTransactions)
        db.commit(); //persist changes into disk
    }

  def del(source: IStorage) = { del(source.Key) }

  def beginTx(): Transaction = { new KeyValueHashMapTx(this) }

  def endTx(tx: Transaction) = {}

  def commitTx(tx: Transaction) = {}

  override def Shutdown() = {
    if( db != null && db.isClosed() == false ){
      logger.debug("Trying to shutdown hashmap db")
      try{
	db.commit(); //persist changes into disk
	db = null
	map.close();
      }catch{
	case e:NullPointerException =>{

	  logger.error("Unexpected Null pointer exception when closing hashmap, seems like internal bug related to mapdb ")
	}
	case e:Exception =>{

	  logger.error("Unexpected error when closing hashmap " + e.getMessage())
	}
      }
    }
  }

  def TruncateStore() {
    map.clear()
    if (withTransactions)
      db.commit() //persist changes into disk

    // Defrag on startup
    db.compact()
  }

  def getAllKeys(handler: (Key) => Unit) =
    {
      var iter = map.keySet().iterator()
      while (iter.hasNext()) {
        val buffer = iter.next()

        // Construct the output value
        // BUGBUG-jh-20140703: There should be a more concise way to get the data
        //
        val key = new Key
        for (b <- buffer)
          key += b

        handler(key)
      }
    }
}


text:
A minimal syntax highlighting theme for [Visual Studio Code](http://code.visualstudio.com)

![image](./screenshot.png)

## Installation

1. Go to `View -> Extensions`
1. Search for `Minimal Colors`
1. Click the `Install` button
1. Click `Reload` if prompted

## Activate it

1. Go to `View -> Command Palette...`
1. Type `Preferences: Color Theme` and hit Enter
1. Choose the `Minimal Colors` theme

## License

[MIT License](./LICENSE)


text:
using namespace ouro::tests;

#define oTEST_REGISTER_MESH_TEST0(_Name) oTEST_THROWS_REGISTER0(oCONCAT(oMesh_, _Name), oCONCAT(TEST, _Name))
#define oTEST_REGISTER_MESH_TEST(_Name) oTEST_THROWS_REGISTER(oCONCAT(oMesh_, _Name), oCONCAT(TEST, _Name))

#define oTEST_REGISTER_MESH_TEST_BUGGED0(_Name) oTEST_THROWS_REGISTER_BUGGED0(oCONCAT(oMesh_, _Name), oCONCAT(TEST, _Name))
#define oTEST_REGISTER_MESH_TEST_BUGGED(_Name) oTEST_THROWS_REGISTER_BUGGED(oCONCAT(oMesh_, _Name), oCONCAT(TEST, _Name))

oTEST_REGISTER_MESH_TEST(obj);


text:
package cn.zxl.xmlbean.converter.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
 * 注解工具类
 * @author 左潇龙
 * @version 1.0.0
 * @since 1.0.0
 */
public class Annotations {

	private Annotations(){}

	/**
	 * 获取属性的所有注解
	 * @param field field
	 * @return Annotation[]
	 */
	public static Annotation[] getAnnotations(Field field){
		return field.getAnnotations();
	}

	/**
	 * 获取属性指定类型的注解
	 * @param field field
	 * @return Annotation
	 */
	public static Annotation getAnnotation(Field field,Class<? extends Annotation> clazz){
		return field.getAnnotation(clazz);
	}

}


text:
<title>
Will Jeb Bush execute an innocent man?
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Scheduled to be killed after 26 years

Will Jeb Bush execute an innocent man?

By Elizabeth Schulte | February 28, 2003 | Page 2

ON FEBRUARY 26, Florida Gov. Jeb Bush wants to execute a man who has languished on death row for 26 years for a crime he says he didn't commit.

Last December, Amos King came within 15 minutes of being put to death when Bush issued a 30-day stay of execution so DNA tests could be conducted on new evidence. The tests came back inconclusive because the evidence is so old. But George W. Bush's baby brother set a new date for killing King anyway.

King's story underlines all the reasons why the death penalty should be abolished. King, who is Black and poor, was convicted of raping and killing an elderly white woman, Natalie Brady, in 1977.

At the time of the murder, King was living in a minimum-security prison. Prosecutors claimed that after King got off work from his job at a local restaurant, he broke into Brady's house, tortured, raped and stabbed Brady to death.

The coroner made up a story that Brady's rapist jabbed knitting needles into the victim's vagina--and the prosecution used this sickening detail to link the crime to King, using the testimony of a prison counselor who said he found King that night with blood on his shirt and pants.

King's clothes were examined, and no blood was found. And the prosecution never produced the pants at the trial. But they didn't need to. The horrifying story was enough for the all-white jurors--whose average age was 65 years old--to convict King. And eight years later, the coroner recanted the knitting needle story.

King's lawyer, a public defender, handed over his client's life on a silver platter. King was familiar with lawyer Thomas Cole's work--Cole was responsible for King's previous conviction on a gun theft charge. When King petitioned for another public defender, the court refused. Cole was so unprepared for King's capital trial that he himself asked to be taken off the case. But the judge refused that, too.

Anything that could have gone wrong for King did. But he has fought for 26 long years to expose the truth. Now Jeb Bush wants to bury the truth.

"The judicial system has failed," King wrote in a letter sent to Socialist Worker. "I have complained of ineffective counsel for over 25 years, even to the governor himself, knowing that an execution can be held on this evidence. I'm an innocent man."

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
using namespace std;
using namespace nspace;

BoxRenderer::BoxRenderer(const Hexahedron & box):
    _textRenderer(0),
_box(box),
_p(box.coordinates().position()){
  boxExtent(0) = box.getXExtent();
  boxExtent(1) = box.getYExtent();
  boxExtent(2) = box.getZExtent();
}
void BoxRenderer::render(){
  Matrix3x3 RT;
  _box.coordinates().orientation().toTransposedRotationMatrix(RT);
  //texture.bind();
  MiniGL::drawCube(
    _p,
    RT,
    (float)boxExtent(0),
    (float)boxExtent(1),
    (float)boxExtent(2),
    MiniGL::gray);
  _textPosition = _p + Vector3D(boxExtent(0)+0.1,0.1,0.1);
  //texture.unbind();
  //if(_textRenderer) _textRenderer->render();
}

bool BoxRenderer::initializeObject(){
//  *simulation()<<texture;
  if(!_box.hasName())return true;
  const string & name =_box.name();
  _textRenderer = new TextRenderer(name,_textPosition);
  return true;
}