text:
var get = Ember.get;
var set = Ember.set;
var resolve = Ember.RSVP.resolve;
var TestAdapter, store, person;
var run = Ember.run;

module("unit/store/adapter_interop - DS.Store working with a DS.Adapter", {
  setup: function() {
    TestAdapter = DS.Adapter.extend();
  },
  teardown: function() {
    run(function() {
      if (store) { store.destroy(); }
    });
  }
});

test("Adapter can be set as a factory", function() {
  store = createStore({ adapter: TestAdapter });

  ok(store.get('defaultAdapter') instanceof TestAdapter);
});

test('Adapter can be set as a name', function() {
  store = createStore({ adapter: '-rest' });

  ok(store.get('defaultAdapter') instanceof DS.RESTAdapter);
});

test('Default RESTAdapter has been deprecated', function() {
  expectDeprecation(function() {
    run(function() {
      store = createStore({ adapter: '-rest' });
    });
  }, /You are currently using the default DS.RESTAdapter adapter. For Ember 2.0 the default adapter will be DS.JSONAPIAdapter. If you would like to continue using DS.RESTAdapter please create an application adapter that extends DS.RESTAdapter./);
});

test('Adapter can not be set as an instance', function() {
  expect(1);

  store = DS.Store.create({
    adapter: DS.Adapter.create()
  });
  expectAssertion(() => store.get('defaultAdapter'));
});

test("Calling Store#find invokes its adapter#find", function() {
  expect(5);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      ok(true, "Adapter#find was called");
      equal(store, currentStore, "Adapter#find was called with the right store");
      equal(type, store.modelFor('test'), "Adapter#find was called with the type passed into Store#find");
      equal(id, 1, "Adapter#find was called with the id passed into Store#find");
      equal(snapshot.id, '1', "Adapter#find was called with the record created from Store#find");

      return Ember.RSVP.resolve({ id: 1 });
    }
  });

  var currentType = DS.Model.extend();
  var currentStore = createStore({ adapter: adapter, test: currentType });

  run(function() {
    currentStore.findRecord('test', 1);
  });
});

test("Calling Store#findRecord multiple times coalesces the calls into a adapter#findMany call", function() {
  expect(2);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      ok(false, "Adapter#findRecord was not called");
    },
    findMany: function(store, type, ids, snapshots) {
      start();
      ok(true, "Adapter#findMany was called");
      deepEqual(ids, ["1","2"], 'Correct ids were passed in to findMany');
      return Ember.RSVP.resolve([{ id: 1 }, { id: 2 }]);
    },
    coalesceFindRequests: true
  });

  var currentType = DS.Model.extend();
  var currentStore = createStore({ adapter: adapter, test: currentType });

  stop();
  run(function() {
    currentStore.findRecord('test', 1);
    currentStore.findRecord('test', 2);
  });
});

test("Returning a promise from `findRecord` asynchronously loads data", function() {
  expect(1);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      return resolve({ id: 1, name: "Scumbag Dale" });
    }
  });

  var currentType = DS.Model.extend({
    name: DS.attr('string')
  });
  var currentStore = createStore({ adapter: adapter, test: currentType });

  run(function() {
    currentStore.findRecord('test', 1).then(async(function(object) {
      strictEqual(get(object, 'name'), "Scumbag Dale", "the data was pushed");
    }));
  });
});

test("IDs provided as numbers are coerced to strings", function() {
  expect(4);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      equal(typeof id, 'string', "id has been normalized to a string");
      return resolve({ id: 1, name: "Scumbag Sylvain" });
    }
  });

  var currentType = DS.Model.extend({
    name: DS.attr('string')
  });
  var currentStore = createStore({ adapter: adapter, test: currentType });

  run(function() {
    currentStore.findRecord('test', 1).then(async(function(object) {
      equal(typeof object.get('id'), 'string', "id was coerced to a string");
      run(function() {
        currentStore.push('test', { id: 2, name: "Scumbag Sam Saffron" });
      });
      return currentStore.findRecord('test', 2);
    })).then(async(function(object) {
      ok(object, "object was found");
      equal(typeof object.get('id'), 'string', "id is a string despite being supplied and searched for as a number");
    }));
  });
});

var array = [{ id: "1", name: "Scumbag Dale" }, { id: "2", name: "Scumbag Katz" }, { id: "3", name: "Scumbag Bryn" }];

test("can load data for the same record if it is not dirty", function() {
  expect(3);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = createStore({
    person: Person
  });

  run(function() {
    store.push('person', { id: 1, name: "Tom Dale" });

    store.findRecord('person', 1).then(async(function(tom) {
      equal(get(tom, 'hasDirtyAttributes'), false, "precond - record is not dirty");
      equal(get(tom, 'name'), "Tom Dale", "returns the correct name");

      store.push('person', { id: 1, name: "Captain Underpants" });
      equal(get(tom, 'name'), "Captain Underpants", "updated record with new date");
    }));
  });
});

/*
test("DS.Store loads individual records without explicit IDs with a custom primaryKey", function() {
  var store = DS.Store.create();
  var Person = DS.Model.extend({ name: DS.attr('string'), primaryKey: 'key' });

  store.load(Person, { key: 1, name: "Tom Dale" });

  var tom = store.findRecord(Person, 1);
  equal(get(tom, 'name'), "Tom Dale", "the person was successfully loaded for the given ID");
});
*/

test("pushMany extracts ids from an Array of hashes if no ids are specified", function() {
  expect(1);

  var Person = DS.Model.extend({ name: DS.attr('string') });

  var store = createStore({
    person: Person
  });

  run(function() {
    store.pushMany('person', array);
    store.findRecord('person', 1).then(async(function(person) {
      equal(get(person, 'name'), "Scumbag Dale", "correctly extracted id for loaded data");
    }));
  });
});

test("loadMany takes an optional Object and passes it on to the Adapter", function() {
  expect(2);

  var passedQuery = { page: 1 };

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var adapter = TestAdapter.extend({
    query: function(store, type, query) {
      equal(type, store.modelFor('person'), 'The type was Person');
      equal(query, passedQuery, "The query was passed in");
      return Ember.RSVP.resolve([]);
    }
  });

  var store = createStore({
    adapter: adapter,
    person: Person
  });

  run(function() {
    store.query('person', passedQuery);
  });
});

test("Find with query calls the correct extract", function() {
  var passedQuery = { page: 1 };

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var adapter = TestAdapter.extend({
    query: function(store, type, query) {
      return Ember.RSVP.resolve([]);
    }
  });

  var callCount = 0;

  var ApplicationSerializer = DS.JSONSerializer.extend({
    extractFindQuery: function(store, type, payload) {
      callCount++;
      return [];
    }
  });

  var env = setupStore({
    adapter: adapter,
    person: Person
  });
  var store = env.store;

  env.registry.register('serializer:application', ApplicationSerializer);

  run(function() {
    store.query('person', passedQuery);
  });
  equal(callCount, 1, 'extractQuery was called');
});

test("peekAll(type) returns a record array of all records of a specific type", function() {
  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = createStore({
    person: Person
  });

  run(function() {
    store.push('person', { id: 1, name: "Tom Dale" });
  });

  var results = store.peekAll('person');
  equal(get(results, 'length'), 1, "record array should have the original object");
  equal(get(results.objectAt(0), 'name'), "Tom Dale", "record has the correct information");

  run(function() {
    store.push('person', { id: 2, name: "Yehuda Katz" });
  });
  equal(get(results, 'length'), 2, "record array should have the new object");
  equal(get(results.objectAt(1), 'name'), "Yehuda Katz", "record has the correct information");

  strictEqual(results, store.peekAll('person'), "subsequent calls to peekAll return the same recordArray)");
});

test("a new record of a particular type is created via store.createRecord(type)", function() {
  var Person = DS.Model.extend({
    name: DS.attr('string')
  });
  var person;

  var store = createStore({
    person: Person
  });

  run(function() {
    person = store.createRecord('person');
  });

  equal(get(person, 'isLoaded'), true, "A newly created record is loaded");
  equal(get(person, 'isNew'), true, "A newly created record is new");
  equal(get(person, 'hasDirtyAttributes'), true, "A newly created record is dirty");

  run(function() {
    set(person, 'name', "Braaahm Dale");
  });

  equal(get(person, 'name'), "Braaahm Dale", "Even if no hash is supplied, `set` still worked");
});

test("a new record with a specific id can't be created if this id is already used in the store", function() {
  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  Person.reopenClass({
    toString: function() {
      return 'Person';
    }
  });

  var store = createStore({
    person: Person
  });

  run(function() {
    store.createRecord('person', { id: 5 });
  });

  expectAssertion(function() {
    run(function() {
      store.createRecord('person', { id: 5 });
    });
  }, /The id 5 has already been used with another record of type Person/);
});

test("an initial data hash can be provided via store.createRecord(type, hash)", function() {
  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = createStore({
    person: Person
  });

  run(function() {
    person = store.createRecord('person', { name: "Brohuda Katz" });
  });

  equal(get(person, 'isLoaded'), true, "A newly created record is loaded");
  equal(get(person, 'isNew'), true, "A newly created record is new");
  equal(get(person, 'hasDirtyAttributes'), true, "A newly created record is dirty");

  equal(get(person, 'name'), "Brohuda Katz", "The initial data hash is provided");
});

test("if an id is supplied in the initial data hash, it can be looked up using `store.find`", function() {
  expect(1);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });
  var store = createStore({
    person: Person
  });
  var person;

  run(function() {
    person = store.createRecord('person', { id: 1, name: "Brohuda Katz" });
    store.findRecord('person', 1).then(async(function(again) {
      strictEqual(person, again, "the store returns the loaded object");
    }));
  });
});

test("initial values of attributes can be passed in as the third argument to find", function() {
  expect(1);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      equal(snapshot.attr('name'), 'Test', 'Preloaded attribtue set');
      return Ember.RSVP.resolve({ id: '1', name: 'Test' });
    }
  });

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = createStore({
    adapter: adapter,
    test: Person
  });

  run(function() {
    store.findRecord('test', 1, { preload: { name: 'Test' } });
  });
});

test("initial values of belongsTo can be passed in as the third argument to find as records", function() {
  expect(1);
  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      equal(snapshot.belongsTo('friend').attr('name'), 'Tom', 'Preloaded belongsTo set');
      return new Ember.RSVP.Promise(function() {});
    }
  });

  var env = setupStore({
    adapter: adapter
  });
  var store = env.store;

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    friend: DS.belongsTo('person', { inverse: null, async: true })
  });

  env.registry.register('model:person', Person);
  var tom;

  run(function() {
    tom = store.push('person', { id: 2, name: 'Tom' });
    store.findRecord('person', 1, { preload: { friend: tom } });
  });
});

test("initial values of belongsTo can be passed in as the third argument to find as ids", function() {
  expect(1);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      return Ember.RSVP.Promise.resolve({ id: id });
    }
  });

  var env = setupStore({
    adapter: adapter
  });
  var store = env.store;

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    friend: DS.belongsTo('person', { async: true, inverse: null })
  });

  env.registry.register('model:person', Person);

  run(function() {
    store.findRecord('person', 1, { preload: { friend: 2 } }).then(async(function() {
      store.peekRecord('person', 1).get('friend').then(async(function(friend) {
        equal(friend.get('id'), '2', 'Preloaded belongsTo set');
      }));
    }));
  });
});

test("initial values of hasMany can be passed in as the third argument to find as records", function() {
  expect(1);
  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      equal(snapshot.hasMany('friends')[0].attr('name'), 'Tom', 'Preloaded hasMany set');
      return new Ember.RSVP.Promise(function() {});
    }
  });

  var env = setupStore({
    adapter: adapter
  });
  var store = env.store;

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    friends: DS.hasMany('person', { inverse: null, async: true })
  });

  env.registry.register('model:person', Person);
  var tom;

  run(function() {
    tom = store.push('person', { id: 2, name: 'Tom' });
    store.findRecord('person', 1, { preload: { friends: [tom] } });
  });
});

test("initial values of hasMany can be passed in as the third argument to find as ids", function() {
  expect(1);

  var adapter = TestAdapter.extend({
    findRecord: function(store, type, id, snapshot) {
      equal(snapshot.hasMany('friends')[0].id, '2', 'Preloaded hasMany set');
      return Ember.RSVP.resolve({ id: id });
    }
  });

  var env = setupStore({
    adapter: adapter
  });
  var store = env.store;

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    friends: DS.hasMany('person', { async: true, inverse: null })
  });

  env.registry.register('model:person', Person);

  run(function() {
    store.findRecord('person', 1, { preload: { friends: [2] } });
  });
});

test("records should have their ids updated when the adapter returns the id data", function() {
  expect(2);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var idCounter = 1;
  var adapter = TestAdapter.extend({
    createRecord: function(store, type, snapshot) {
      return Ember.RSVP.resolve({ name: snapshot.attr('name'), id: idCounter++ });
    }
  });

  var store = createStore({
    adapter: adapter,
    person: Person
  });

  var people = store.peekAll('person');
  var tom, yehuda;

  run(function() {
    tom = store.createRecord('person', { name: 'Tom Dale' });
    yehuda = store.createRecord('person', { name: 'Yehuda Katz' });
  });

  run(function() {
    Ember.RSVP.all([tom.save(), yehuda.save()]).then(async(function() {
      people.forEach(function(person, index) {
        equal(person.get('id'), index + 1, "The record's id should be correct.");
      });
    }));
  });
});

test("store.fetchMany should always return a promise", function() {
  expect(3);

  var Person = DS.Model.extend();
  var store = createStore({
    adapter: TestAdapter.extend(),
    person: Person
  });
  run(function() {
    store.createRecord('person');
  });
  var records = Ember.A([]);
  var results;

  run(function() {
    results = store.scheduleFetchMany(records);
  });
  ok(results, "A call to store.scheduleFetchMany() should return a result");
  ok(results.then, "A call to store.scheduleFetchMany() should return a promise");

  results.then(async(function(returnedRecords) {
    deepEqual(returnedRecords, [], "The correct records are returned");
  }));
});

test("store.scheduleFetchMany should not resolve until all the records are resolved", function() {
  expect(1);

  var Person = DS.Model.extend();
  var Phone = DS.Model.extend();

  var adapter = TestAdapter.extend({
    findRecord: function (store, type, id, snapshot) {
      var wait = 5;

      var record = { id: id };

      return new Ember.RSVP.Promise(function(resolve, reject) {
        run.later(function() {
          resolve(record);
        }, wait);
      });
    },

    findMany: function(store, type, ids, snapshots) {
      var wait = 15;

      var records = ids.map(function(id) {
        return { id: id };
      });

      return new Ember.RSVP.Promise(function(resolve, reject) {
        run.later(function() {
          resolve(records);
        }, wait);
      });
    }
  });

  var store = createStore({
    adapter: adapter,
    test: Person,
    phone: Phone
  });

  run(function() {
    store.createRecord('test');
  });

  var records = Ember.A([
    store.recordForId('test', 10),
    store.recordForId('phone', 20),
    store.recordForId('phone', 21)
  ]);

  run(function() {
    store.scheduleFetchMany(records).then(async(function() {
      var unloadedRecords = records.filterBy('isEmpty');
      equal(get(unloadedRecords, 'length'), 0, 'All unloaded records should be loaded');
    }));
  });
});

test("the store calls adapter.findMany according to groupings returned by adapter.groupRecordsForFindMany", function() {
  expect(3);

  var Person = DS.Model.extend();

  var adapter = TestAdapter.extend({
    groupRecordsForFindMany: function(store, snapshots) {
      return [
        [snapshots[0]],
        [snapshots[1], snapshots[2]]
      ];
    },

    findRecord: function(store, type, id, snapshot) {
      equal(id, "10", "The first group is passed to find");
      return Ember.RSVP.resolve({ id: id });
    },

    findMany: function(store, type, ids, snapshots) {
      var records = ids.map(function(id) {
        return { id: id };
      });

      deepEqual(ids, ["20", "21"], "The second group is passed to findMany");

      return new Ember.RSVP.Promise(function(resolve, reject) {
        resolve(records);
      });
    }
  });

  var store = createStore({
    adapter: adapter,
    test: Person
  });

  var records = Ember.A([
    store.recordForId('test', 10),
    store.recordForId('test', 20),
    store.recordForId('test', 21)
  ]);

  run(function() {
    store.scheduleFetchMany(records).then(async(function() {
      var ids = records.mapBy('id');
      deepEqual(ids, ["10", "20", "21"], "The promise fulfills with the records");
    }));
  });
});

test("the promise returned by `scheduleFetch`, when it resolves, does not depend on the promises returned to other calls to `scheduleFetch` that are in the same run loop, but different groups", function() {
  expect(2);

  var Person = DS.Model.extend();
  var davidResolved = false;

  var adapter = TestAdapter.extend({
    groupRecordsForFindMany: function (store, snapshots) {
      return [
        [snapshots[0]],
        [snapshots[1]]
      ];
    },

    findRecord: function(store, type, id, snapshot) {
      var record = { id: id };

      return new Ember.RSVP.Promise(function(resolve, reject) {
        if (id === 'igor') {
          resolve(record);
        } else {
          run.later(function () {
            davidResolved = true;
            resolve(record);
          }, 5);
        }
      });
    }
  });

  var store = createStore({
    adapter: adapter,
    test: Person
  });

  run(function () {
    var davidPromise = store.findRecord('test', 'david');
    var igorPromise = store.findRecord('test', 'igor');

    igorPromise.then(async(function () {
      equal(davidResolved, false, "Igor did not need to wait for David");
    }));

    davidPromise.then(async(function () {
      equal(davidResolved, true, "David resolved");
    }));
  });
});

test("the promise returned by `scheduleFetch`, when it rejects, does not depend on the promises returned to other calls to `scheduleFetch` that are in the same run loop, but different groups", function() {
  expect(2);

  var Person = DS.Model.extend();
  var davidResolved = false;

  var adapter = TestAdapter.extend({
    groupRecordsForFindMany: function(store, snapshots) {
      return [
        [snapshots[0]],
        [snapshots[1]]
      ];
    },

    findRecord: function(store, type, id, snapshot) {
      var record = { id: id };

      return new Ember.RSVP.Promise(function(resolve, reject) {
        if (id === 'igor') {
          reject(record);
        } else {
          run.later(function () {
            davidResolved = true;
            resolve(record);
          }, 5);
        }
      });
    }
  });

  var store = createStore({
    adapter: adapter,
    test: Person
  });

  run(function () {
    var davidPromise = store.findRecord('test', 'david');
    var igorPromise = store.findRecord('test', 'igor');

    igorPromise.then(null, async(function () {
      equal(davidResolved, false, "Igor did not need to wait for David");
    }));

    davidPromise.then(async(function () {
      equal(davidResolved, true, "David resolved");
    }));
  });
});

test("store.fetchRecord reject records that were not found, even when those requests were coalesced with records that were found", function() {
  expect(4);

  var Person = DS.Model.extend();

  var adapter = TestAdapter.extend({
    findMany: function(store, type, ids, snapshots) {
      var records = ids.map(function(id) {
        return { id: id };
      });

      return new Ember.RSVP.Promise(function(resolve, reject) {
        resolve([
          records[0]
        ]);
      });
    }
  });

  var store = createStore({
    adapter: adapter,
    test: Person
  });

  warns(function() {
    run(function () {
      var davidPromise = store.findRecord('test', 'david');
      var igorPromise = store.findRecord('test', 'igor');

      davidPromise.then(async(function () {
        ok(true, "David resolved");
      }));

      igorPromise.then(null, async(function () {
        ok(true, "Igor rejected");
      }));
    });
  }, /expected to find records with the following ids in the adapter response but they were missing/);
});

test("store should not call shouldReloadRecord when the record is not in the store", function() {
  expect(1);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadRecord: function(store, type, id, snapshot) {
      ok(false, 'shouldReloadRecord should not be called when the record is not loaded');
      return false;
    },
    findRecord: function() {
      ok(true, 'find is always called when the record is not in the store');
      return { id: 1 };
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.findRecord('person', 1);
  });
});

test("store should not reload record when shouldReloadRecord returns false", function() {
  expect(1);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadRecord: function(store, type, id, snapshot) {
      ok(true, 'shouldReloadRecord should be called when the record is in the store');
      return false;
    },
    findRecord: function() {
      ok(false, 'find should not be called when shouldReloadRecord returns false');
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.push('person', { id: 1 });
    store.findRecord('person', 1);
  });
});

test("store should reload record when shouldReloadRecord returns true", function() {
  expect(3);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadRecord: function(store, type, id, snapshot) {
      ok(true, 'shouldReloadRecord should be called when the record is in the store');
      return true;
    },
    findRecord: function() {
      ok(true, 'find should not be called when shouldReloadRecord returns false');
      return { id: 1, name: 'Tom' };
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.push('person', { id: 1 });
    store.findRecord('person', 1).then(function(record) {
      equal(record.get('name'), 'Tom');
    });
  });
});

test("store should not call shouldBackgroundReloadRecord when the store is already loading the record", function() {
  expect(2);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadRecord: function(store, type, id, snapshot) {
      return true;
    },
    shouldBackgroundReloadRecord: function(store, type, id, snapshot) {
      ok(false, 'shouldBackgroundReloadRecord is not called when shouldReloadRecord returns true');
    },
    findRecord: function() {
      ok(true, 'find should be called');
      return { id: 1, name: 'Tom' };
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.push('person', { id: 1 });
    store.findRecord('person', 1).then(function(record) {
      equal(record.get('name'), 'Tom');
    });
  });
});

test("store should not reload a record when `shouldBackgroundReloadRecord` is false", function() {
  expect(2);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldBackgroundReloadRecord: function(store, type, id, snapshot) {
      ok(true, 'shouldBackgroundReloadRecord is called when record is loaded form the cache');
      return false;
    },
    findRecord: function() {
      ok(false, 'find should not be called');
      return { id: 1, name: 'Tom' };
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.push('person', { id: 1 });
    store.findRecord('person', 1).then(function(record) {
      equal(record.get('name'), undefined);
    });
  });
});

test("store should reload the record in the background when `shouldBackgroundReloadRecord` is true", function() {
  expect(4);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldBackgroundReloadRecord: function(store, type, id, snapshot) {
      ok(true, 'shouldBackgroundReloadRecord is called when record is loaded form the cache');
      return true;
    },
    findRecord: function() {
      ok(true, 'find should not be called');
      return { id: 1, name: 'Tom' };
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.push('person', { id: 1 });
    store.findRecord('person', 1).then(function(record) {
      equal(record.get('name'), undefined);
    });
  });

  equal(store.peekRecord('person', 1).get('name'), 'Tom');
});

test("store should not reload record array when shouldReloadAll returns false", function() {
  expect(1);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadAll: function(store, snapshot) {
      ok(true, 'shouldReloadAll should be called when the record is in the store');
      return false;
    },
    shouldBackgroundReloadAll: function(store, snapshot) {
      return false;
    },
    findAll: function() {
      ok(false, 'findAll should not be called when shouldReloadAll returns false');
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.find('person');
  });
});

test("store should reload all records when shouldReloadAll returns true", function() {
  expect(3);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadAll: function(store, type, id, snapshot) {
      ok(true, 'shouldReloadAll should be called when the record is in the store');
      return true;
    },
    findAll: function() {
      ok(true, 'findAll should be called when shouldReloadAll returns true');
      return [{ id: 1, name: 'Tom' }];
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.findAll('person').then(function(records) {
      equal(records.get('firstObject.name'), 'Tom');
    });
  });
});

test("store should not call shouldBackgroundReloadAll when the store is already loading all records", function() {
  expect(2);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadAll: function(store, type, id, snapshot) {
      return true;
    },
    shouldBackgroundReloadAll: function(store, type, id, snapshot) {
      ok(false, 'shouldBackgroundReloadRecord is not called when shouldReloadRecord returns true');
    },
    findAll: function() {
      ok(true, 'find should be called');
      return [{ id: 1, name: 'Tom' }];
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.findAll('person').then(function(records) {
      equal(records.get('firstObject.name'), 'Tom');
    });
  });
});

test("store should not reload all records when `shouldBackgroundReloadAll` is false", function() {
  expect(3);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadAll: function(store, type, id, snapshot) {
      ok(true, 'shouldReloadAll is called when record is loaded form the cache');
      return false;
    },
    shouldBackgroundReloadAll: function(store, type, id, snapshot) {
      ok(true, 'shouldBackgroundReloadAll is called when record is loaded form the cache');
      return false;
    },
    findAll: function() {
      ok(false, 'findAll should not be called');
      return [{ id: 1, name: 'Tom' }];
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.findAll('person').then(function(records) {
      equal(records.get('firstObject'), undefined);
    });
  });
});

test("store should reload all records in the background when `shouldBackgroundReloadAll` is true", function() {
  expect(5);

  var Person = DS.Model.extend({
    name: DS.attr('string')
  });

  var TestAdapter = DS.Adapter.extend({
    shouldReloadAll: function() {
      ok(true, 'shouldReloadAll is called');
      return false;
    },
    shouldBackgroundReloadAll: function(store, snapshot) {
      ok(true, 'shouldBackgroundReloadAll is called when record is loaded form the cache');
      return true;
    },
    findAll: function() {
      ok(true, 'find should not be called');
      return [{ id: 1, name: 'Tom' }];
    }
  });

  store = createStore({
    adapter: TestAdapter,
    person: Person
  });

  run(function() {
    store.findAll('person').then(function(records) {
      equal(records.get('firstObject.name'), undefined);
    });
  });

  equal(store.peekRecord('person', 1).get('name'), 'Tom');
});

module("unit/store/adapter_interop - find preload deprecations", {
  setup: function() {
    var Person = DS.Model.extend({
      name: DS.attr('string')
    });

    var TestAdapter = DS.Adapter.extend({
      findRecord: function(store, type, id, snapshot) {
        equal(snapshot.attr('name'), 'Tom');
        return Ember.RSVP.resolve({ id: id });
      }
    });

    store = createStore({
      adapter: TestAdapter,
      person: Person
    });
  },
  teardown: function() {
    run(function() {
      if (store) { store.destroy(); }
    });
  }
});

test("store#find with deprecated preload passes correct options to store#findRecord", function() {
  expect(2);

  var expectedOptions = { preload: { name: 'Tom' } };

  store.reopen({
    findRecord: function(modelName, id, options) {
      deepEqual(options, expectedOptions,
        'deprecated preload transformed to new options store#findRecord');
    }
  });

  expectDeprecation(
    function() {
      run(function() {
        store.find('person', 1, { name: 'Tom' });
      });
    },
    /Passing a preload argument to `store.find` is deprecated./
  );
});

test("Using store#find with preload is deprecated", function() {
  expect(2);

  expectDeprecation(
    function() {
      run(function() {
        store.find('person', 1, { name: 'Tom' });
      });
    },
    /Passing a preload argument to `store.find` is deprecated./
  );
});

test("Using store#fetchById with preload is deprecated", function() {
  expect(2);

  expectDeprecation(
    function() {
      run(function() {
        store.fetchById('person', 1, { name: 'Tom' });
      });
    },
    /Passing a preload argument to `store.fetchById` is deprecated./
  );
});

test("Using store#findById with preload is deprecated", function() {
  expect(2);

  expectDeprecation(
    function() {
      run(function() {
        store.findById('person', 1, { name: 'Tom' });
      });
    },
    /Passing a preload argument to `store.findById` is deprecated/
  );
});


text:
namespace System.Buffers.Pools
{
    public sealed class ManagedBufferPool : BufferPool
    {
        static ManagedBufferPool s_shared = new ManagedBufferPool();

        public static ManagedBufferPool Shared
        {
            get
            {
                return s_shared;
            }
        }

        public override OwnedMemory<byte> Rent(int minimumBufferSize)
        {
            var array = ArrayPool<byte>.Shared.Rent(minimumBufferSize);
            return new OwnedArray<byte>(array);
        }

        public override void Return(OwnedMemory<byte> buffer)
        {
            var ownedArray = buffer as OwnedArray<byte>;
            if (ownedArray == null) throw new InvalidOperationException("buffer not rented from this pool");
            ArrayPool<byte>.Shared.Return(ownedArray.Array);
            buffer.Dispose();
        }

        protected override void Dispose(bool disposing)
        {
            throw new NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.litho;

import static com.facebook.litho.EventDispatcherUtils.dispatchOnClick;

import android.view.View;
import androidx.annotation.Nullable;

/** Click listener that triggers its underlying event handler. */
class ComponentClickListener implements View.OnClickListener {

  private final @Nullable EventHandler<ClickEvent> mEventHandler;

  public ComponentClickListener(@Nullable EventHandler<ClickEvent> eventHandler) {
    mEventHandler = eventHandler;
  }

  @Override
  public void onClick(View view) {
    if (mEventHandler != null) {
      final boolean isTracing = ComponentsSystrace.isTracing();
      if (isTracing) {
        String componentClassName = "";
        if (mEventHandler.dispatchInfo.hasEventDispatcher != null) {
          componentClassName = mEventHandler.dispatchInfo.hasEventDispatcher.getClass().getName();
          if (componentClassName.length() > 100) {
            componentClassName = "";
          }
        }
        ComponentsSystrace.beginSection("onClick_<cls>" + componentClassName + "</cls>");
      }
      try {
        dispatchOnClick(mEventHandler, view);
      } finally {
        if (isTracing) {
          ComponentsSystrace.endSection();
        }
      }
    }
  }
}


text:
export const dot = {
  marginLeft: 4,
  marginRight: 4,
};

export const wrapper = {
  display: 'flex',
};


text:
/*
    This file is part of web3.js.

    web3.js is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    web3.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @file index.js
 * @author Fabian Vogelsteller <fabian@ethereum.org>
 * @author Marek Kotewicz <marek@parity.io>
 * @date 2017
 */

"use strict";

var _ = require('underscore');
var errors = require('web3-core-helpers').errors;
var formatters = require('web3-core-helpers').formatters;
var utils = require('web3-utils');
var promiEvent = require('web3-core-promievent');
var Subscriptions = require('web3-core-subscriptions').subscriptions;

var TIMEOUTBLOCK = 50;
var CONFIRMATIONBLOCKS = 24;

var Method = function Method(options) {

    if(!options.call || !options.name) {
        throw new Error('When creating a method you need to provide at least the "name" and "call" property.');
    }

    this.name = options.name;
    this.call = options.call;
    this.params = options.params || 0;
    this.inputFormatter = options.inputFormatter;
    this.outputFormatter = options.outputFormatter;
    this.transformPayload = options.transformPayload;
    this.extraFormatters = options.extraFormatters;

    this.requestManager = options.requestManager;

    // reference to eth.accounts
    this.accounts = options.accounts;

    this.defaultBlock = options.defaultBlock || 'latest';
    this.defaultAccount = options.defaultAccount || null;
};

Method.prototype.setRequestManager = function (requestManager, accounts) {
    this.requestManager = requestManager;

    // reference to eth.accounts
    if (accounts) {
        this.accounts = accounts;
    }

};

Method.prototype.createFunction = function (requestManager, accounts) {
    var func = this.buildCall();
    func.call = this.call;

    this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts);

    return func;
};

Method.prototype.attachToObject = function (obj) {
    var func = this.buildCall();
    func.call = this.call;
    var name = this.name.split('.');
    if (name.length > 1) {
        obj[name[0]] = obj[name[0]] || {};
        obj[name[0]][name[1]] = func;
    } else {
        obj[name[0]] = func;
    }
};

/**
 * Should be used to determine name of the jsonrpc method based on arguments
 *
 * @method getCall
 * @param {Array} arguments
 * @return {String} name of jsonrpc method
 */
Method.prototype.getCall = function (args) {
    return _.isFunction(this.call) ? this.call(args) : this.call;
};

/**
 * Should be used to extract callback from array of arguments. Modifies input param
 *
 * @method extractCallback
 * @param {Array} arguments
 * @return {Function|Null} callback, if exists
 */
Method.prototype.extractCallback = function (args) {
    if (_.isFunction(args[args.length - 1])) {
        return args.pop(); // modify the args array!
    }
};

/**
 * Should be called to check if the number of arguments is correct
 *
 * @method validateArgs
 * @param {Array} arguments
 * @throws {Error} if it is not
 */
Method.prototype.validateArgs = function (args) {
    if (args.length !== this.params) {
        throw errors.InvalidNumberOfParams(args.length, this.params, this.name);
    }
};

/**
 * Should be called to format input args of method
 *
 * @method formatInput
 * @param {Array}
 * @return {Array}
 */
Method.prototype.formatInput = function (args) {
    var _this = this;

    if (!this.inputFormatter) {
        return args;
    }

    return this.inputFormatter.map(function (formatter, index) {
        // bind this for defaultBlock, and defaultAccount
        return formatter ? formatter.call(_this, args[index]) : args[index];
    });
};

/**
 * Should be called to format output(result) of method
 *
 * @method formatOutput
 * @param {Object}
 * @return {Object}
 */
Method.prototype.formatOutput = function (result) {
    var _this = this;

    if(_.isArray(result)) {
        return result.map(function(res){
            return _this.outputFormatter && res ? _this.outputFormatter(res) : res;
        });
    } else {
        return this.outputFormatter && result ? this.outputFormatter(result) : result;
    }
};

/**
 * Should create payload from given input args
 *
 * @method toPayload
 * @param {Array} args
 * @return {Object}
 */
Method.prototype.toPayload = function (args) {
    var call = this.getCall(args);
    var callback = this.extractCallback(args);
    var params = this.formatInput(args);
    this.validateArgs(params);

    var payload = {
        method: call,
        params: params,
        callback: callback
    };

    if (this.transformPayload) {
        payload = this.transformPayload(payload);
    }

    return payload;
};

Method.prototype._confirmTransaction = function (defer, result, payload) {
    var method = this,
        promiseResolved = false,
        canUnsubscribe = true,
        timeoutCount = 0,
        confirmationCount = 0,
        intervalId = null,
        gasProvided = (_.isObject(payload.params[0]) && payload.params[0].gas) ? payload.params[0].gas : null,
        isContractDeployment = _.isObject(payload.params[0]) &&
            payload.params[0].data &&
            payload.params[0].from &&
            !payload.params[0].to;

    // add custom send Methods
    var _ethereumCalls = [
        new Method({
            name: 'getTransactionReceipt',
            call: 'eth_getTransactionReceipt',
            params: 1,
            inputFormatter: [null],
            outputFormatter: formatters.outputTransactionReceiptFormatter
        }),
        new Method({
            name: 'getCode',
            call: 'eth_getCode',
            params: 2,
            inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
        }),
        new Subscriptions({
            name: 'subscribe',
            type: 'eth',
            subscriptions: {
                'newBlockHeaders': {
                    subscriptionName: 'newHeads', // replace subscription with this name
                    params: 0,
                    outputFormatter: formatters.outputBlockFormatter
                }
            }
        })
    ];
    // attach methods to this._ethereumCall
    var _ethereumCall = {};
    _.each(_ethereumCalls, function (mthd) {
        mthd.attachToObject(_ethereumCall);
        mthd.requestManager = method.requestManager; // assign rather than call setRequestManager()
    });

    // fire "receipt" and confirmation events and resolve after
    var checkConfirmation = function (err, blockHeader, sub, existingReceipt) {
        if (!err) {
            // create fake unsubscribe
            if (!sub) {
                sub = {
                    unsubscribe: function () {
                        clearInterval(intervalId);
                    }
                };
            }
            // if we have a valid receipt we don't need to send a request
            return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result))
            // catch error from requesting receipt
            .catch(function (err) {
                sub.unsubscribe();
                promiseResolved = true;
                utils._fireError({message: 'Failed to check for transaction receipt:', data: err}, defer.eventEmitter, defer.reject);
            })
            // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false
            .then(function(receipt) {

                if (!receipt || !receipt.blockHash) {
                    throw new Error('Receipt missing or blockHash null');
                }

                // apply extra formatters
                if (method.extraFormatters && method.extraFormatters.receiptFormatter) {
                    receipt = method.extraFormatters.receiptFormatter(receipt);
                }

                // check if confirmation listener exists
                if (defer.eventEmitter.listeners('confirmation').length > 0) {

                    defer.eventEmitter.emit('confirmation', confirmationCount, receipt);

                    canUnsubscribe = false;
                    confirmationCount++;

                    if (confirmationCount === CONFIRMATIONBLOCKS + 1) { // add 1 so we account for conf 0
                        sub.unsubscribe();
                        defer.eventEmitter.removeAllListeners();
                    }
                }

                return receipt;
            })
            // CHECK for CONTRACT DEPLOYMENT
            .then(function(receipt) {

                if (isContractDeployment && !promiseResolved) {

                    if (!receipt.contractAddress) {

                        if (canUnsubscribe) {
                            sub.unsubscribe();
                            promiseResolved = true;
                        }

                        return utils._fireError(new Error('The transaction receipt didn\'t contain a contract address.'), defer.eventEmitter, defer.reject);
                    }

                    _ethereumCall.getCode(receipt.contractAddress, function (e, code) {

                        if (!code) {
                            return;
                        }

                        if (code.length > 2) {
                            defer.eventEmitter.emit('receipt', receipt);

                            // if contract, return instance instead of receipt
                            if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) {
                                defer.resolve(method.extraFormatters.contractDeployFormatter(receipt));
                            } else {
                                defer.resolve(receipt);
                            }

                            // need to remove listeners, as they aren't removed automatically when succesfull
                            if (canUnsubscribe) {
                                defer.eventEmitter.removeAllListeners();
                            }

                        } else {
                            utils._fireError(new Error('The contract code couldn\'t be stored, please check your gas limit.'), defer.eventEmitter, defer.reject);
                        }

                        if (canUnsubscribe) {
                            sub.unsubscribe();
                        }
                        promiseResolved = true;
                    });
                }

                return receipt;
            })
            // CHECK for normal tx check for receipt only
            .then(function(receipt) {

                if (!isContractDeployment && !promiseResolved) {

                    if(!receipt.outOfGas &&
                       (!gasProvided || gasProvided !== receipt.gasUsed)) {
                        defer.eventEmitter.emit('receipt', receipt);
                        defer.resolve(receipt);

                        // need to remove listeners, as they aren't removed automatically when succesfull
                        if (canUnsubscribe) {
                            defer.eventEmitter.removeAllListeners();
                        }

                    } else {
                        if(receipt) {
                            receipt = JSON.stringify(receipt, null, 2);
                        }
                        utils._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+ receipt), defer.eventEmitter, defer.reject);
                    }

                    if (canUnsubscribe) {
                        sub.unsubscribe();
                    }
                    promiseResolved = true;
                }

            })
            // time out the transaction if not mined after 50 blocks
            .catch(function () {
                timeoutCount++;

                if (timeoutCount - 1 >= TIMEOUTBLOCK) {
                    sub.unsubscribe();
                    promiseResolved = true;
                    return utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
                }
            });

        } else {
            sub.unsubscribe();
            promiseResolved = true;
            return utils._fireError({message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.', data: err}, defer.eventEmitter, defer.reject);
        }
    };

  // start watching for confirmation depending on the support features of the provider
  var startWatching = function() {
      // if provider allows PUB/SUB
      if (_.isFunction(this.requestManager.provider.on)) {
          _ethereumCall.subscribe('newBlockHeaders', checkConfirmation);
      } else {
          intervalId = setInterval(checkConfirmation, 1000);
      }
  }.bind(this);

  // first check if we already have a confirmed transaction
  _ethereumCall.getTransactionReceipt(result)
  .then(function(receipt) {
      if (receipt && receipt.blockHash) {
          if (defer.eventEmitter.listeners('confirmation').length > 0) {
              // if the promise has not been resolved we must keep on watching for new Blocks, if a confrimation listener is present
              setTimeout(function(){
                  if (!promiseResolved) startWatching();
              }, 1000);
          }

          return checkConfirmation(null, null, null, receipt);
      } else if (!promiseResolved) {
          startWatching();
      }
  })
  .catch(function(){
      if (!promiseResolved) startWatching();
  });

};

var getWallet = function(from, accounts) {
    var wallet = null;

    // is index given
    if (_.isNumber(from)) {
        wallet = accounts.wallet[from];

        // is account given
    } else if (_.isObject(from) && from.address && from.privateKey) {
        wallet = from;

        // search in wallet for address
    } else {
        wallet = accounts.wallet[from.toLowerCase()];
    }

    return wallet;
};

Method.prototype.buildCall = function() {
    var method = this,
        isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'); // || method.call === 'personal_sendTransaction'

    // actual send function
    var send = function () {
        var defer = promiEvent(!isSendTx),
            payload = method.toPayload(Array.prototype.slice.call(arguments));

        // CALLBACK function
        var sendTxCallback = function (err, result) {
            try {
                result = method.formatOutput(result);
            } catch(e) {
                err = e;
            }

            if (result instanceof Error) {
                err = result;
            }

            if (!err) {
                if (payload.callback) {
                    payload.callback(null, result);
                }
            } else {
                if(err.error) {
                    err = err.error;
                }

                return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback);
            }

            // return PROMISE
            if (!isSendTx) {

                if (!err) {
                    defer.resolve(result);

                }

            // return PROMIEVENT
            } else {
                defer.eventEmitter.emit('transactionHash', result);

                method._confirmTransaction(defer, result, payload);
            }

        };

        // SENDS the SIGNED SIGNATURE
        var sendSignedTx = function(sign){

            payload.method = 'eth_sendRawTransaction';
            payload.params = [sign.rawTransaction];

            method.requestManager.send(payload, sendTxCallback);
        };

        var sendRequest = function(payload, method) {

            if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) {
                var wallet;

                // ETH_SENDTRANSACTION
                if (payload.method === 'eth_sendTransaction') {
                    var tx = payload.params[0];
                    wallet = getWallet((_.isObject(tx)) ? tx.from : null, method.accounts);

                    // If wallet was found, sign tx, and send using sendRawTransaction
                    if (wallet && wallet.privateKey) {
                        delete tx.from;

                        var signature = method.accounts.signTransaction(tx, wallet.privateKey);

                        return (_.isFunction(signature.then)) ? signature.then(sendSignedTx) : sendSignedTx(signature);
                    }

                // ETH_SIGN
                } else if (payload.method === 'eth_sign') {
                    var data = payload.params[1];
                    wallet = getWallet(payload.params[0], method.accounts);

                    // If wallet was found, sign tx, and send using sendRawTransaction
                    if (wallet && wallet.privateKey) {
                        var sign = method.accounts.sign(data, wallet.privateKey);

                        if (payload.callback) {
                            payload.callback(null, sign.signature);
                        }

                        defer.resolve(sign.signature);
                        return;
                    }

                }
            }

            return method.requestManager.send(payload, sendTxCallback);
        };

        // Send the actual transaction
        if(isSendTx && _.isObject(payload.params[0]) && !payload.params[0].gasPrice) {

            var getGasPrice = (new Method({
                name: 'getGasPrice',
                call: 'eth_gasPrice',
                params: 0
            })).createFunction(method.requestManager);

            getGasPrice(function (err, gasPrice) {

                if (gasPrice) {
                    payload.params[0].gasPrice = gasPrice;
                }
                sendRequest(payload, method);
            });

        } else {
            sendRequest(payload, method);
        }

        return defer.eventEmitter;
    };

    // necessary to attach things to the method
    send.method = method;
    // necessary for batch requests
    send.request = this.request.bind(this);
    return send;
};

/**
 * Should be called to create the pure JSONRPC request which can be used in a batch request
 *
 * @method request
 * @return {Object} jsonrpc request
 */
Method.prototype.request = function () {
    var payload = this.toPayload(Array.prototype.slice.call(arguments));
    payload.format = this.formatOutput.bind(this);
    return payload;
};

module.exports = Method;


text:
require_relative './node'

class SinglyLinkedList
	attr_accessor :head, :tail

	def initialize(data)
		@head = Node.new(data)
		@head.next = nil
		@tail = @head
	end

	def add(data)
		@tail.next = Node.new(data)
		@tail = @tail.next
		@tail.next = nil
	end

	def delete_middle
		if @head.nil?
			puts 'This is an empty singly linked list'
		elsif @head.next.nil?
			puts 'Only one node in the list, removing now...'
			@head = @head.next
		else
			current = @head.next
			middle = @head
			previous = nil
			while !current.next.nil? && !current.next.next.nil?
				previous = middle
				middle = current
				current = current.next
			end
			previous.next = current
	 end
	end

	def find(data) #how should we find the node? by data it's holding? This requires each node to have unique data
		current_node = @head
		while current_node != nil
			if current_node.data == data
				return current_node
			else
				current_node = current_node.next
			end
		end
	end

end


text:
require 'aws-sdk'
require 'gemjars/deux/streams'

module Gemjars
  module Deux
    class AWSStore
      def self.from_file path
        config = YAML.load(File.read(File.expand_path(path)))
        bucket_name = config['bucket']
        s3 = AWS::S3.new(access_key_id: config['access_key_id'], secret_access_key: config['secret_access_key'])
        bucket = s3.buckets.create(bucket_name, :acl => :public_read)
        executor = Java::JavaUtilConcurrent::Executors.new_fixed_thread_pool(10)
        at_exit { executor.shutdown }
        new(bucket, executor)
      end

      def initialize bucket, executor
        @bucket = bucket
        @executor = executor
      end

      def put name, opts = {}
        r, w = Streams.pipe_channel
        @executor.submit proc {
          begin
            @bucket.objects.create name, Streams.to_input_stream(r).to_io, {:estimated_content_length => 2048 * 1024, :acl => :public_read}.merge(opts)
          rescue => e
            puts e
          end
        }.to_java(Java::JavaLang::Runnable)
        w
      end

      def get name
        return unless @bucket.objects[name].exists?

        r, w = Streams.pipe_channel
        @executor.submit proc {
          begin
            @bucket.objects[name].read do |chunk|
              w.write Streams.to_buffer(chunk)
            end
          rescue => e
            puts e
          ensure
            w.close
          end
        }.to_java(Java::JavaLang::Runnable)
        r
      end

      def delete_all *names
        @bucket.objects.delete *names
      end
    end
  end
end


text:
package hu.belicza.andras.sc2gearspluginapi;

import java.io.File;
import java.util.Date;

/**
 * Plugin descriptor: provides meta-data about a plugin.
 *
 * @version 1.0
 *
 * @author Andras Belicza
 */
public interface PluginDescriptor {

	/**
	 * Returns the plugin folder (where the plugin files are).
	 * @return the plugin folder (where the plugin files are)
	 */
	File getPluginFolder();

	/**
	 * Returns the libraries (*.jar files) that were found and loaded from the plugin folder.
	 * @return the libraries (*.jar files) that were found and loaded from the plugin folder
	 */
	File[] getPluginLibs();

	/**
	 * Returns the name of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "name").
	 * @return the name of the plugin
	 */
	String getName();

	/**
	 * Returns the first name of the author of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "authorFirstName").
	 * @return the first name of the author of the plugin
	 */
	String getAuthorFirstName();

	/**
	 * Returns the last name of the author of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "authorLastName").
	 * @return the last name of the author of the plugin
	 */
	String getAuthorLastName();

	/**
	 * Returns the email of the author of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "authorEmail").
	 * @return the email of the author of the plugin
	 */
	String getAuthorEmail();

	/**
	 * Returns the version of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "version").
	 * @return the version of the plugin
	 */
	String getVersion();

	/**
	 * Returns the release date of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "releaseDate").
	 * @return the date of the plugin
	 */
	Date getReleaseDate();

	/**
	 * Returns the API version implemented/used by the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "apiVersion").
	 * @return the API version implemented/used by the plugin
	 */
	String getApiVersion();

	/**
	 * Returns the home page of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "homePage").
	 * @return the home page of the plugin
	 */
	String getHomePage();

	/**
	 * Tells if the description is HTML.
	 * This property is taken from the plugin descriptor XML (tag name: "description", attribute: "isHtml").
	 * @return true if the description is HTML; false if it is plain text
	 */
	boolean isHtmlDescription();

	/**
	 * Returns the description of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "description").
	 * @return the description of the plugin
	 */
	String getDescription();

	/**
	 * Returns the main class of the plugin.

	 * This property is taken from the plugin descriptor XML (tag name: "mainClass").
	 * @return the main class of the plugin
	 */
	String getMainClass();

}


text:
package tools.descartes.dlim.httploadgenerator.http;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;

import tools.descartes.dlim.httploadgenerator.generator.ResultTracker;
import tools.descartes.dlim.httploadgenerator.transaction.Transaction;
import tools.descartes.dlim.httploadgenerator.transaction.TransactionDroppedException;
import tools.descartes.dlim.httploadgenerator.transaction.TransactionInvalidException;
import tools.descartes.dlim.httploadgenerator.transaction.TransactionQueueSingleton;

/**
 * HTTP transaction sends HTML requests to a HTTP web server based on a LUA script.
 *
 * @author Joakim von Kistowski, Maximilian Deffner
 *
 */
public class HTTPTransaction extends Transaction {

	private static final String POST_SIGNAL = "[POST]";

	/** The constant logging instance. */
	private static final Logger LOG = Logger.getLogger(HTTPTransaction.class.getName());

	/**
	 * Processes the transaction of sending a GET request to a web server.
	 * @param generator The input generator to use.
	 * @return Response time in milliseconds.
	 */
	public long process(HTTPInputGenerator generator) throws TransactionDroppedException, TransactionInvalidException {
		long processStartTime = System.currentTimeMillis();
		if (generator.getTimeout() > 0 && processStartTime - getStartTime() > generator.getTimeout()) {
			throw new TransactionDroppedException("Wait time in queue too long. "
					+ String.valueOf(processStartTime - getStartTime()) + " ms passed before transaction was even started.");
		}
		String url = generator.getNextInput().trim();
		String method = "GET";
		if (url.startsWith("[")) {
			if (url.startsWith(POST_SIGNAL)) {
				method = "POST";
			}
			url = url.replaceFirst("\\[.*\\]", "");
		}
		Request request = generator.initializeHTTPRequest(url, method);

		try {
			ContentResponse response = request.send();
			if (response.getStatus() >= 400) {
				generator.revertLastCall();
				LOG.log(Level.FINEST, "Received error response code: " + response.getStatus());
				throw new TransactionInvalidException("Error code: " + response.getStatus());
			} else {
				String responseBody = response.getContentAsString();
				long responseTime = System.currentTimeMillis() - processStartTime;

				//store result
				generator.resetHTMLFunctions(responseBody);
				return responseTime;
			}
		} catch (TimeoutException e) {
			generator.revertLastCall();
		} catch (ExecutionException e) {
			if (e.getCause() == null || !(e.getCause() instanceof TimeoutException)) {
				LOG.log(Level.SEVERE, "ExecutionException in call for URL: " + url + "; Cause: " + e.getCause().toString());
			}
			generator.revertLastCall();
			throw new TransactionInvalidException("ExecutionException: " + e.getMessage());
		} catch (CancellationException e) {
			LOG.log(Level.SEVERE, "CancellationException: " + url + "; " + e.getMessage());
			generator.revertLastCall();
			throw new TransactionInvalidException("CancellationException: " + e.getMessage());
		} catch (InterruptedException e) {
			LOG.log(Level.SEVERE, "InterruptedException: " + e.getMessage());
			generator.revertLastCall();
			throw new TransactionInvalidException("InterruptedException: " + e.getMessage());
		}
		return 0;
	}

	@Override
	public void run() {
		HTTPInputGenerator generator = HTTPInputGeneratorPool.getPool().takeFromPool();
		try {
			long responseTime = this.process(generator);
			ResultTracker.TRACKER.logTransaction(responseTime, ResultTracker.TransactionState.SUCCESS);
		} catch (TransactionDroppedException e) {
			ResultTracker.TRACKER.logTransaction(0, ResultTracker.TransactionState.DROPPED);
		} catch (TransactionInvalidException e) {
			ResultTracker.TRACKER.logTransaction(0, ResultTracker.TransactionState.FAILED);
		}
		HTTPInputGeneratorPool.getPool().releaseBackToPool(generator);
		TransactionQueueSingleton transactionQueue = TransactionQueueSingleton.getInstance();
		transactionQueue.addQueueElement(this);
	}
}


text:
var app = angular.module("app", [
    'oc.lazyLoad',
    'ui.router'
]);
app.config(["$provide", "$compileProvider", "$controllerProvider", "$filterProvider",
    function($provide, $compileProvider, $controllerProvider, $filterProvider) {
        app.controller = $controllerProvider.register;
        app.directive = $compileProvider.register;
        app.filter = $filterProvider.register;
        app.factory = $provide.factory;
        app.service = $provide.service;
        app.constant = $provide.constant;
    }
]);

app.run(["$rootScope", "$state", "$stateParams", function($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}]);

app.controller("MainCtrl", ["$scope", function($scope) {

}]);

app.directive("uiNav", ["$timeout", function() {
    return {
        restrict: "AC",
        link: function(a, b) {
            b.find("a").bind("click", function() {
                var b = angular.element(this).parent();
                b.parent().find("li").removeClass("active");
                b.toggleClass("active");
            })
        }
    }
}])

app.config([
    '$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider
            //.when('/c?id', '/contacts/:id')
            //.when('/user/:id', '/contacts/:id')
            .otherwise('/app/dashboard');

        $stateProvider
            .state("app", {
                "abstract": true, // abstract: true 表明此状态不能被显性激活,只能被子状态隐性激活
                url: "/app",
                views: {
                    "": {
                        templateUrl: "views/layout.html"
                    },
                    aside: {
                        templateUrl: "views/pages/dashboardasider.html"
                    }
                }
            })
            .state('app.dashboard', {
                url: "/dashboard",
                templateUrl: 'views/pages/dashboard.html',
            })
            .state('user', {
                url: "/user",
                views: {
                    "": {
                        templateUrl: "views/layout.html"
                    },
                    aside: {
                        templateUrl: 'views/pages/usersider.html'
                    }
                }
            })
            .state('user.main', {
                url: '/main',
                templateUrl: 'views/pages/user.html'
            })
            .state('user.list', {
                url: '/list',
                templateUrl: 'views/pages/userlist.html'
            })
            .state('user.log', {
                url: '/log',
                templateUrl: 'views/pages/log.html',
                controller: 'LogCtrl',
                resolve: {
                    deps: ["$ocLazyLoad", function(a) {
                        return a.load(["js/test.js"])
                    }]
                }
            });
    }
]);


text:
const _ = require('underscore-plus')
const {Disposable, CompositeDisposable} = require('event-kit')
let Tooltip = null

// Essential: Associates tooltips with HTML elements.
//
// You can get the `TooltipManager` via `atom.tooltips`.
//
// ## Examples
//
// The essence of displaying a tooltip
//
// ```javascript
// // display it
// const disposable = atom.tooltips.add(div, {title: 'This is a tooltip'})
//
// // remove it
// disposable.dispose()
// ```
//
// In practice there are usually multiple tooltips. So we add them to a
// CompositeDisposable
//
// ```javascript
// const {CompositeDisposable} = require('atom')
// const subscriptions = new CompositeDisposable()
//
// const div1 = document.createElement('div')
// const div2 = document.createElement('div')
// subscriptions.add(atom.tooltips.add(div1, {title: 'This is a tooltip'}))
// subscriptions.add(atom.tooltips.add(div2, {title: 'Another tooltip'}))
//
// // remove them all
// subscriptions.dispose()
// ```
//
// You can display a key binding in the tooltip as well with the
// `keyBindingCommand` option.
//
// ```javascript
// disposable = atom.tooltips.add(this.caseOptionButton, {
//   title: 'Match Case',
//   keyBindingCommand: 'find-and-replace:toggle-case-option',
//   keyBindingTarget: this.findEditor.element
// })
// ```
module.exports =
class TooltipManager {
  constructor ({keymapManager, viewRegistry}) {
    this.defaults = {
      trigger: 'hover',
      container: 'body',
      html: true,
      placement: 'auto top',
      viewportPadding: 2
    }

    this.hoverDefaults = {
      delay: {show: 1000, hide: 100}
    }

    this.keymapManager = keymapManager
    this.viewRegistry = viewRegistry
    this.tooltips = new Map()
  }

  // Essential: Add a tooltip to the given element.
  //
  // * `target` An `HTMLElement`
  // * `options` An object with one or more of the following options:
  //   * `title` A {String} or {Function} to use for the text in the tip. If
  //     a function is passed, `this` will be set to the `target` element. This
  //     option is mutually exclusive with the `item` option.
  //   * `html` A {Boolean} affecting the interpretation of the `title` option.
  //     If `true` (the default), the `title` string will be interpreted as HTML.
  //     Otherwise it will be interpreted as plain text.
  //   * `item` A view (object with an `.element` property) or a DOM element
  //     containing custom content for the tooltip. This option is mutually
  //     exclusive with the `title` option.
  //   * `class` A {String} with a class to apply to the tooltip element to
  //     enable custom styling.
  //   * `placement` A {String} or {Function} returning a string to indicate
  //     the position of the tooltip relative to `element`. Can be `'top'`,
  //     `'bottom'`, `'left'`, `'right'`, or `'auto'`. When `'auto'` is
  //     specified, it will dynamically reorient the tooltip. For example, if
  //     placement is `'auto left'`, the tooltip will display to the left when
  //     possible, otherwise it will display right.
  //     When a function is used to determine the placement, it is called with
  //     the tooltip DOM node as its first argument and the triggering element
  //     DOM node as its second. The `this` context is set to the tooltip
  //     instance.
  //   * `trigger` A {String} indicating how the tooltip should be displayed.
  //     Choose from one of the following options:
  //       * `'hover'` Show the tooltip when the mouse hovers over the element.
  //         This is the default.
  //       * `'click'` Show the tooltip when the element is clicked. The tooltip
  //         will be hidden after clicking the element again or anywhere else
  //         outside of the tooltip itself.
  //       * `'focus'` Show the tooltip when the element is focused.
  //       * `'manual'` Show the tooltip immediately and only hide it when the
  //         returned disposable is disposed.
  //   * `delay` An object specifying the show and hide delay in milliseconds.
  //     Defaults to `{show: 1000, hide: 100}` if the `trigger` is `hover` and
  //     otherwise defaults to `0` for both values.
  //   * `keyBindingCommand` A {String} containing a command name. If you specify
  //     this option and a key binding exists that matches the command, it will
  //     be appended to the title or rendered alone if no title is specified.
  //   * `keyBindingTarget` An `HTMLElement` on which to look up the key binding.
  //     If this option is not supplied, the first of all matching key bindings
  //     for the given command will be rendered.
  //
  // Returns a {Disposable} on which `.dispose()` can be called to remove the
  // tooltip.
  add (target, options) {
    if (target.jquery) {
      const disposable = new CompositeDisposable()
      for (let i = 0; i < target.length; i++) {
        disposable.add(this.add(target[i], options))
      }
      return disposable
    }

    if (Tooltip == null) { Tooltip = require('./tooltip') }

    const {keyBindingCommand, keyBindingTarget} = options

    if (keyBindingCommand != null) {
      const bindings = this.keymapManager.findKeyBindings({command: keyBindingCommand, target: keyBindingTarget})
      const keystroke = getKeystroke(bindings)
      if ((options.title != null) && (keystroke != null)) {
        options.title += ` ${getKeystroke(bindings)}`
      } else if (keystroke != null) {
        options.title = getKeystroke(bindings)
      }
    }

    delete options.selector
    options = _.defaults(options, this.defaults)
    if (options.trigger === 'hover') {
      options = _.defaults(options, this.hoverDefaults)
    }

    const tooltip = new Tooltip(target, options, this.viewRegistry)

    if (!this.tooltips.has(target)) {
      this.tooltips.set(target, [])
    }
    this.tooltips.get(target).push(tooltip)

    const hideTooltip = function () {
      tooltip.leave({currentTarget: target})
      tooltip.hide()
    }

    window.addEventListener('resize', hideTooltip)
    window.addEventListener('keydown', hideTooltip)

    const disposable = new Disposable(() => {
      window.removeEventListener('resize', hideTooltip)
      window.removeEventListener('keydown', hideTooltip)
      hideTooltip()
      tooltip.destroy()

      if (this.tooltips.has(target)) {
        const tooltipsForTarget = this.tooltips.get(target)
        const index = tooltipsForTarget.indexOf(tooltip)
        if (index !== -1) {
          tooltipsForTarget.splice(index, 1)
        }
        if (tooltipsForTarget.length === 0) {
          this.tooltips.delete(target)
        }
      }
    })

    return disposable
  }

  // Extended: Find the tooltips that have been applied to the given element.
  //
  // * `target` The `HTMLElement` to find tooltips on.
  //
  // Returns an {Array} of `Tooltip` objects that match the `target`.
  findTooltips (target) {
    if (this.tooltips.has(target)) {
      return this.tooltips.get(target).slice()
    } else {
      return []
    }
  }
}

function humanizeKeystrokes (keystroke) {
  let keystrokes = keystroke.split(' ')
  keystrokes = (keystrokes.map((stroke) => _.humanizeKeystroke(stroke)))
  return keystrokes.join(' ')
}

function getKeystroke (bindings) {
  if (bindings && bindings.length) {
    return `<span class="keystroke">${humanizeKeystrokes(bindings[0].keystrokes)}</span>`
  }
}


text:
package cluster_test

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/hashicorp/raft"
	"github.com/lxc/lxd/lxd/cluster"
	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/version"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/net/context"
)

// After a heartbeat request is completed, the leader updates the heartbeat
// timestamp column, and the serving node updates its cache of raft nodes.
func TestHeartbeat(t *testing.T) {
	f := heartbeatFixture{t: t}
	defer f.Cleanup()

	f.Bootstrap()
	f.Grow()
	f.Grow()

	leader := f.Leader()
	leaderState := f.State(leader)

	// Artificially mark all nodes as down
	err := leaderState.Cluster.Transaction(func(tx *db.ClusterTx) error {
		nodes, err := tx.Nodes()
		require.NoError(t, err)
		for _, node := range nodes {
			err := tx.NodeHeartbeat(node.Address, time.Now().Add(-time.Minute))
			require.NoError(t, err)
		}
		return nil
	})
	require.NoError(t, err)

	// Perform the heartbeat requests.
	heartbeat, _ := cluster.Heartbeat(leader, leaderState.Cluster)
	ctx := context.Background()
	heartbeat(ctx)

	// The heartbeat timestamps of all nodes got updated
	err = leaderState.Cluster.Transaction(func(tx *db.ClusterTx) error {
		nodes, err := tx.Nodes()
		require.NoError(t, err)

		offlineThreshold, err := tx.NodeOfflineThreshold()
		require.NoError(t, err)

		for _, node := range nodes {
			assert.False(t, node.IsOffline(offlineThreshold))
		}
		return nil
	})
	require.NoError(t, err)
}

// If a certain node does not successfully respond to the heartbeat, its
// timestamp does not get updated.
func DISABLE_TestHeartbeat_MarkAsDown(t *testing.T) {
	f := heartbeatFixture{t: t}
	defer f.Cleanup()

	f.Bootstrap()
	f.Grow()

	leader := f.Leader()
	leaderState := f.State(leader)

	// Artificially mark all nodes as down
	t.Logf("marking all nodes as down")
	err := leaderState.Cluster.Transaction(func(tx *db.ClusterTx) error {
		nodes, err := tx.Nodes()
		require.NoError(t, err)
		for _, node := range nodes {
			err := tx.NodeHeartbeat(node.Address, time.Now().Add(-time.Minute))
			require.NoError(t, err)
		}
		return nil
	})
	require.NoError(t, err)

	follower := f.Follower()

	// Shutdown the follower node and perform the heartbeat requests.
	f.Server(follower).Close()
	heartbeat, _ := cluster.Heartbeat(leader, leaderState.Cluster)
	ctx := context.Background()
	heartbeat(ctx)

	// The heartbeat timestamp of the second node did not get updated
	err = leaderState.Cluster.Transaction(func(tx *db.ClusterTx) error {
		nodes, err := tx.Nodes()
		require.NoError(t, err)

		offlineThreshold, err := tx.NodeOfflineThreshold()
		require.NoError(t, err)

		i := f.Index(follower)
		assert.True(t, nodes[i].IsOffline(offlineThreshold))
		return nil
	})
	require.NoError(t, err)
}

// Helper for testing heartbeat-related code.
type heartbeatFixture struct {
	t        *testing.T
	gateways map[int]*cluster.Gateway              // node index to gateway
	states   map[*cluster.Gateway]*state.State     // gateway to its state handle
	servers  map[*cluster.Gateway]*httptest.Server // gateway to its HTTP server
	cleanups []func()
}

// Bootstrap the first node of the cluster.
func (f *heartbeatFixture) Bootstrap() *cluster.Gateway {
	f.t.Logf("create bootstrap node for test cluster")
	state, gateway, _ := f.node()

	err := cluster.Bootstrap(state, gateway, "buzz")
	require.NoError(f.t, err)

	return gateway
}

// Grow adds a new node to the cluster.
func (f *heartbeatFixture) Grow() *cluster.Gateway {
	// Figure out the current leader
	f.t.Logf("adding another node to the test cluster")
	target := f.Leader()
	targetState := f.states[target]

	state, gateway, address := f.node()
	name := address

	nodes, err := cluster.Accept(
		targetState, target, name, address, cluster.SchemaVersion, len(version.APIExtensions))
	require.NoError(f.t, err)

	err = cluster.Join(state, gateway, target.Cert(), name, nodes)
	require.NoError(f.t, err)

	return gateway
}

// Return the leader gateway in the cluster.
func (f *heartbeatFixture) Leader() *cluster.Gateway {
	timeout := time.Second
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	for {
		for _, gateway := range f.gateways {
			if gateway.Raft().State() == raft.Leader {
				return gateway
			}
		}

		select {
		case <-ctx.Done():
			f.t.Fatalf("no leader was elected within %s", timeout)
		default:
		}

		// Wait a bit for election to take place
		time.Sleep(10 * time.Millisecond)
	}
}

// Return a follower gateway in the cluster.
func (f *heartbeatFixture) Follower() *cluster.Gateway {
	timeout := time.Second
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	for {
		for _, gateway := range f.gateways {
			if gateway.Raft().State() == raft.Follower {
				return gateway
			}
		}

		select {
		case <-ctx.Done():
			f.t.Fatalf("no node running as follower")
		default:
		}

		// Wait a bit for election to take place
		time.Sleep(10 * time.Millisecond)
	}
}

// Return the cluster index of the given gateway.
func (f *heartbeatFixture) Index(gateway *cluster.Gateway) int {
	for i := range f.gateways {
		if f.gateways[i] == gateway {
			return i
		}
	}
	return -1
}

// Return the state associated with the given gateway.
func (f *heartbeatFixture) State(gateway *cluster.Gateway) *state.State {
	return f.states[gateway]
}

// Return the HTTP server associated with the given gateway.
func (f *heartbeatFixture) Server(gateway *cluster.Gateway) *httptest.Server {
	return f.servers[gateway]
}

// Creates a new node, without either bootstrapping or joining it.
//
// Return the associated gateway and network address.
func (f *heartbeatFixture) node() (*state.State, *cluster.Gateway, string) {
	if f.gateways == nil {
		f.gateways = make(map[int]*cluster.Gateway)
		f.states = make(map[*cluster.Gateway]*state.State)
		f.servers = make(map[*cluster.Gateway]*httptest.Server)
	}

	state, cleanup := state.NewTestState(f.t)
	f.cleanups = append(f.cleanups, cleanup)

	cert := shared.TestingKeyPair()
	gateway := newGateway(f.t, state.Node, cert)
	f.cleanups = append(f.cleanups, func() { gateway.Shutdown() })

	mux := http.NewServeMux()
	server := newServer(cert, mux)

	for path, handler := range gateway.HandlerFuncs() {
		mux.HandleFunc(path, handler)
	}

	address := server.Listener.Addr().String()
	mf := &membershipFixtures{t: f.t, state: state}
	mf.NetworkAddress(address)

	var err error
	require.NoError(f.t, state.Cluster.Close())
	state.Cluster, err = db.OpenCluster("db.bin", gateway.Dialer(), address)
	require.NoError(f.t, err)

	f.gateways[len(f.gateways)] = gateway
	f.states[gateway] = state
	f.servers[gateway] = server

	return state, gateway, address
}

func (f *heartbeatFixture) Cleanup() {
	// Run the cleanups in reverse order
	for i := len(f.cleanups) - 1; i >= 0; i-- {
		f.cleanups[i]()
	}
	for _, server := range f.servers {
		server.Close()
	}
}


text:
'use strict';
// interceptor service which can be used to control the requests
angular.module('rppFrontEnd')
  .factory('PathService', ['ApiService', function(ApiService) {
	  var PathService = {};
	  PathService.path = {};

	  PathService.getAll = function() {
	    return ApiService.get('paths', {}).success(function(data){
	      PathService.path = data;
	    }).error(function(data){
	    	PathService.path = {};
	    });
	  };

	  PathService.getPathsByStudentID = function(studentID){
	  	return ApiService.post('paths/getPathsByStudentID', {
	  		studentID : studentID
	  	}).success(function(data){
	  	  PathService.path = data;
	  	}).error(function(data){
	  		PathService.path = {};
	  	});
	  };

	  PathService.addNew = function(pathName){
	  	return ApiService.post('paths/create',{
	  		name : pathName
	  	}).success(function(data){
	  		return data;
	  	}).error(function(data){
	  		return data;
	  	});
	  };

	  PathService.addStudentToPath = function(studentID, pathID){
	  	return ApiService.post('StudentPaths/create',{
	  		studentID : studentID,
	  		pathID : pathID
	  	}).success(function(data){
	  		return data;
	  	}).error(function(data){
	  		return data;
	  	});
	  };

	  return PathService;
	}]);


text:
from __future__ import division
import pcbnew

import HelpfulFootprintWizardPlugin as HFPW

class FPC_FootprintWizard(HFPW.HelpfulFootprintWizardPlugin):

    def GetName(self):
        return "FPC (SMT connector)"

    def GetDescription(self):
        return "FPC (SMT connector) Footprint Wizard"

    def GetValue(self):
        pins = self.parameters["Pads"]["*n"]
        return "FPC_%d" % pins

    def GenerateParameterList(self):
        self.AddParam( "Pads", "n", self.uNatural, 40 )
        self.AddParam( "Pads", "pitch", self.uMM, 0.5 )
        self.AddParam( "Pads", "width", self.uMM, 0.25 )
        self.AddParam( "Pads", "height", self.uMM, 1.6)
        self.AddParam( "Shield", "shield_to_pad", self.uMM, 1.6 )
        self.AddParam( "Shield", "from_top", self.uMM, 1.3 )
        self.AddParam( "Shield", "width", self.uMM, 1.5 )
        self.AddParam( "Shield", "height", self.uMM, 2 )

    # build a rectangular pad
    def smdRectPad(self,module,size,pos,name):
        pad = pcbnew.D_PAD(module)
        pad.SetSize(size)
        pad.SetShape(pcbnew.PAD_SHAPE_RECT)
        pad.SetAttribute(pcbnew.PAD_ATTRIB_SMD)
        pad.SetLayerSet( pad.SMDMask() )
        pad.SetPos0(pos)
        pad.SetPosition(pos)
        pad.SetPadName(name)
        return pad

    def CheckParameters(self):
        p = self.parameters
        self.CheckParamInt( "Pads", "*n" )  # not internal units preceded by "*"

    def BuildThisFootprint(self):
        p = self.parameters
        pad_count       = int(p["Pads"]["*n"])
        pad_width       = p["Pads"]["width"]
        pad_height      = p["Pads"]["height"]
        pad_pitch       = p["Pads"]["pitch"]
        shl_width       = p["Shield"]["width"]
        shl_height      = p["Shield"]["height"]
        shl_to_pad      = p["Shield"]["shield_to_pad"]
        shl_from_top    = p["Shield"]["from_top"]

        offsetX         = pad_pitch * ( pad_count-1 ) / 2
        size_pad = pcbnew.wxSize( pad_width, pad_height )
        size_shld = pcbnew.wxSize(shl_width, shl_height)
        size_text = self.GetTextSize()  # IPC nominal

        # Gives a position and size to ref and value texts:
        textposy = pad_height/2 + pcbnew.FromMM(1) + self.GetTextThickness()
        self.draw.Reference( 0, textposy, size_text )

        textposy = textposy + size_text + self.GetTextThickness()
        self.draw.Value( 0, textposy, size_text )

        # create a pad array and add it to the module
        for n in range ( 0, pad_count ):
            xpos = pad_pitch*n - offsetX
            pad = self.smdRectPad(self.module,size_pad, pcbnew.wxPoint(xpos,0),str(n+1))
            self.module.Add(pad)

        # Mechanical shield pads: left pad and right pad
        xpos = -shl_to_pad-offsetX
        pad_s0_pos = pcbnew.wxPoint(xpos,shl_from_top)
        pad_s0 = self.smdRectPad(self.module, size_shld, pad_s0_pos, "0")
        xpos = (pad_count-1) * pad_pitch+shl_to_pad - offsetX
        pad_s1_pos = pcbnew.wxPoint(xpos,shl_from_top)
        pad_s1 = self.smdRectPad(self.module, size_shld, pad_s1_pos, "0")

        self.module.Add(pad_s0)
        self.module.Add(pad_s1)

        # add footprint outline
        linewidth = self.draw.GetLineTickness()
        margin = linewidth

        # upper line
        posy = -pad_height/2 - linewidth/2 - margin
        xstart = - pad_pitch*0.5-offsetX
        xend = pad_pitch * pad_count + xstart;
        self.draw.Line( xstart, posy, xend, posy )

        # lower line
        posy = pad_height/2 + linewidth/2 + margin
        self.draw.Line(xstart, posy, xend, posy)

        # around left mechanical pad (the outline around right pad is mirrored/y axix)
        yend = pad_s0_pos.y + shl_height/2 + margin
        self.draw.Line(xstart, posy, xstart, yend)
        self.draw.Line(-xstart, posy, -xstart, yend)

        posy = yend
        xend = pad_s0_pos.x - (shl_width/2 + linewidth + margin*2)
        self.draw.Line(xstart, posy, xend, posy)

        # right pad side
        self.draw.Line(-xstart, posy, -xend, yend)

        # vertical segment at left of the pad
        xstart = xend
        yend = posy - (shl_height + linewidth + margin*2)
        self.draw.Line(xstart, posy, xend, yend)

        # right pad side
        self.draw.Line(-xstart, posy, -xend, yend)

        # horizontal segment above the pad
        xstart = xend
        xend = - pad_pitch*0.5-offsetX
        posy = yend
        self.draw.Line(xstart, posy, xend, yend)

        # right pad side
        self.draw.Line(-xstart, posy,-xend, yend)

        # vertical segment above the pad
        xstart = xend
        yend = -pad_height/2 - linewidth/2 - margin
        self.draw.Line(xstart, posy, xend, yend)

        # right pad side
        self.draw.Line(-xstart, posy, -xend, yend)

FPC_FootprintWizard().register()


text:
<?php
/**
 * Created by PhpStorm.
 * User: tmtbe
 * Date: 16-6-17
 * Time: 下午1:56
 */
require_once __DIR__ . '/vendor/autoload.php';

$ip = '127.0.0.1';
$port = 9093;

function encode($buffer)
{
    $total_length = 4 + strlen($buffer);
    return pack('N', $total_length) . $buffer;
}

$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞
$client->set(array(
    'open_length_check' => 1,
    'package_length_type' => 'N',
    'package_length_offset' => 0,       //第N个字节是包长度的值
    'package_body_offset' => 0,       //第几个字节开始计算长度
    'package_max_length' => 2000000,  //协议最大长度
));
$client->on("connect", 'connect');

$client->on("receive", 'receive');

$client->on("error", function ($cli) {
    exit("error\n");
});

$client->on("close", function ($cli) {

});

$client->connect($ip, $port, 0.5);

function connect($cli){
    print_r('send');
    $message = new \app\Protobuf\Message();
    $message->setRequest(new \app\Protobuf\Request());
    $message->setResponse(new \app\Protobuf\Response());
    $loginRequest = new \app\Protobuf\Login_Request();
    $loginRequest->setUsername('test');
    $loginRequest->setPassword('123');
    $message->getRequest()->setMLoginRequest($loginRequest);
    $message->setCmdMethod(\app\Protobuf\CMD_METHOD::Login());
    $message->setCmdService(\app\Protobuf\CMD_SERVICE::Account());
    $message->setToken(time());
    $length=$cli->send(encode($message->toStream()->getContents()));
    print_r($length);
}
function receive($cli, $data){
    print_r('get');
    $message = new \app\Protobuf\Message(substr($data, 4));
    print_r($message->getCmdMethod());
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.impl.core.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.engine.delegate.BaseDelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateListener;
import org.camunda.bpm.engine.delegate.DelegateVariableInstance;
import org.camunda.bpm.engine.delegate.VariableListener;

/**
 * @author Daniel Meyer
 * @author Roman Smirnov
 * @author Sebastian Menski
 *
 */
public abstract class CoreModelElement implements Serializable {

  private static final long serialVersionUID = 1L;

  protected String id;
  protected String name;
  protected Map<String, Object> properties;

  /** contains built-in listeners */
  protected Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> builtInListeners = new HashMap<String, List<DelegateListener<? extends BaseDelegateExecution>>>();

  /** contains all listeners (built-in + user-provided) */
  protected Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> listeners = new HashMap<String, List<DelegateListener<? extends BaseDelegateExecution>>>();

  protected Map<String, List<VariableListener<?>>> builtInVariableListeners =
      new HashMap<String, List<VariableListener<?>>>();

  protected Map<String, List<VariableListener<?>>> variableListeners =
      new HashMap<String, List<VariableListener<?>>>();

  public CoreModelElement(String id) {
    this.id = id;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setProperty(String name, Object value) {
    if (properties==null) {
      properties = new HashMap<String, Object>();
    }
    properties.put(name, value);
  }

  public Object getProperty(String name) {
    if (properties==null) {
      return null;
    }
    return properties.get(name);
  }

  public Map<String, Object> getProperties() {
    if (properties==null) {
      return Collections.emptyMap();
    }
    return properties;
  }

  public void setProperties(Map<String, Object> properties) {
    this.properties = properties;
  }

  public void setId(String id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = name;
  }

  //event listeners //////////////////////////////////////////////////////////

  public List<DelegateListener<? extends BaseDelegateExecution>> getListeners(String eventName) {
    List<DelegateListener<? extends BaseDelegateExecution>> listenerList = getListeners().get(eventName);
    if (listenerList != null) {
      return listenerList;
    }
    return Collections.emptyList();
  }

  public List<DelegateListener<? extends BaseDelegateExecution>> getBuiltInListeners(String eventName) {
    List<DelegateListener<? extends BaseDelegateExecution>> listenerList = getBuiltInListeners().get(eventName);
    if (listenerList != null) {
      return listenerList;
    }
    return Collections.emptyList();
  }

  public List<VariableListener<?>> getVariableListenersLocal(String eventName) {
    List<VariableListener<?>> listenerList = getVariableListeners().get(eventName);
    if (listenerList != null) {
      return listenerList;
    }
    return Collections.emptyList();
  }

  public List<VariableListener<?>> getBuiltInVariableListenersLocal(String eventName) {
    List<VariableListener<?>> listenerList = getBuiltInVariableListeners().get(eventName);
    if (listenerList != null) {
      return listenerList;
    }
    return Collections.emptyList();
  }

  public void addListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener) {
    addListener(eventName, listener, -1);
  }

  public void addBuiltInListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener) {
    addBuiltInListener(eventName, listener, -1);
  }

  public void addBuiltInListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) {
    addListenerToMap(listeners, eventName, listener, index);
    addListenerToMap(builtInListeners, eventName, listener, index);
  }

  public void addListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) {
    addListenerToMap(listeners, eventName, listener, index);
  }

  protected <T> void addListenerToMap(Map<String, List<T>> listenerMap, String eventName, T listener, int index) {
    List<T> listeners = listenerMap.get(eventName);
    if (listeners == null) {
      listeners = new ArrayList<T>();
      listenerMap.put(eventName, listeners);
    }
    if (index < 0) {
      listeners.add(listener);
    } else {
      listeners.add(index, listener);
    }
  }

  public void addVariableListener(String eventName, VariableListener<?> listener) {
    addVariableListener(eventName, listener, -1);
  }

  public void addVariableListener(String eventName, VariableListener<?> listener, int index) {
    addListenerToMap(variableListeners, eventName, listener, index);
  }

  public void addBuiltInVariableListener(String eventName, VariableListener<?> listener) {
    addBuiltInVariableListener(eventName, listener, -1);
  }

  public void addBuiltInVariableListener(String eventName, VariableListener<?> listener, int index) {
    addListenerToMap(variableListeners, eventName, listener, index);
    addListenerToMap(builtInVariableListeners, eventName, listener, index);
  }

  public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getListeners() {
    return listeners;
  }

  public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getBuiltInListeners() {
    return builtInListeners;
  }

  public Map<String, List<VariableListener<?>>> getBuiltInVariableListeners() {
    return builtInVariableListeners;
  }

  public Map<String, List<VariableListener<?>>> getVariableListeners() {
    return variableListeners;
  }

}


text:
<?php

namespace app\modules\post\models\backend\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\post\models\backend\Post;

/**
 * PostSearch represents the model behind the search form about `app\modules\admin\models\Post`.
 */
class PostSearch extends Post
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'created_at', 'updated_at', 'status'], 'integer'],
            [['title', 'body', 'slug', 'keywords', 'description'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Post::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort'=> ['defaultOrder' => ['updated_at'=>3]]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'body', $this->body])
          //  ->andFilterWhere(['like', 'slug', $this->slug])
            ->andFilterWhere(['like', 'keywords', $this->keywords])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}