text:
/**************************************************************************
 *                                                                        *
 *               1+-------------------+1                                  *
 *       +--------+     Company       +--------+                          *
 *      *|        +-------------------+        |*                         *
 *  +----------+      +----------+       +---------+ +     +-----------+  *
 *  |  Driver  +------+   Ride   +-------+   Taxi    +-----+ BreakDown |  *
 *  +----------+1    *+----------+*     1+---------+ +1   *+-----------+  *
 *      1|                                    *|                          *
 *      1|                                    1|                          *
 *  +----------+      +----------+       +-----------+     +-----------+  *
 *  | Address  |      |Department+-------+Constructor+-----+  country  |  *
 *  +----------+      +----------+*     1+-----------+*   *+-----------+  *
 *                                                                        *
 *  1. A company may have many taxis and many drivers (OneToMany).        *
 *  2. A driver may have only one address (OneToOne).                     *
 *  3. A driver may drive many taxis and                                  *
 *     a taxi may be driven by many drivers (ManyToMany through Ride).    *
 *  4. A taxi may pass through many breakdowns (OneToMany).               *
 *     and may have only one constructor (ManyToOne).                     *
 *  5. A constructor may have many departments (OneToMany).               *
 *  6. Many contructor may have many country (ManyToMany).                *
 *                                                                        *
 **************************************************************************/

var Offshore = require('../../../../lib/offshore');
var assert = require('assert');
var async = require('async');
var offshore = new Offshore();
var migrate = 'drop';

describe('Deep', function() {
  var companyModel, taxiModel, driverModel, rideModel, constructorModel, addressModel, breakDownModel, departmentModel, countryModel;
  before(function(done) {
    var Company = Offshore.Collection.extend({
      identity: 'Company',
      connection: 'pop_deep',
      tableName: 'company_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'companyId',
          type: 'integer',
          primaryKey: true
        },
        name: {
          columnName: 'companyName',
          type: 'string'
        },
        taxis: {
          collection: 'Taxi',
          via: 'company'
        },
        drivers: {
          collection: 'Driver',
          via: 'company'
        }
      }
    });

    var Driver = Offshore.Collection.extend({
      identity: 'Driver',
      connection: 'pop_deep',
      tableName: 'driver_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'driverId',
          type: 'integer',
          primaryKey: true
        },
        name: {
          columnName: 'driverName',
          type: 'string'
        },
        taxis: {
          collection: 'Taxi',
          via: 'driver',
          through: 'ride'
        },
        address: {
          model: 'Address'
        },
        company: {
          model: 'Company'
        }
      }
    });

    var Taxi = Offshore.Collection.extend({
      identity: 'Taxi',
      connection: 'pop_deep',
      tableName: 'taxi_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'taxiId',
          type: 'integer',
          primaryKey: true
        },
        matricule: {
          columnName: 'taxiMatricule',
          type: 'string'
        },
        drivers: {
          collection: 'Driver',
          via: 'taxi',
          through: 'ride'
        },
        company: {
          model: 'Company'
        },
        constructor: {
          model: 'Constructor'
        },
        breakdowns: {
          collection: 'BreakDown',
          via: 'taxi'
        }
      }
    });

    var Ride = Offshore.Collection.extend({
      identity: 'Ride',
      connection: 'pop_deep',
      tableName: 'ride_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'rideId',
          type: 'integer',
          primaryKey: true
        },
        taxi: {
          model: 'Taxi'
        },
        driver: {
          model: 'Driver'
        }
      }
    });

    var Address = Offshore.Collection.extend({
      identity: 'Address',
      connection: 'pop_deep',
      tableName: 'address_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'addressId',
          type: 'integer',
          primaryKey: true
        },
        city: {
          columnName: 'addressCity',
          type: 'string'
        }
      }
    });

    var Constructor = Offshore.Collection.extend({
      identity: 'Constructor',
      connection: 'pop_deep',
      tableName: 'constructor_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'constructorId',
          type: 'integer',
          primaryKey: true
        },
        name: {
          columnName: 'constructorName',
          type: 'string'
        },
        taxis: {
          collection: 'Taxi',
          via: 'constructor'
        },
        departments: {
          collection: 'Department',
          via: 'constructor'
        },
        countries: {
          collection: 'Country',
          via: 'constructors'
        }
      }
    });
    var Country = Offshore.Collection.extend({
      identity: 'Country',
      connection: 'pop_deep',
      tableName: 'country_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'countryId',
          type: 'integer',
          primaryKey: true
        },
        name: 'string',
        constructors: {
          collection: 'Constructor',
          via: 'countries'
        }
      }
    });

    var BreakDown = Offshore.Collection.extend({
      identity: 'breakdown',
      connection: 'pop_deep',
      tableName: 'breakdown_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'breakDownId',
          type: 'integer',
          primaryKey: true
        },
        level: {
          columnName: 'breakDownLevel',
          type: 'integer'
        },
        taxi: {
          model: 'Taxi'
        }
      }
    });

    var Department = Offshore.Collection.extend({
      identity: 'Department',
      connection: 'pop_deep',
      tableName: 'department_table',
      migrate: migrate,
      attributes: {
        id: {
          columnName: 'departmentId',
          type: 'integer',
          primaryKey: true
        },
        name: {
          columnName: 'departmentName',
          type: 'string'
        },
        constructor: {
          model: 'Constructor'
        }
      }
    });

    var companies = [
      {id: 1, name: 'company 1'},
      {id: 2, name: 'company 2'}
    ];
    var drivers = [
      {id: 1, name: 'driver 1', company: 1, address: 1},
      {id: 2, name: 'driver 2', company: 2, address: 2},
      {id: 3, name: 'driver 3', company: 1, address: 3},
      {id: 4, name: 'driver 4', company: 2, address: 4}
    ];
    var taxis = [
      {id: 1, matricule: 'taxi_1', company: 1, constructor: 1},
      {id: 2, matricule: 'taxi_2', company: 2, constructor: 2},
      {id: 3, matricule: 'taxi_3', company: 2, constructor: 2},
      {id: 4, matricule: 'taxi_4', company: 1, constructor: 1},
      {id: 5, matricule: 'taxi_5', company: 1, constructor: 1}
    ];
    var rides = [
      {id: 1, taxi: 1, driver: 1},
      {id: 2, taxi: 4, driver: 1},
      {id: 3, taxi: 5, driver: 1},
      {id: 4, taxi: 2, driver: 2},
      {id: 5, taxi: 1, driver: 2},
      {id: 6, taxi: 3, driver: 3},
      {id: 7, taxi: 2, driver: 3}
    ];

    var addresses = [
      {id: 1, city: 'city 1'},
      {id: 2, city: 'city 2'},
      {id: 3, city: 'city 3'},
      {id: 4, city: 'city 4'}
    ];
    var constructors = [
      {id: 1, name: 'constructor 1'},
      {id: 2, name: 'constructor 2'}
    ];

    var breakDowns = [
      {id: 1, level: 5, taxi: 3},
      {id: 2, level: 7, taxi: 2},
      {id: 3, level: 1, taxi: 3},
      {id: 4, level: 8, taxi: 3},
      {id: 5, level: 9, taxi: 1},
      {id: 8, level: 9, taxi: 1},
      {id: 6, level: 10, taxi: 4},
      {id: 7, level: 11, taxi: 5}
    ];

    var departments = [
      {id: 1, name: 'dep 1', constructor: 1},
      {id: 2, name: 'dep 2', constructor: 1},
      {id: 3, name: 'dep 3', constructor: 2},
      {id: 4, name: 'dep 4', constructor: 1},
      {id: 5, name: 'dep 5', constructor: 2}
    ];

    var countries = [
      {id: 1, name: 'france'},
      {id: 2, name: 'germany'}
    ];

    offshore.loadCollection(Company);
    offshore.loadCollection(Driver);
    offshore.loadCollection(Taxi);
    offshore.loadCollection(Address);
    offshore.loadCollection(Ride);
    offshore.loadCollection(Constructor);
    offshore.loadCollection(BreakDown);
    offshore.loadCollection(Department);
    offshore.loadCollection(Country);

    var connections = {
      pop_deep: {
        adapter: 'adapter'
      }
    };

    offshore.initialize({adapters: {adapter: require('offshore-memory')}, connections: connections}, function(err, colls) {
      if (err) {
        return done(err);
      }

      companyModel = colls.collections.company;
      taxiModel = colls.collections.taxi;
      driverModel = colls.collections.driver;
      addressModel = colls.collections.address;
      rideModel = colls.collections.ride;
      constructorModel = colls.collections.constructor;
      breakDownModel = colls.collections.breakdown;
      departmentModel = colls.collections.department;
      countryModel = colls.collections.country;

      async.series([
        function(callback) {
          companyModel.createEach(companies, callback);
        },
        function(callback) {
          taxiModel.createEach(taxis, callback);
        },
        function(callback) {
          driverModel.createEach(drivers, callback);
        },
        function(callback) {
          rideModel.createEach(rides, callback);
        }, function(callback) {
          addressModel.createEach(addresses, callback);
        },
        function(callback) {
          constructorModel.createEach(constructors, callback);
        },
        function(callback) {
          breakDownModel.createEach(breakDowns, callback);
        },
        function(callback) {
          departmentModel.createEach(departments, callback);
        },
        function(callback) {
          countryModel.createEach(countries, function(err, countries) {
            if (err) {
              return callback(err);
            }
            countryModel.findOne(1, function(err, country) {
              country.constructors.add(1);
              country.constructors.add(2);
              country.save(callback);
            });
          });
        }
      ], function(err) {
        if (err) {
          return done(err);
        }
        done();
      });
    });

  });

  describe('Populate', function() {
    it('should deeply populate a branch', function(done) {
      companyModel.find().sort('id asc')
        .populate('drivers.taxis', {sort: {id: 1}})
        .populate('drivers.taxis.constructor.departments', {sort: {id: 1}})
        .exec(function(err, companies) {
          if (err) {
            return done(err);
          }
          // Root Level
          assert(companies.length === 2 && companies[1].name === 'company 2', 'Root criteria not applied.');
          //Level 1
          assert(companies[1].drivers.length === 2, 'Could not populate first level oneToMany collection.');
          assert(companies[1].drivers[0].name === 'driver 2', 'First level not correctly populated.');

          //Level 2
          assert(companies[1].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
          var taxi1 = companies[1].drivers[0].taxis[0];
          var taxi2 = companies[1].drivers[0].taxis[1];
          assert(taxi1.matricule === 'taxi_1' && taxi2.matricule === 'taxi_2', 'Second level not correctly populated.');
          //Level 3
          assert(taxi1.constructor, 'Could not populate third level manyToOne model.');
          var constructor1 = taxi1.constructor;
          var constructor2 = taxi2.constructor;
          assert(constructor1.name === 'constructor 1' && constructor2.name === 'constructor 2',
            'Third level not correctly populated.');
          //Level 4
          assert(constructor1.departments.length === 3, 'Could not populate fourth level oneToMany collection.');
          assert(constructor1.departments[0].name === 'dep 1' && constructor1.departments[1].name === 'dep 2'
            && constructor1.departments[2].name === 'dep 4', 'Fourth level not correctly populated.');
          assert(constructor2.departments.length === 2, 'Could not populate fourth level oneToMany collection.');
          assert(constructor2.departments[0].name === 'dep 3',
            'Fourth level not correctly populated.');
          done();
        });
    });

    it('should deeply populate multiple branchs', function(done) {
      companyModel.find().where({name: 'company 2'})
        .populate('drivers.taxis', {sort: {id: 1}})
        .populate('drivers.address')
        .populate('taxis')
        .exec(function(err, companies) {
          if (err)
            return done(err);
          // Root Level
          assert(companies.length === 1 && companies[0].name === 'company 2', 'Root criteria not applied.');
          //Level 1
          assert(companies[0].drivers.length === 2, 'Could not populate first level oneToMany collection.');
          assert(companies[0].drivers[0].name === 'driver 2', 'First level not correctly populated.');
          assert(companies[0].taxis.length === 2, 'First level not correctly populated.');
          //Level 2 A
          assert(companies[0].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
          var taxi1 = companies[0].drivers[0].taxis[0];
          assert(taxi1.matricule === 'taxi_1', 'Second level (A) not correctly populated.');
          //Level 2 B
          assert(companies[0].drivers[0].address.city === 'city 2', 'Second level (B) criteria not populated.');
          done();
        });
    });

    it('should apply criteria to current populate path last alias', function(done) {
      companyModel.find().where({name: 'company 1'})
        .populate('drivers', {name: 'driver 3'})
        .populate('drivers.taxis', {matricule: 'taxi_3'})
        .populate('drivers.taxis.breakdowns', {where: {level: {'>': 2}}, sort: {level: 1}})
        .exec(function(err, companies) {
          if (err)
            return done(err);
          // Root Level
          assert(companies.length === 1 && companies[0].name === 'company 1', 'Root criteria not applied.');
          //Level 1
          assert(companies[0].drivers.length === 1, 'Could not populate first level oneToMany collection.');
          assert(companies[0].drivers[0].name === 'driver 3', 'First level criteria not applied.');
          //Level 2
          assert(companies[0].drivers[0].taxis.length === 1, 'Could not populate second level manyToMany collection.');
          var taxi = companies[0].drivers[0].taxis[0];
          assert(taxi.matricule === 'taxi_3', 'Second level criteria not applied.');
          //Level 3
          assert(taxi.breakdowns.length === 2, 'Could not populate third level oneToMany collection.');
          assert(taxi.breakdowns[0].level === 5 && taxi.breakdowns[1].level === 8, 'Third level criteria not applied.');

          done();
        });
    });

    it('should deeply populate nested collections', function(done) {
      companyModel.find().where({id: 2})
        .populate('taxis')
        .populate('taxis.breakdowns')
        .exec(function(err, company) {
          if (err)
            return done(err);
          assert(company[0].taxis[0].breakdowns.length === 1);
          assert(company[0].taxis[1].breakdowns.length === 3);
          done();
        });
    });

    it('findOne with populate deep should return undefined if there is no results', function(done) {
      companyModel.findOne().where({id: 999})
        .populate('taxis')
        .populate('taxis.breakdowns')
        .exec(function(err, company) {
          if (err) {
            return done(err);
          }
          assert(company === void(0));
          done();
        });
    });
  });
  describe('Criteria', function() {
    it('should find model using deep criteria on belongsTo', function(done) {
      taxiModel.find({where: {constructor: {name: 'constructor 1'}}}).populate('constructor').exec(function(err, taxis) {
        if (err) {
          return done(err);
        }
        assert(taxis.length === 3);
        assert(taxis[0].constructor.name === 'constructor 1');
        assert(taxis[1].constructor.name === 'constructor 1');
        assert(taxis[2].constructor.name === 'constructor 1');
        done();
      });
    });

    it('should find model using deep criteria on hasManyToOne', function(done) {
      taxiModel.find({where: {breakdowns: {level: 11}}}).populate('breakdowns').exec(function(err, taxis) {
        if (err) {
          return done(err);
        }
        assert(taxis[0].id === 5);
        assert(taxis[0].breakdowns[0].id === 7);
        assert(taxis[0].breakdowns[0].level === 11);
        done();
      });
    });

    it('should find model using deep criteria on hasManyToMany', function(done) {
      constructorModel.find({where: {countries: {name: 'france'}}}).populate('countries').exec(function(err, constructors) {
        if (err) {
          return done(err);
        }
        assert(constructors.length === 2);
        assert(constructors[0].countries[0].name === 'france');
        assert(constructors[1].countries[0].name === 'france');
        done();
      });
    });

    it('should find model using deep criteria on hasManyToMany through', function(done) {
      driverModel.find({where: {taxis: {matricule: 'taxi_4'}}}).populate('taxis', {sort: 'matricule'}).exec(function(err, drivers) {
        if (err) {
          return done(err);
        }
        assert(drivers.length === 1);
        assert(drivers[0].id === 1);
        assert(drivers[0].taxis.length === 3);
        assert(drivers[0].taxis[0].matricule === 'taxi_1');
        assert(drivers[0].taxis[1].matricule === 'taxi_4');
        assert(drivers[0].taxis[2].matricule === 'taxi_5');
        done();
      });
    });

    it('should find model using deep criteria with operator', function(done) {
      driverModel.find({sort: 'id', where: {taxis: {or: [{matricule: 'taxi_1'}, {matricule: 'taxi_2'}]}}}).populate('taxis', {sort: 'matricule'}).exec(function(err, drivers) {
        if (err) {
          return done(err);
        }
        assert(drivers.length === 3);
        assert(drivers[0].id === 1);
        assert(drivers[0].taxis.length === 3);
        assert(drivers[0].taxis[0].matricule === 'taxi_1');
        assert(drivers[0].taxis[1].matricule === 'taxi_4');
        assert(drivers[0].taxis[2].matricule === 'taxi_5');
        assert(drivers[1].id === 2);
        assert(drivers[1].taxis.length === 2);
        assert(drivers[1].taxis[0].matricule === 'taxi_1');
        assert(drivers[1].taxis[1].matricule === 'taxi_2');
        assert(drivers[2].id === 3);
        assert(drivers[2].taxis.length === 2);
        assert(drivers[2].taxis[0].matricule === 'taxi_2');
        assert(drivers[2].taxis[1].matricule === 'taxi_3');
        done();
      });
    });

    it('should find model using deep criteria in operator', function(done) {
      driverModel.find({sort: 'id', where: {or: [{taxis: {matricule: 'taxi_3'}}, {address: {city: 'city 4'}}]}}).populate('taxis', {sort: 'matricule'}).exec(function(err, drivers) {
        if (err) {
          return done(err);
        }
        assert(drivers.length === 2);
        assert(drivers[0].id === 3);
        assert(drivers[0].taxis.length === 2);
        assert(drivers[0].taxis[0].matricule === 'taxi_2');
        assert(drivers[0].taxis[1].matricule === 'taxi_3');
        assert(drivers[1].id === 4);
        assert(drivers[1].taxis.length === 0);
        assert(drivers[1].address === 4);
        done();
      });
    });

    it('should populate using deep criteria', function(done) {
      driverModel.findOne(3).populate('taxis', {sort: 'matricule', where: {breakdowns: {level: 5}}}).exec(function(err, driver) {
        if (err) {
          return done(err);
        }
        assert(driver.taxis.length === 1);
        assert(driver.taxis[0].id === 3);
        done();
      });
    });
  });

  describe('Associations', function() {

    it('should deeply populate and apply criteria on associations (One-to-One)', function(done) {
      taxiModel.findOne({where: {matricule: 'taxi_1'}})
        .populate('constructor', {where: {name: 'constructor 1'}})
        .populate('constructor.departments', {name: {contains: '4'}})
        .exec(function(err, taxi) {
          if (err)
            return done(err);
          // Root Level
          assert(taxi.matricule === 'taxi_1', 'Root criteria not applied.');
          //Level 1
          assert(taxi.constructor, 'Could not populate first level with criteria.');
          assert(taxi.constructor.name === 'constructor 1', 'First level criteria not applied.');
          //Level 2
          assert(taxi.constructor.departments, 'Second level not populated.');
          assert(taxi.constructor.departments[0].name === 'dep 4', 'Second level criteria not applied.');
          done();
        });
    });

    it('should deeply populate and apply criteria on associations (One-to-Many)', function(done) {
      companyModel.findOne({where: {name: 'company 1'}})
        .populate('taxis', {matricule: 'taxi_4'})
        .populate('taxis.breakdowns', {level: 10})
        .exec(function(err, company) {
          if (err)
            return done(err);
          // Root Level
          assert(company.name === 'company 1', 'Root criteria not applied.');
          //Level 1
          assert(company.taxis, 'Could not populate first level');
          assert(company.taxis[0].matricule === 'taxi_4', 'First level criteria not applied.');
          //Level 2
          assert(company.taxis[0].breakdowns, 'Second level not populated.');
          assert(company.taxis[0].breakdowns[0].level === 10, 'Second level criteria not applied.');
          done();
        });
    });

    it('should deeply populate and apply criteria on associations (Many-to-Many Through)', function(done) {
      driverModel.findOne({where: {name: 'driver 1'}})
        .populate('taxis', {matricule: 'taxi_4'})
        .populate('taxis.breakdowns', {level: 10})
        .exec(function(err, driver) {
          if (err)
            return done(err);
          // Root Level
          assert(driver.name === 'driver 1', 'Root criteria not applied.');
          //Level 1
          assert(driver.taxis, 'Could not populate first level with criteria.');
          assert(driver.taxis[0].matricule === 'taxi_4', 'first level criteria not applied.');
          //Level 2
          assert(driver.taxis[0].breakdowns, 'Second level not populated.');
          assert(driver.taxis[0].breakdowns[0].level === 10, 'Second level criteria not applied.');
          done();
        });
    });

    it('should deeply populate and apply criteria on associations (Many-to-Many)', function(done) {
      countryModel.findOne({name: 'france'})
        .populate('constructors', {name: 'constructor 1'})
        .populate('constructors.departments', {name: 'dep 4'})
        .exec(function(err, country) {
          if (err) {
            done(err);
          }
          assert(country.name === 'france', 'Root criteria not applied.');
          assert(country.constructors, 'Could not populate first level with criteria.');
          assert(country.constructors[0].name === 'constructor 1', 'first level criteria not applied.');
          assert(country.constructors[0].departments, 'Second level not populated.');
          assert(country.constructors[0].departments[0].name === 'dep 4', 'Second level criteria not applied.');
          done();
        });
    });

    it('should deeply populate and apply criteria on associations (Many-to-One)', function(done) {
      taxiModel.findOne({where: {matricule: 'taxi_1'}})
        .populate('constructor', {where: {name: 'constructor 1'}})
        .populate('constructor.departments', {name: {contains: '4'}})
        .exec(function(err, taxi) {
          if (err) {
            return done(err);
          }
          // Root Level
          assert(taxi.matricule === 'taxi_1', 'Root criteria not applied.');
          //Level 1
          assert(taxi.constructor, 'Could not populate first level with criteria.');
          assert(taxi.constructor.name === 'constructor 1', 'First level criteria not applied.');
          //Level 2
          assert(taxi.constructor.departments, 'Second level not populated.');
          assert(taxi.constructor.departments[0].name === 'dep 4', 'Second level criteria not applied.');
          done();
        });
    });
  });
});


text:
from .stochastic_gradient import BaseSGDClassifier

class Perceptron(BaseSGDClassifier):
    """Perceptron

    Read more in the :ref:`User Guide <perceptron>`.

    Parameters
    ----------

    penalty : None, 'l2' or 'l1' or 'elasticnet'
        The penalty (aka regularization term) to be used. Defaults to None.

    alpha : float
        Constant that multiplies the regularization term if regularization is
        used. Defaults to 0.0001

    fit_intercept : bool
        Whether the intercept should be estimated or not. If False, the
        data is assumed to be already centered. Defaults to True.

    max_iter : int, optional
        The maximum number of passes over the training data (aka epochs).
        It only impacts the behavior in the ``fit`` method, and not the
        `partial_fit`.
        Defaults to 5. Defaults to 1000 from 0.21, or if tol is not None.

        .. versionadded:: 0.19

    tol : float or None, optional
        The stopping criterion. If it is not None, the iterations will stop
        when (loss > previous_loss - tol). Defaults to None.
        Defaults to 1e-3 from 0.21.

        .. versionadded:: 0.19

    shuffle : bool, optional, default True
        Whether or not the training data should be shuffled after each epoch.

    verbose : integer, optional
        The verbosity level

    eta0 : double
        Constant by which the updates are multiplied. Defaults to 1.

    n_jobs : integer, optional
        The number of CPUs to use to do the OVA (One Versus All, for
        multi-class problems) computation. -1 means 'all CPUs'. Defaults
        to 1.

    random_state : int, RandomState instance or None, optional, default None
        The seed of the pseudo random number generator to use when shuffling
        the data.  If int, random_state is the seed used by the random number
        generator; If RandomState instance, random_state is the random number
        generator; If None, the random number generator is the RandomState
        instance used by `np.random`.

    class_weight : dict, {class_label: weight} or "balanced" or None, optional
        Preset for the class_weight fit parameter.

        Weights associated with classes. If not given, all classes
        are supposed to have weight one.

        The "balanced" mode uses the values of y to automatically adjust
        weights inversely proportional to class frequencies in the input data
        as ``n_samples / (n_classes * np.bincount(y))``

    warm_start : bool, optional
        When set to True, reuse the solution of the previous call to fit as
        initialization, otherwise, just erase the previous solution.

    n_iter : int, optional
        The number of passes over the training data (aka epochs).
        Defaults to None. Deprecated, will be removed in 0.21.

        .. versionchanged:: 0.19
            Deprecated

    Attributes
    ----------
    coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\
            n_features]
        Weights assigned to the features.

    intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
        Constants in decision function.

    n_iter_ : int
        The actual number of iterations to reach the stopping criterion.
        For multiclass fits, it is the maximum over every binary fit.

    Notes
    -----

    `Perceptron` and `SGDClassifier` share the same underlying implementation.
    In fact, `Perceptron()` is equivalent to `SGDClassifier(loss="perceptron",
    eta0=1, learning_rate="constant", penalty=None)`.

    See also
    --------

    SGDClassifier

    References
    ----------

    https://en.wikipedia.org/wiki/Perceptron and references therein.
    """
    def __init__(self, penalty=None, alpha=0.0001, fit_intercept=True,
                 max_iter=None, tol=None, shuffle=True, verbose=0, eta0=1.0,
                 n_jobs=1, random_state=0, class_weight=None,
                 warm_start=False, n_iter=None):
        super(Perceptron, self).__init__(loss="perceptron",
                                         penalty=penalty,
                                         alpha=alpha, l1_ratio=0,
                                         fit_intercept=fit_intercept,
                                         max_iter=max_iter,
                                         tol=tol,
                                         shuffle=shuffle,
                                         verbose=verbose,
                                         random_state=random_state,
                                         learning_rate="constant",
                                         eta0=eta0,
                                         power_t=0.5,
                                         warm_start=warm_start,
                                         class_weight=class_weight,
                                         n_jobs=n_jobs,
                                         n_iter=n_iter)

redpajama_set_name: RedPajamaGithub


text:
// TypeScript Version: 2.0

/**
* Computes the complete elliptic integral of the first kind.
*
* @param m - input value
* @returns evaluated elliptic integral
*
* @example
* var v = ellipk( 0.5 );
* // returns ~1.854
*
* v = ellipk( 2.0 );
* // returns NaN
*
* v = ellipk( -1.0 );
* // returns ~1.311
*
* v = ellipk( Infinity );
* // returns NaN
*
* v = ellipk( -Infinity );
* // returns NaN
*
* v = ellipk( NaN );
* // returns NaN
*/
declare function ellipk( x: number ): number;

// EXPORTS //

export = ellipk;


text:
<?php

namespace Components\Courses\Models;

use Components\Tags\Models\Cloud;

require_once \Component::path('com_tags') . DS . 'models' . DS . 'cloud.php';

/**
 * Helper class for handling course tags
 */
class Tags extends Cloud
{
	/**
	 * Object type, used for linking objects (such as resources) to tags
	 *
	 * @var  string
	 */
	protected $_scope = 'courses';

	/**
	 * Turn a string of tags to an array
	 *
	 * @param   string $tag Tag string
	 * @param   string $remove
	 * @return  mixed
	 */
	public function parseTags($tag, $remove='')
	{
		if (is_array($tag))
		{
			$bunch = $tag;
		}
		else
		{
			$bunch = $this->_parse($tag);
		}

		$tags = array();
		if ($remove)
		{
			foreach ($bunch as $t)
			{
				if ($remove == $t)
				{
					continue;
				}
				$tags[] = $t;
			}
		}
		else
		{
			return $bunch;
		}

		return $tags;
	}

	/**
	 * Render a tag cloud
	 *
	 * @param   string  $rtrn    Format to render
	 * @param   array   $filters Filters to apply
	 * @param   boolean $clear   Clear cached data?
	 * @return  string
	 */
	public function render($rtrn='html', $filters=array(), $clear=false)
	{
		switch (strtolower($rtrn))
		{
			case 'string':
				if (!isset($this->_cache['tags_string']) || $clear)
				{
					$tags = array();
					foreach ($this->tags('list', $filters, $clear) as $tag)
					{
						$tags[] = $tag->get('raw_tag');
					}
					$this->_cache['tags_string'] = implode(', ', $tags);
				}
				return $this->_cache['tags_string'];
			break;

			case 'array':
				return $this->tags('list', $filters, $clear);
			break;

			case 'cloud':
			case 'html':
			default:
				if (!isset($this->_cache['tags_cloud']) || $clear)
				{
					$view = new \Hubzero\Component\View(array(
						'base_path' => dirname(__DIR__) . '/site',
						'name'      => 'courses',
						'layout'    => '_tags'
					));
					if (isset($filters['filters']))
					{
						$view->base    = $filters['base'];
						$view->filters = $filters['filters'];
					}
					$view->config = \Component::params('com_tags');
					$view->tags   = $this->tags('list', $filters, $clear);

					$this->_cache['tags_cloud'] = $view->loadTemplate();
				}
				return $this->_cache['tags_cloud'];
			break;
		}
	}
}


text:
CCVideoPlayer
==================

Simple Video Player for Cocos2D apps.

Features
-------------

   * Universal support (iPhone + iPad + Mac)
   * Play / Cancel (by tap or key pressed on mac)
   * Plays file from Caches or Resources directory (if found) - compatible with FilesDownloader
   * Easy to use

Limitations
---------------

1. iOS: Supported orientations are only Landscape Left & Landscape Right ( Issue #13 )

Usage
-----------------------

CustomVideoView.nib is  needed only for Mac. (Probably it's possible to remove it and load view with code only. Issue #14 )

To link it you need MediaPlayer.framework for iOS & QTKit for Mac

To play videofile foo.mp4 simply use:

	// First tries to find file in NSCachesDirectory and play it from there
	// Second tries to find file in resources directory
	// Does nothing if file not found
    [CCVideoPlayer playMovieWithFile: @"bait.mp4"];

CCVideoPlayer ignores orientation change by itself, but you can manually change it's orientation:

    UIDeviceOrientation deviceOrientation = (UIDeviceOrientation)toInterfaceOrientation;
    [CCVideoPlayer updateOrientationWithOrientation: deviceOrientation ];

Playing video uses a lot of resources, so it's recommended to stop gpu render and other heavy tasks, while playing video.
You can do this by setting a CCVideoPlayer delegate:

    [CCVideoPlayer setDelegate: self];

Your delegate class should conform to CCVideoPlayerDelegate and implement these methods:

    - (void) moviePlaybackFinished
    {
        [[CCDirector sharedDirector] startAnimation];
    }

    - (void) movieStartsPlaying
    {
        [[CCDirector sharedDirector] stopAnimation];
    }

It's a weak ref, so don't forget to set CCVideoPlayer's delegate to nil in delegates dealloc or before.

Dependencies
----------------------------

1. QTKit.framework for Mac
2. MediaPlayer.framework for iOS

Supported Video Formats
----------------------------

Supported formats are the same as for MPMediaPlayer for iOS and QTMovie for Mac.
mp4 bundled with tests is compatible with both Mac & iOS


text:
steal("jquery/dom/fixture", function(){

	$.fixture.make("encoder", 5, function(i, encoder){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "encoder "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("volume", 5, function(i, volume){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "volume "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("disk", 5, function(i, disk){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "disk "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("user", 5, function(i, user){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "user "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("tcpip", 5, function(i, tcpip){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "tcpip "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("protocol", 5, function(i, protocol){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "protocol "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("iptable", 5, function(i, iptable){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "iptable "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("ddn_service", 5, function(i, ddn_service){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "ddn_service "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("profile", 5, function(i, profile){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "profile "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("schedule", 5, function(i, schedule){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "schedule "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("alarm", 5, function(i, alarm){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "alarm "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("alarm_data", 5, function(i, alarm_data){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "alarm_data "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("bookmark", 5, function(i, bookmark){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "bookmark "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("recording", 5, function(i, recording){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "recording "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("log", 5, function(i, log){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "log "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("log", 5, function(i, log){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "log "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("system_log", 5, function(i, system_log){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "system_log "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("camera_log", 5, function(i, camera_log){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "camera_log "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("user_log", 5, function(i, user_log){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "user_log "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("vision", 5, function(i, vision){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "vision "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
	$.fixture.make("emap", 5, function(i, emap){
		var descriptions = ["grill fish", "make ice", "cut onions"]
		return {
			name: "emap "+i,
			description: $.fixture.rand( descriptions , 1)[0]
		}
	})
})


text:
TEST=buffer-prefix1

TOPDIR=../../..
USE_LIBS=common
include ${TOPDIR}/common/program.mk


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EFCoreExtend.Sql.SqlConfig.Policies.Default
{
    /// <summary>
    /// 对sql的参数SqlParameter为Model(属性类)对象的参数进行遍历策略 的执行器
    /// </summary>
    [SqlConfigPolicy(SqlConfigConst.SqlForeachModelPolicyName)]
    public class SqlForeachModelPolicy : SqlParamObjEachPolicyBase<SqlForeachModelPolicyInfo>
    {
    }

    public class SqlForeachModelPolicyInfo : KVPairForeachPolicyInfoBase
    {

    }

}


text:
package com.google.wave.api.robot;

import com.google.common.base.Charsets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

/**
 * A {@link RobotConnection} that uses Apache's {@code HTTP Client} for
 * communicating with the robot.
 *
 */
public class HttpRobotConnection implements RobotConnection {

  /** A user agent client that can execute HTTP methods. */
  private final HttpClient httpClient;

  /** An executor to submit tasks asynchronously. */
  private final ExecutorService executor;

  /**
   * Constructor.
   *
   * @param client the client for executing HTTP methods.
   * @param executor the executor for submitting tasks asynchronously.
   */
  public HttpRobotConnection(HttpClient client, ExecutorService executor) {
    this.httpClient = client;
    this.executor = executor;
  }

  @Override
  public String get(String url) throws RobotConnectionException {
    GetMethod method = new GetMethod(url);
    return fetch(url, method);
  }

  @Override
  public ListenableFuture<String> asyncGet(final String url) {
    return Futures.makeListenable(executor.submit(new Callable<String>() {
      @Override
      public String call() throws RobotConnectionException {
        return get(url);
      }
    }));
  }

  @Override
  public String postJson(String url, String body) throws RobotConnectionException {
    PostMethod method = new PostMethod(url);
    try {
      method.setRequestEntity(new StringRequestEntity(body, RobotConnection.JSON_CONTENT_TYPE,
          Charsets.UTF_8.name()));
      return fetch(url, method);
    } catch (IOException e) {
      String msg = "Robot fetch http failure: " + url + ": " + e;
      throw new RobotConnectionException(msg, e);
    }
  }

  @Override
  public ListenableFuture<String> asyncPostJson(final String url, final String body) {
    return Futures.makeListenable(executor.submit(new Callable<String>() {
      @Override
      public String call() throws RobotConnectionException {
        return postJson(url, body);
      }
    }));
  }

  /**
   * Fetches the given URL, given a method ({@code GET} or {@code POST}).
   *
   * @param url the URL to be fetched.
   * @param method the method to fetch the URL, can be {@code GET} or
   *     {@code POST}.
   * @return the content of the URL.
   *
   * @throws RobotConnectionException if there is a problem fetching the URL,
   *     for example, if the response code is not HTTP OK (200).
   */
  private String fetch(String url, HttpMethod method) throws RobotConnectionException {
    try {
      int statusCode = httpClient.executeMethod(method);
      return RobotConnectionUtil.validateAndReadResponse(url, statusCode,
          method.getResponseBodyAsStream());
    } catch (IOException e) {
      String msg = "Robot fetch http failure: " + url + ".";
      throw new RobotConnectionException(msg, e);
    } finally {
      method.releaseConnection();
    }
  }
}


text:
**Build Number**  : $($build.buildnumber)
**Build Configuration** :  $($build.parameters | ConvertFrom-Json | select -ExpandProperty BuildConfiguration )
**Build started** : $("{0:dd/MM/yy HH:mm:ss}" -f [datetime]$build.startTime)
**Source Branch** $($build.sourceBranch)

## Associated work items
@@WILOOP@@
* **$($widetail.fields.'System.WorkItemType') $($widetail.id)** [Assigned by: $($widetail.fields.'System.AssignedTo'.displayName)] $($widetail.fields.'System.Title')
@@WILOOP@@

## Associated change sets/commits
@@CSLOOP@@
* **ID $($csdetail.changesetid)$($csdetail.commitid)** $($csdetail.comment)
@@CSLOOP@@


text:
@implementation AGCPerson

- (instancetype)initWithName:(NSString*)name
{
    self = [super init];
    if (!self) {
        return nil;
    }
    _name = name;
    return self;
}

- (NSString*)sectionIdentifier
{
    return [_name substringToIndex:1];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>PlausibleInstruments: Source/PLInstrumentResult.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Classes

Files

Source/PLInstrumentResult.h

00001
00027
00028 #import <Foundation/Foundation.h>
00029
00030 #import "PLInstrumentTime.h"
00031
00032 @interface PLInstrumentResult : NSObject {
00033 @private
00035     PLITimeInterval _totalTime;
00036
00038     unsigned long _iterations;
00039 }
00040
00041 + (id) resultWithRunTime: (PLITimeInterval) runTime iterations: (unsigned long) iterations;
00042 + (id) resultWithStartTime: (PLIAbsoluteTime) startTime endTime: (PLIAbsoluteTime) endTime iterations: (unsigned long) iterations;
00043
00044 - (id) initWithRunTime: (PLITimeInterval) runTime iterations: (unsigned long) iterations;
00045 - (id) initWithStartTime: (PLIAbsoluteTime) startTime endTime: (PLIAbsoluteTime) endTime iterations: (unsigned long) iterations;
00046
00047 - (double) iterationsPerInterval: (PLITimeInterval) timeInterval;
00048 - (PLITimeInterval) intervalPerIteration;
00049
00050 @end

<address style="text-align: right;">Generated on Wed Dec 31 18:55:32 2008 for PlausibleInstruments by

 1.5.5 </address>


text:
package org.elasticsearch.index.query.functionscore;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.Explanation;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.lucene.search.function.LeafScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexGeoPointFieldData;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.core.DateFieldMapper;
import org.elasticsearch.index.mapper.core.NumberFieldMapper;
import org.elasticsearch.index.mapper.geo.BaseGeoPointFieldMapper;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.MultiValueMode;

import java.io.IOException;
import java.util.Objects;

public abstract class DecayFunctionBuilder<DFB extends DecayFunctionBuilder<DFB>> extends ScoreFunctionBuilder<DFB> {

    protected static final String ORIGIN = "origin";
    protected static final String SCALE = "scale";
    protected static final String DECAY = "decay";
    protected static final String OFFSET = "offset";

    public static double DEFAULT_DECAY = 0.5;
    public static MultiValueMode DEFAULT_MULTI_VALUE_MODE = MultiValueMode.MIN;

    private final String fieldName;
    //parsing of origin, scale, offset and decay depends on the field type, delayed to the data node that has the mapping for it
    private final BytesReference functionBytes;
    private MultiValueMode multiValueMode = DEFAULT_MULTI_VALUE_MODE;

    /**
     * Convenience constructor that converts its parameters into json to parse on the data nodes.
     */
    protected DecayFunctionBuilder(String fieldName, Object origin, Object scale, Object offset) {
        this(fieldName, origin, scale, offset, DEFAULT_DECAY);
    }

    /**
     * Convenience constructor that converts its parameters into json to parse on the data nodes.
     */
    protected DecayFunctionBuilder(String fieldName, Object origin, Object scale, Object offset, double decay) {
        if (fieldName == null) {
            throw new IllegalArgumentException("decay function: field name must not be null");
        }
        if (scale == null) {
            throw new IllegalArgumentException("decay function: scale must not be null");
        }
        if (decay <= 0 || decay >= 1.0) {
            throw new IllegalStateException("decay function: decay must be in range 0..1!");
        }
        this.fieldName = fieldName;
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.startObject();
            if (origin != null) {
                builder.field(ORIGIN, origin);
            }
            builder.field(SCALE, scale);
            if (offset != null) {
                builder.field(OFFSET, offset);
            }
            builder.field(DECAY, decay);
            builder.endObject();
            this.functionBytes = builder.bytes();
        } catch (IOException e) {
            throw new IllegalArgumentException("unable to build inner function object",e);
        }
    }

    protected DecayFunctionBuilder(String fieldName, BytesReference functionBytes) {
        if (fieldName == null) {
            throw new IllegalArgumentException("decay function: field name must not be null");
        }
        if (functionBytes == null) {
            throw new IllegalArgumentException("decay function: function must not be null");
        }
        this.fieldName = fieldName;
        this.functionBytes = functionBytes;
    }

    /**
     * Read from a stream.
     */
    protected DecayFunctionBuilder(StreamInput in) throws IOException {
        super(in);
        fieldName = in.readString();
        functionBytes = in.readBytesReference();
        multiValueMode = MultiValueMode.readMultiValueModeFrom(in);
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeString(fieldName);
        out.writeBytesReference(functionBytes);
        multiValueMode.writeTo(out);
    }

    public String getFieldName() {
        return this.fieldName;
    }

    public BytesReference getFunctionBytes() {
        return this.functionBytes;
    }

    @Override
    public void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(getName());
        builder.field(fieldName);
        XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes);
        builder.copyCurrentStructure(parser);
        builder.field(DecayFunctionParser.MULTI_VALUE_MODE.getPreferredName(), multiValueMode.name());
        builder.endObject();
    }

    @SuppressWarnings("unchecked")
    public DFB setMultiValueMode(MultiValueMode multiValueMode) {
        if (multiValueMode == null) {
            throw new IllegalArgumentException("decay function: multi_value_mode must not be null");
        }
        this.multiValueMode = multiValueMode;
        return (DFB) this;
    }

    public MultiValueMode getMultiValueMode() {
        return this.multiValueMode;
    }

    @Override
    protected boolean doEquals(DFB functionBuilder) {
        return Objects.equals(this.fieldName, functionBuilder.getFieldName()) &&
                Objects.equals(this.functionBytes, functionBuilder.getFunctionBytes()) &&
                Objects.equals(this.multiValueMode, functionBuilder.getMultiValueMode());
    }

    @Override
    protected int doHashCode() {
        return Objects.hash(this.fieldName, this.functionBytes, this.multiValueMode);
    }

    @Override
    protected ScoreFunction doToFunction(QueryShardContext context) throws IOException {
        XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes);
        return parseVariable(fieldName, parser, context, multiValueMode);
    }

    /**
     * Override this function if you want to produce your own scorer.
     * */
    protected abstract DecayFunction getDecayFunction();

    private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryShardContext context,
            MultiValueMode mode) throws IOException {
        //the field must exist, else we cannot read the value for the doc later
        MappedFieldType fieldType = context.fieldMapper(fieldName);
        if (fieldType == null) {
            throw new ParsingException(parser.getTokenLocation(), "unknown field [{}]", fieldName);
        }

        // dates and time and geo need special handling
        parser.nextToken();
        if (fieldType instanceof DateFieldMapper.DateFieldType) {
            return parseDateVariable(parser, context, (DateFieldMapper.DateFieldType) fieldType, mode);
        } else if (fieldType instanceof BaseGeoPointFieldMapper.GeoPointFieldType) {
            return parseGeoVariable(parser, context, (BaseGeoPointFieldMapper.GeoPointFieldType) fieldType, mode);
        } else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
            return parseNumberVariable(parser, context, (NumberFieldMapper.NumberFieldType) fieldType, mode);
        } else {
            throw new ParsingException(parser.getTokenLocation(), "field [{}] is of type [{}], but only numeric types are supported.",
                    fieldName, fieldType);
        }
    }

    private AbstractDistanceScoreFunction parseNumberVariable(XContentParser parser, QueryShardContext context,
            NumberFieldMapper.NumberFieldType fieldType, MultiValueMode mode) throws IOException {
        XContentParser.Token token;
        String parameterName = null;
        double scale = 0;
        double origin = 0;
        double decay = 0.5;
        double offset = 0.0d;
        boolean scaleFound = false;
        boolean refFound = false;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                parameterName = parser.currentName();
            } else if (DecayFunctionBuilder.SCALE.equals(parameterName)) {
                scale = parser.doubleValue();
                scaleFound = true;
            } else if (DecayFunctionBuilder.DECAY.equals(parameterName)) {
                decay = parser.doubleValue();
            } else if (DecayFunctionBuilder.ORIGIN.equals(parameterName)) {
                origin = parser.doubleValue();
                refFound = true;
            } else if (DecayFunctionBuilder.OFFSET.equals(parameterName)) {
                offset = parser.doubleValue();
            } else {
                throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
            }
        }
        if (!scaleFound || !refFound) {
            throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE,
                    DecayFunctionBuilder.ORIGIN);
        }
        IndexNumericFieldData numericFieldData = context.getForField(fieldType);
        return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
    }

    private AbstractDistanceScoreFunction parseGeoVariable(XContentParser parser, QueryShardContext context,
            BaseGeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException {
        XContentParser.Token token;
        String parameterName = null;
        GeoPoint origin = new GeoPoint();
        String scaleString = null;
        String offsetString = "0km";
        double decay = 0.5;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                parameterName = parser.currentName();
            } else if (DecayFunctionBuilder.SCALE.equals(parameterName)) {
                scaleString = parser.text();
            } else if (DecayFunctionBuilder.ORIGIN.equals(parameterName)) {
                origin = GeoUtils.parseGeoPoint(parser);
            } else if (DecayFunctionBuilder.DECAY.equals(parameterName)) {
                decay = parser.doubleValue();
            } else if (DecayFunctionBuilder.OFFSET.equals(parameterName)) {
                offsetString = parser.text();
            } else {
                throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
            }
        }
        if (origin == null || scaleString == null) {
            throw new ElasticsearchParseException("[{}] and [{}] must be set for geo fields.", DecayFunctionBuilder.ORIGIN,
                    DecayFunctionBuilder.SCALE);
        }
        double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT);
        double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT);
        IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
        return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode);

    }

    private AbstractDistanceScoreFunction parseDateVariable(XContentParser parser, QueryShardContext context,
            DateFieldMapper.DateFieldType dateFieldType, MultiValueMode mode) throws IOException {
        XContentParser.Token token;
        String parameterName = null;
        String scaleString = null;
        String originString = null;
        String offsetString = "0d";
        double decay = 0.5;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                parameterName = parser.currentName();
            } else if (DecayFunctionBuilder.SCALE.equals(parameterName)) {
                scaleString = parser.text();
            } else if (DecayFunctionBuilder.ORIGIN.equals(parameterName)) {
                originString = parser.text();
            } else if (DecayFunctionBuilder.DECAY.equals(parameterName)) {
                decay = parser.doubleValue();
            } else if (DecayFunctionBuilder.OFFSET.equals(parameterName)) {
                offsetString = parser.text();
            } else {
                throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
            }
        }
        long origin;
        if (originString == null) {
            origin = context.nowInMillis();
        } else {
            origin = dateFieldType.parseToMilliseconds(originString, false, null, null);
        }

        if (scaleString == null) {
            throw new ElasticsearchParseException("[{}] must be set for date fields.", DecayFunctionBuilder.SCALE);
        }
        TimeValue val = TimeValue.parseTimeValue(scaleString, TimeValue.timeValueHours(24),
                DecayFunctionParser.class.getSimpleName() + ".scale");
        double scale = val.getMillis();
        val = TimeValue.parseTimeValue(offsetString, TimeValue.timeValueHours(24), DecayFunctionParser.class.getSimpleName() + ".offset");
        double offset = val.getMillis();
        IndexNumericFieldData numericFieldData = context.getForField(dateFieldType);
        return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
    }

    static class GeoFieldDataScoreFunction extends AbstractDistanceScoreFunction {

        private final GeoPoint origin;
        private final IndexGeoPointFieldData fieldData;

        private static final GeoDistance distFunction = GeoDistance.DEFAULT;

        public GeoFieldDataScoreFunction(GeoPoint origin, double scale, double decay, double offset, DecayFunction func,
                                         IndexGeoPointFieldData fieldData, MultiValueMode mode) {
            super(scale, decay, offset, func, mode);
            this.origin = origin;
            this.fieldData = fieldData;
        }

        @Override
        public boolean needsScores() {
            return false;
        }

        @Override
        protected NumericDoubleValues distance(LeafReaderContext context) {
            final MultiGeoPointValues geoPointValues = fieldData.load(context).getGeoPointValues();
            return mode.select(new MultiValueMode.UnsortedNumericDoubleValues() {
                @Override
                public int count() {
                    return geoPointValues.count();
                }

                @Override
                public void setDocument(int docId) {
                    geoPointValues.setDocument(docId);
                }

                @Override
                public double valueAt(int index) {
                    GeoPoint other = geoPointValues.valueAt(index);
                    return Math.max(0.0d,
                            distFunction.calculate(origin.lat(), origin.lon(), other.lat(), other.lon(), DistanceUnit.METERS) - offset);
                }
            }, 0.0);
        }

        @Override
        protected String getDistanceString(LeafReaderContext ctx, int docId) {
            StringBuilder values = new StringBuilder(mode.name());
            values.append(" of: [");
            final MultiGeoPointValues geoPointValues = fieldData.load(ctx).getGeoPointValues();
            geoPointValues.setDocument(docId);
            final int num = geoPointValues.count();
            if (num > 0) {
                for (int i = 0; i < num; i++) {
                    GeoPoint value = geoPointValues.valueAt(i);
                    values.append("Math.max(arcDistance(");
                    values.append(value).append("(=doc value),");
                    values.append(origin).append("(=origin)) - ").append(offset).append("(=offset), 0)");
                    if (i != num - 1) {
                        values.append(", ");
                    }
                }
            } else {
                values.append("0.0");
            }
            values.append("]");
            return values.toString();
        }

        @Override
        protected String getFieldName() {
            return fieldData.getFieldName();
        }

        @Override
        protected boolean doEquals(ScoreFunction other) {
            GeoFieldDataScoreFunction geoFieldDataScoreFunction = (GeoFieldDataScoreFunction) other;
            return super.doEquals(other) &&
                    Objects.equals(this.origin, geoFieldDataScoreFunction.origin);
        }

        @Override
        protected int doHashCode() {
            return Objects.hash(super.doHashCode(), origin);
        }
    }

    static class NumericFieldDataScoreFunction extends AbstractDistanceScoreFunction {

        private final IndexNumericFieldData fieldData;
        private final double origin;

        public NumericFieldDataScoreFunction(double origin, double scale, double decay, double offset, DecayFunction func,
                                             IndexNumericFieldData fieldData, MultiValueMode mode) {
            super(scale, decay, offset, func, mode);
            this.fieldData = fieldData;
            this.origin = origin;
        }

        @Override
        public boolean needsScores() {
            return false;
        }

        @Override
        protected NumericDoubleValues distance(LeafReaderContext context) {
            final SortedNumericDoubleValues doubleValues = fieldData.load(context).getDoubleValues();
            return mode.select(new MultiValueMode.UnsortedNumericDoubleValues() {
                @Override
                public int count() {
                    return doubleValues.count();
                }

                @Override
                public void setDocument(int docId) {
                    doubleValues.setDocument(docId);
                }

                @Override
                public double valueAt(int index) {
                    return Math.max(0.0d, Math.abs(doubleValues.valueAt(index) - origin) - offset);
                }
            }, 0.0);
        }

        @Override
        protected String getDistanceString(LeafReaderContext ctx, int docId) {

            StringBuilder values = new StringBuilder(mode.name());
            values.append("[");
            final SortedNumericDoubleValues doubleValues = fieldData.load(ctx).getDoubleValues();
            doubleValues.setDocument(docId);
            final int num = doubleValues.count();
            if (num > 0) {
                for (int i = 0; i < num; i++) {
                    double value = doubleValues.valueAt(i);
                    values.append("Math.max(Math.abs(");
                    values.append(value).append("(=doc value) - ");
                    values.append(origin).append("(=origin))) - ");
                    values.append(offset).append("(=offset), 0)");
                    if (i != num - 1) {
                        values.append(", ");
                    }
                }
            } else {
                values.append("0.0");
            }
            values.append("]");
            return values.toString();

        }

        @Override
        protected String getFieldName() {
            return fieldData.getFieldName();
        }

        @Override
        protected boolean doEquals(ScoreFunction other) {
            NumericFieldDataScoreFunction numericFieldDataScoreFunction = (NumericFieldDataScoreFunction) other;
            if (super.doEquals(other) == false) {
                return false;
            }
            return Objects.equals(this.origin, numericFieldDataScoreFunction.origin);
        }
    }

    /**
     * This is the base class for scoring a single field.
     *
     * */
    public static abstract class AbstractDistanceScoreFunction extends ScoreFunction {

        private final double scale;
        protected final double offset;
        private final DecayFunction func;
        protected final MultiValueMode mode;

        public AbstractDistanceScoreFunction(double userSuppiedScale, double decay, double offset, DecayFunction func,
                MultiValueMode mode) {
            super(CombineFunction.MULTIPLY);
            this.mode = mode;
            if (userSuppiedScale <= 0.0) {
                throw new IllegalArgumentException(FunctionScoreQueryBuilder.NAME + " : scale must be > 0.0.");
            }
            if (decay <= 0.0 || decay >= 1.0) {
                throw new IllegalArgumentException(FunctionScoreQueryBuilder.NAME + " : decay must be in the range [0..1].");
            }
            this.scale = func.processScale(userSuppiedScale, decay);
            this.func = func;
            if (offset < 0.0d) {
                throw new IllegalArgumentException(FunctionScoreQueryBuilder.NAME + " : offset must be > 0.0");
            }
            this.offset = offset;
        }

        /**
         * This function computes the distance from a defined origin. Since
         * the value of the document is read from the index, it cannot be
         * guaranteed that the value actually exists. If it does not, we assume
         * the user handles this case in the query and return 0.
         * */
        protected abstract NumericDoubleValues distance(LeafReaderContext context);

        @Override
        public final LeafScoreFunction getLeafScoreFunction(final LeafReaderContext ctx) {
            final NumericDoubleValues distance = distance(ctx);
            return new LeafScoreFunction() {

                @Override
                public double score(int docId, float subQueryScore) {
                    return func.evaluate(distance.get(docId), scale);
                }

                @Override
                public Explanation explainScore(int docId, Explanation subQueryScore) throws IOException {
                    return Explanation.match(
                            CombineFunction.toFloat(score(docId, subQueryScore.getValue())),
                            "Function for field " + getFieldName() + ":",
                            func.explainFunction(getDistanceString(ctx, docId), distance.get(docId), scale));
                }
            };
        }

        protected abstract String getDistanceString(LeafReaderContext ctx, int docId);

        protected abstract String getFieldName();

        @Override
        protected boolean doEquals(ScoreFunction other) {
            AbstractDistanceScoreFunction distanceScoreFunction = (AbstractDistanceScoreFunction) other;
            return Objects.equals(this.scale, distanceScoreFunction.scale) &&
                    Objects.equals(this.offset, distanceScoreFunction.offset) &&
                    Objects.equals(this.mode, distanceScoreFunction.mode) &&
                    Objects.equals(this.func, distanceScoreFunction.func) &&
                    Objects.equals(this.getFieldName(), distanceScoreFunction.getFieldName());
        }

        @Override
        protected int doHashCode() {
            return Objects.hash(scale, offset, mode, func, getFieldName());
        }
    }
}


text:
class DefaultAppointmentType < ActiveRecord::Migration[5.0]
  def change
    change_column_default :appointments, :type_of_appointment, ''
  end
end


text:
package org.nutz.json;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Json字段的映射
 *
 * @author zozoh(zozohtnt@gmail.com)
 * @author 有心猴(belialofking@163.com)
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Documented
public @interface JsonField {

    String value() default "";

    /**
     * 仅仅对 Field 有效,对 Method 则无效
     *
     * @return 是否忽略这个字段
     */
    boolean ignore() default false;

    /**
     * 有些对象类型总是被当做字符串输出会有更好的效果,比如 Region

     * 当然这些对象是可以被 Castors 从字符串正确的转换回来的。即它们有一个带一个字符串为参数的构造函数即可
     *

     * 这个声明,也将作用于数组,和集合
     *
     * @return 这个字段是否被强制输出成字符串
     * @see org.nutz.lang.util.Region
     */
    boolean forceString() default false;

    @Deprecated
    String dateFormat() default "";

    String dataFormat() default "";
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AssaultBird2454.VPTU.Server.Class.ConsoleCommands
{
    class Command
    {
    }
}


text:
package pr04_WorkForce.models;

import pr04_WorkForce.interfaces.Employee;
import pr04_WorkForce.interfaces.JobCompletedListener;

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

public class Job {

    private String name;
    private int hoursOfWorkRequired;
    private Employee employee;
    private List<JobCompletedListener> observers;

    public Job(String name, int hoursOfWorkRequired, Employee employee) {
        this.setName(name);
        this.setHoursOfWorkRequired(hoursOfWorkRequired);
        this.setEmployee(employee);
        this.observers = new ArrayList<>();
    }

    public String getName() {
        return this.name;
    }

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

    public int getHoursOfWorkRequired() {
        return this.hoursOfWorkRequired;
    }

    private void setHoursOfWorkRequired(int hoursOfWorkRequired) {
        this.hoursOfWorkRequired = hoursOfWorkRequired;
    }

    private void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public void update() {
        this.setHoursOfWorkRequired(this.getHoursOfWorkRequired() - this.employee.getWeeklyWorkHours());

        if (this.getHoursOfWorkRequired() <= 0) {
            System.out.printf("Job %s done!%n", this.getName());
            this.fireJobCompleteEvent();
        }
    }

    public void addJobCompleteListener(JobCompletedListener listener) {
        this.observers.add(listener);
    }

    public void removeJobCompleteListener(JobCompletedListener listener) {
        this.observers.remove(listener);
    }

    public void fireJobCompleteEvent() {
        JobCompletedEvent event = new JobCompletedEvent(this);

        for (JobCompletedListener observer : observers) {
            observer.handleJobCompleted(event);
        }
    }

    @Override
    public String toString() {
        return String.format("Job: %s Hours Remaining: %d", this.getName(), this.getHoursOfWorkRequired());
    }
}


text:
<?php

namespace tests\models;

use app\models\calc\tokens\LParToken;
use Codeception\Test\Unit;

class LParTokenTest extends Unit
{
    public function testNotRequiresValue()
    {
        new LParToken(1);
    }

    public function testGetLexeme()
    {
        $token = new LParToken(0);
        $this->assertTrue(preg_match($token->getLexemeFullRegExp(), $token->getLexeme()) == 1);
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>live coding / algoraves</title>
	<meta name="description" content="A brief history of live-coded music, algorave, and some opinions" />
	<meta name="author" content="Mike Hodnick" />
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui" />
	<link rel="stylesheet" href="css/reveal.css">
	<link rel="stylesheet" href="css/theme/black.css" id="theme">

	<link rel="stylesheet" href="lib/css/zenburn.css">

live coding / algorave

a brief history (and some opinions)

					Mike Hodnick /
						@kindohm

						kindohm.github.io/space150-livecoding

Mike Hodnick

a.k.a. kindohm

Programmer / noise-maker

programming

≈

problem-solving

problem solving

live experience

improvised

disposable

Live Coding

Change a running program in real time.

music

visual

spreadsheets?

live-coded music

Algorave

What does it sound like?

UK

Toronto / Vancouver

Karlsruhe / Berlin

Mexico City

Brooklyn / Albany

Pittsburgh

Baton Rouge

Milwaukee

Minneapolis

Learn

Toplap.org

algorave.com

"algorave" and "live coding"

Stay in touch

kindohm

.com, gmail, fb, twitter, snapchat, bandcamp, soundcloud


text:
var host='ayotli.com';
var pathNew='notifications';
var pathZero='';

var counter=0;
var newNotif=false;
var protocol='http'
var alwaysNew=false;
var showZero=false;
var deskNoti=null;
var showNoti=true;
var timeNoti=20000;
var timerVar=null;
var timerDelay=300000;
var playSound=true;
var audio=new Audio('sound.ogg'); // sound.ogg is button-44.wav from soundjay.com
window.onload=init;

var BADGE_NEW={color:[0,204,51,255]};
var BADGE_ACTIVE={color:[204,0,51,255]};
var BADGE_LOADING={color:[204,204,51,255]};
var BADGE_INACTIVE={color:[153,153,153,255]};

function loadData(){
	var xhr=new XMLHttpRequest();
	xhr.open('GET','http://ayotli.com/notifications/demo.json',true);	//JSON
	//xhr.open('GET','http://ayotli.com/notifications/demo.xml',true);	//XML
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4){
			chrome.browserAction.setBadgeBackgroundColor(BADGE_INACTIVE);

			var jsonDoc=JSON.parse(xhr.responseText);		//JSON
			var username=jsonDoc.username;					//JSON
			//var xmlDoc=new DOMParser().parseFromString(xhr.responseText,'text/xml');			//XML
			//var username=xmlDoc.getElementsByTagName('username')[0].childNodes[0].nodeValue;	//XML

			if(username){
				var lastCounter=counter;
				var mess=parseInt(jsonDoc.messages);		//JSON
				var noti=parseInt(jsonDoc.notifications);	//JSON
				//var mess=parseInt(xmlDoc.getElementsByTagName('messages')[0].childNodes[0].nodeValue);		//XML
				//var noti=parseInt(xmlDoc.getElementsByTagName('notifications')[0].childNodes[0].nodeValue);	//XML

				var badgeTitle=username+' - Notifications';
				if(mess>0) badgeTitle+='\n> '+mess+' messages';
				if(noti>0) badgeTitle+='\n> '+noti+' notifications';
				counter=mess+noti;

				chrome.browserAction.setIcon({path:'icon.png'});
				chrome.browserAction.setTitle({title:badgeTitle});
				if(!showZero&&counter==0)chrome.browserAction.setBadgeText({text:''});
				else chrome.browserAction.setBadgeText({text:counter+''});
				if(counter>lastCounter){
					newNotif=true;
					if(playSound)audio.play();
					if(showNoti){
						if(deskNoti)deskNoti.cancel();
						deskNoti=webkitNotifications.createNotification('icon48.png','Notifications','You have '+counter+' new notifications');
						deskNoti.onclick=function(){openPage();this.cancel()};
						deskNoti.show();
						if(timeNoti){window.setTimeout(function(){deskNoti.cancel();},timeNoti);}
					}
				}
				if(newNotif)chrome.browserAction.setBadgeBackgroundColor(BADGE_NEW);
				else if(counter>0)chrome.browserAction.setBadgeBackgroundColor(BADGE_ACTIVE);
			}
			else{
				chrome.browserAction.setIcon({path:'icon-.png'});
				chrome.browserAction.setTitle({title:'Notifications\n--Disconnected--'});
				chrome.browserAction.setBadgeText({text:'?'});
				return;
			}
		}
		else return;
	}
	xhr.send(null);
	window.clearTimeout(timerVar);
	timerVar=window.setTimeout(loadData,timerDelay);
}

function init(){
	pathNew=(localStorage.pathNew||localStorage.pathNew=='')?localStorage.pathNew:pathNew;
	pathZero=(localStorage.pathZero||localStorage.pathZero=='')?localStorage.pathZero:pathZero;
	protocol=(localStorage.useHttps=='yes')?'https':'http';
	alwaysNew=(localStorage.alwaysNew)?(localStorage.alwaysNew=='yes'):false;
	showZero=(localStorage.showZero)?(localStorage.showZero=='yes'):false;
	playSound=(localStorage.playSound)?(localStorage.playSound=='yes'):true;
	showNoti=(localStorage.showNoti)?(localStorage.showNoti=='yes'):true;
	timeNoti=parseInt(localStorage.timeNoti||'20000');
	timerDelay=parseInt(localStorage.refreshInterval||'300000');

	chrome.browserAction.setIcon({path:'icon-.png'});
	chrome.browserAction.setBadgeText({text:'...'});
	chrome.browserAction.setBadgeBackgroundColor(BADGE_LOADING);
	loadData();
}

function tabCallback(tab){
	chrome.tabs.onRemoved.addListener(function(tabId){if(tabId==tab.id)loadData();});
	chrome.windows.update(tab.windowId,{focused:true});
}

function openUrl(uri){
	chrome.windows.getAll({populate:true},function(windows){
		if(windows.length<1){
			chrome.windows.create({url:uri,focused:true});
			return;
		}
		else if(!alwaysNew){
			for(var i=0;i<windows.length;i++){
				var tabs=windows[i].tabs;
				for(var j=0;j<tabs.length;j++){
					if(tabs[j].url.indexOf(uri)!=-1){
						chrome.tabs.update(tabs[j].id,{selected:true},tabCallback); 			// Just Focus
						//chrome.tabs.update(tabs[j].id,{url:uri,selected:true},tabCallback); 	// Update and Focus
						return;
					}
				}
			}
		}
		chrome.tabs.getSelected(null,function(tab){
			if(tab.url=='chrome://newtab/')
				chrome.tabs.update(tab.id,{url:uri},tabCallback);
			else
				chrome.tabs.create({url:uri},tabCallback);
		});
	});
}

function openPage(){
	if(counter>0)
		openUrl(protocol+'://'+host+'/'+pathNew);
	else
		openUrl(protocol+'://'+host+'/'+pathZero);
	newNotif=false;
	loadData();
}

chrome.browserAction.onClicked.addListener(function(tab){
	openPage();
});


text:
"""
Copyright(c) 2022 Intel Corporation.

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.
"""

import json
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--p4-name", required=True,
                     help="Name of the P4 program")
parser.add_argument("--bf-rt-dir", required=True,
                     help="path of bf-rt.json")
parser.add_argument("--context-dir", required=True,
                     help="path of context.json")
parser.add_argument("--spec-dir", required=True,
                     help="path of spec file")
args = parser.parse_args()

bfrt = open(args.bf_rt_dir)
bfrt_json = json.load(bfrt)

#This func sets the path to store conf file
def set_conf():
    conf_path = args.bf_rt_dir.split("/")
    conf = ""
    i = 0
    while conf_path[i] != 'bf-rt.json':
        conf += conf_path[i] + "/"
        i += 1
    print("Conf File stored in -->",conf+args.p4_name+".conf")
    return conf+args.p4_name+".conf"

#This func sets the pipe_name in the conf file
def get_pipe_name():
    if 'tables' in bfrt_json:
        return bfrt_json['tables'][-1].get('name').split(".")[0]
    else:
        print("Error: Not able to find the tables")
        return NULL

#This funct set the context.json path for the conf file
def get_context():
    context_path = ""
    path = args.context_dir.split("/")
    path = path[path.index('install')+1:]
    context_path = path[0]
    for i in range(1 , len(path)):
        context_path += "/" + path[i]
    return context_path

#This func sets the spec file path in the conf file
def get_spec():
    spec_path = ""
    path = args.spec_dir.split("/")
    path = path[path.index('install')+1:]
    spec_path =  path[0]
    for i in range(1 , len(path)):
        spec_path += "/" + path[i]
    return spec_path

#Get the P4 Name to set in the conf file
def get_p4name():
    return args.p4_name

#Get the bf-rt.json path for the conf file
def bfrt_path():
    bfrt_path = ""
    path = args.bf_rt_dir.split("/")
    path = path[path.index('install')+1:]
    bfrt_path = path[0]
    for i in range(1 , len(path)):
        bfrt_path += "/" + path[i]
    return bfrt_path

#this func sets the path in the conf file
def get_path():
    return "sample_app/"+args.p4_name

#this is the schema for the conf file, Please traverse it from below
chip_list = []
list = {
        "id": "asic-0",
        "chip_family": "dpdk",
        "instance": 0
        }
chip_list.append(list)

p4_devices = []

mempool_data = [{
    "name": "MEMPOOL0",
    "buffer_size": 2304,
    "pool_size": 1024,
    "cache_size": 256,
    "numa_node": 0
    }]

scope = [
        0,
        1,
        2,
        3
        ]

pipeline = [{
    "p4_pipeline_name": get_pipe_name(),
    "core_id": 1,
    "numa_node": 0,
    "context": get_context(),
    "config": get_spec(),
    "pipe_scope" : scope,
    "path" : get_path()
    }]

p4_program = [{
    "program-name": get_p4name(),
    "bfrt-config": bfrt_path(),
    "p4_pipelines": pipeline,
    }]

devices = {
        "device-id": 0,
        "eal-args": "dummy -n 4 -c 3",
        "mempools": mempool_data,
        "p4_programs": p4_program
        }
p4_devices.append(devices)

data = {
        "chip_list" : chip_list,
        "instance" : 0,
        "p4_devices" : p4_devices,
        }

#after populating the schema write it in the conf file
with open(set_conf(), 'w') as f:
    json.dump(data, f, indent=4)


text:
/*! \file unique.h
 *  \brief Generic device implementation of unique()
 */

#pragma once

namespace thrust
{
namespace detail
{
namespace device
{
namespace generic
{

template <typename ForwardIterator,
          typename BinaryPredicate>
ForwardIterator unique(ForwardIterator first,
                       ForwardIterator last,
                       BinaryPredicate binary_pred);

template <typename InputIterator,
          typename OutputIterator,
          typename BinaryPredicate>
OutputIterator unique_copy(InputIterator first,
                           InputIterator last,
                           OutputIterator output,
                           BinaryPredicate binary_pred);

template <typename ForwardIterator1,
          typename ForwardIterator2,
          typename BinaryPredicate>
  thrust::pair<ForwardIterator1,ForwardIterator2>
  unique_by_key(ForwardIterator1 keys_first,
                ForwardIterator1 keys_last,
                ForwardIterator2 values_first,
                BinaryPredicate binary_pred);

template <typename InputIterator1,
          typename InputIterator2,
          typename OutputIterator1,
          typename OutputIterator2,
          typename BinaryPredicate>
  thrust::pair<OutputIterator1,OutputIterator2>
  unique_copy_by_key(InputIterator1 keys_first,
                     InputIterator1 keys_last,
                     InputIterator2 values_first,
                     OutputIterator1 keys_output,
                     OutputIterator2 values_output,
                     BinaryPredicate binary_pred);

} // end namespace generic
} // end namespace device
} // end namespace detail
} // end namespace thrust

#include "unique.inl"


text:
Decimal128: Invalid
--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php

DO NOT EDIT THIS FILE
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

throws(function() {
    new MongoDB\BSON\Decimal128('-Na');
}, 'MongoDB\Driver\Exception\InvalidArgumentException');

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\InvalidArgumentException
===DONE===


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;

    public static class EditTools
    {
        public static bool UpdateHitPos(GameObject p_gameObj, Vector3 planeNormal, ref Vector3 p_mouseHitPos)
        {
            // get reference to the tile map component
            Plane p = new Plane(p_gameObj.transform.TransformDirection(planeNormal), p_gameObj.transform.position);
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
            var hit = new Vector3();
            float dist;
            if (p.Raycast(ray, out dist))
            {
                hit = ray.origin + (ray.direction.normalized * dist);
            }
            var value = p_gameObj.transform.InverseTransformPoint(hit);
            if (value != p_mouseHitPos)
            {
                p_mouseHitPos = value;
                return true;
            }
            // return false if the hit test failed
            return false;
        }

        public static bool UpdateHitPos(Transform p_t, GameObject p_gameObj, Vector3 planeNormal, ref Vector3 p_mouseHitPos)
        {
            // get reference to the tile map component
            Plane p = new Plane(p_gameObj.transform.TransformDirection(planeNormal), p_gameObj.transform.position);
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
            var hit = new Vector3();
            float dist;
            if (p.Raycast(ray, out dist))
            {
                hit = ray.origin + (ray.direction.normalized * dist);
            }
            var value = p_gameObj.transform.InverseTransformPoint(hit);
            Handles.color = new Color(1f, 0f, 0f, 0.7f);
            if (value != p_mouseHitPos)
            {
                p_mouseHitPos = value;
                return true;
            }
            // return false if the hit test failed
            return false;
        }
    }


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**isGlobal** | **Boolean** |  |  [optional]
**overrideGlobal** | **Boolean** |  |  [optional]
**apiToken** | **String** |  |  [optional]
**collectionId** | **String** |  |  [optional]
**baseUrl** | **String** |  |  [optional]


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>The charbox template...</title>
		<link>http://bvs.wikidot.com/forum/t-48529/the-charbox-template</link>
		<description>Posts in the discussion thread "The charbox template..."</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 04:22:04 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-48529#post-129857</guid>
				<title>Re: The charbox template...</title>
				<link>http://bvs.wikidot.com/forum/t-48529/the-charbox-template#post-129857</link>
				<description></description>
				<pubDate>Sun, 23 Mar 2008 00:12:58 +0000</pubDate>
				<wikidot:authorName>BvS-Uzuki</wikidot:authorName>				<wikidot:authorUserId>78144</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Done now. Just add the following line anywhere in the template:

 |season=1

Where "1" is your current season.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-48529#post-129854</guid>
				<title>Re: The charbox template...</title>
				<link>http://bvs.wikidot.com/forum/t-48529/the-charbox-template#post-129854</link>
				<description></description>
				<pubDate>Sun, 23 Mar 2008 00:07:44 +0000</pubDate>
				<wikidot:authorName>BvS-Uzuki</wikidot:authorName>				<wikidot:authorUserId>78144</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Yep. Will do that now.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-48529#post-129851</guid>
				<title>The charbox template...</title>
				<link>http://bvs.wikidot.com/forum/t-48529/the-charbox-template#post-129851</link>
				<description></description>
				<pubDate>Sat, 22 Mar 2008 23:47:18 +0000</pubDate>
				<wikidot:authorName>Fax</wikidot:authorName>				<wikidot:authorUserId>90931</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

…is there a way we can make it include season?

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea furfuracea var. furfuracea Pers.

### Remarks
null


text:
//
//  Copyright © 2016年 Vizlab. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "VZFNodeListItem.h"
#import "VZMistItem.h"

@class VZMistListItem;
@protocol VZMistListItem <VZMistItem>

- (UITableView *)tableView;

//- (VZMistListItem *)itemAtIndexPath:(NSIndexPath *)indexPath;

@end

@class VZMistTemplateController;
@class VZMistTemplate;
@class VZMist;

@interface VZMistListItem : VZFNodeListItem <VZMistListItem, VZMistAsyncDisplayItem>

/**
 继承自父类。item 展示所需要的宽度,使用的是屏幕宽度。
 */
//@property (nonatomic, assign, readonly) float itemWidth;

/**
 继承自父类。item 展示所需的高度,也就是对应的 cell 的高度。
 */
//@property (nonatomic, assign, readonly) float itemHeight;

/**
 继承自父类。展示到的 view,也就是 cell 的 contentView
 */
//@property (nonatomic, weak, readonly) UIView *attachedView;

/**
 tableView 的 indexPath
 */
@property (nonatomic, strong, readonly) NSIndexPath *indexPath;
/**
 template controller 对象
 */
@property (nonatomic, strong, readonly) VZMistTemplateController *tplController;
/**
 模板中UI组件的的state,理解state参考Reacthttps://facebook.github.io/react-native/docs/state.html
 @discussion:
 state的初始值(initial state)会优先从模板的"state"标签获取,如果没有则会从controller的initialState获取
 */
@property (nonatomic, strong, readonly) NSDictionary *state;
/**
 执行表达式的 context
 */
@property (nonatomic, strong, readonly) VZTExpressionContext *expressionContext;
/**
 自定义数据,修改后,可调用 render 刷新布局
 */
@property (nonatomic, strong) NSMutableDictionary *customData;
/**
 关联的模板对象
 */
@property (nonatomic, strong, readonly) VZMistTemplate *tpl;
/**
 异步渲染开启标志
 */
@property (nonatomic, assign) BOOL asyncDisplay;

@property (nonatomic, assign) CGSize constrainedSize;

/**
 渲染,生成视图布局
 */
- (void)render;

/**
 通过数据和模板构造Item对象

 @param data 数据
 @param customData 放置模板所需要的自定义数据,也就是非来自服务器端下发的。比如传入indexPath,屏幕宽度等
 @param tpl 模板对象
 @return item 构建好的item
 */
- (instancetype)initWithData:(NSDictionary *)data
                  customData:(NSDictionary *)customData
                    template:(VZMistTemplate *)tpl NS_DESIGNATED_INITIALIZER;

/**
 更新关联的数据
 @discussion: 更新数据仍会保留state
 @param data 数据
 */
- (void)setData:(NSDictionary *)data keepState:(BOOL)b;
/**
 更新state参考Reacthttps://facebook.github.io/react-native/docs/state.html
 @param block state更新函数
 */
- (void)updateState:(NSDictionary * (^)(NSDictionary * oldState))block;

/**
 table view 下使用这个方法传入 indexPath,用于 item 更新界面的时候做一下检测保护。

 @param view cell 的 contentView
 @param indexPath cell 的 indexPath
 */
- (void)attachToView:(UIView *)view atIndexPath:(NSIndexPath *)indexPath;

- (VZMist *)mistInstance;

@end


text:
var React = require('react');

var BugComment = React.createClass({displayName: "BugComment",
	render: function() {
		var comment = this.props.comment;
		return (
			React.createElement("li", null,
				comment.text
			)
		)
	}
});
module.exports = BugComment;


text:
package com.helger.commons.mime;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.helger.commons.annotation.Nonempty;
import com.helger.commons.id.IHasID;
import com.helger.commons.lang.EnumHelper;
import com.helger.commons.string.StringHelper;

/**
 * Determines the most well known MIME content types.
 *
 * @author Philip Helger
 */
public enum EMimeContentType implements IHasID <String>
{
  APPLICATION ("application"),
  AUDIO ("audio"),
  EXAMPLE ("example"),
  FONT ("font"),
  IMAGE ("image"),
  MESSAGE ("message"),
  MODEL ("model"),
  MULTIPART ("multipart"),
  TEXT ("text"),
  VIDEO ("video"),
  // Special ones
  CHEMICAL ("chemical"),
  FLV_APPLICATION ("flv-application"),
  INODE ("inode"),
  WWW ("www"),
  X_CONFERENCE ("x-conference"),
  X_CONTENT ("x-content"),
  X_DIRECTORY ("x-directory"),
  X_EPOC ("x-epoc"),
  X_WORLD ("x-world"),
  ZZ_APPLICATION ("zz-application"),
  // Generic
  _STAR ("*");

  private final String m_sText;

  /**
   * Constructor
   *
   * @param sText
   *        Must be lowercase MIME content type
   */
  EMimeContentType (@Nonnull @Nonempty final String sText)
  {
    m_sText = sText;
  }

  /**
   * @return The lower case text representation of this MIME content type.
   */
  @Nonnull
  @Nonempty
  public String getID ()
  {
    return m_sText;
  }

  /**
   * @return The lower case text representation of this MIME content type.
   * @see #getID()
   */
  @Nonnull
  @Nonempty
  public String getText ()
  {
    return m_sText;
  }

  /**
   * Build a new {@link MimeType} based on this MIME content type and the
   * provided sub type.
   *
   * @param sContentSubType
   *        The content sub type to append. May neither be null nor
   *        empty.
   * @return Never null.
   */
  @Nonnull
  public MimeType buildMimeType (@Nonnull @Nonempty final String sContentSubType)
  {
    return new MimeType (this, sContentSubType);
  }

  /**
   * Check if the passed MIME type has the same content type as this
   *
   * @param sMimeType
   *        The MIME type string to be checked. May be null.
   * @return true if the passed MIME type has this content type,
   *         false otherwise
   */
  public boolean isTypeOf (@Nullable final String sMimeType)
  {
    if (StringHelper.hasNoText (sMimeType))
      return false;
    final int nIdx = sMimeType.indexOf (CMimeType.SEPARATOR_CONTENTTYPE_SUBTYPE);
    if (nIdx < 0)
      return false;
    return m_sText.equalsIgnoreCase (sMimeType.substring (0, nIdx));
  }

  @Nullable
  public static EMimeContentType getFromIDOrNull (@Nullable final String sID)
  {
    // As MIME types are not case sensitive, this method may not be either :)
    return EnumHelper.getFromIDCaseInsensitiveOrNull (EMimeContentType.class, sID);
  }
}


text:
//// Copyright (c) Microsoft. All rights reserved.
//// Licensed under the MIT license. See LICENSE file in the project root for full license information.

//using System;
//using System.Collections.Generic;
//using System.Composition;

//using Microsoft.CodeAnalysis.Sarif.Driver.Sdk;
//using Microsoft.CodeAnalysis.Sarif.Sdk;
//using Microsoft.CodeAnalysis.Sql.Sdk;
//using Microsoft.SqlServer.TransactSql.ScriptDom;

//namespace Microsoft.CodeAnalysis.Sql.Rules
//{
//    [Export(typeof(ISkimmer<SqlFileContext>)), Export(typeof(IRuleDescriptor))]
//    public class RemoveUnusedVariables : SqlSkimmerBase
//    {
//        public override string Id { get { return RuleIds.RemoveUnusedVariables; } }

//        public override string FullDescription { get { return RuleResources.SQL2001_RemoveUnusedVariables_Description; } }

//        public override void Analyze(SqlFileContext context)
//        {
//            return;
//        }

//        public override IEnumerable<Type> Types { get { return new Type[] { }; } }
//    }
//}