<commit_before>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('log')('plan');
var defaults = require('model-defaults');
var model = require('model');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 25;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bus: true,
    car: true,
    days: 'M—F',
    end_time: 9,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    per_year: false,
    start_time: 7,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('per_day')
  .attr('per_year')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.fromIsValid() && this.toIsValid();
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback) {
  callback = callback || function() {}; // noop callback

  // Don't set if they're the same
  if (toLowerCase(this[name]()) === toLowerCase(address)) return callback();

  var plan = this;
  var location = new Location({
    address: address
  });

  location.save(function(err, res) {
    if (err) {
      callback(err);
    } else {
      var changes = {};
      changes[name] = address;
      changes[name + '_ll'] = res.body.coordinate;
      changes[name + '_id'] = res.body._id;
      changes[name + '_valid'] = true;

      plan.set(changes);
      callback(null, res.body);
    }
  });
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

/**
 * From is valid
 */

Plan.prototype.fromIsValid = function() {
  var from = this.from_ll();
  return !!from && !!from.lat && !!from.lng;
};

/**
 * To is valid
 */

Plan.prototype.toIsValid = function() {
  var to = this.to_ll();
  return !!to && !!to.lat && !!to.lng;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bus()) modes.push('BUS');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;

  this.bike(csv.indexOf('BICYCLE') !== -1);
  this.bus(csv.indexOf('BUS') !== -1);
  this.train(csv.indexOf('TRAINISH') !== -1);
  this.car(csv.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll();
  var to = this.to_ll();

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    bikeSpeed: scorer.rates.bikeSpeed,
    from: {
      lat: from.lat,
      lon: from.lng,
      name: 'From'
    },
    to: {
      lat: to.lat,
      lon: to.lng,
      name: 'To'
    },
    startTime: startTime,
    endTime: endTime,
    date: this.nextDate(),
    modes: this.modesCSV(),
    walkSpeed: scorer.rates.walkSpeed
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
  var url = '?';
  url += 'from=' + this.from();
  url += '&to=' + this.to();
  url += '&modes=' + this.modesCSV();
  url += '&start_time=' + this.start_time();
  url += '&end_time=' + this.end_time();
  url += '&days=' + this.days();

  window.history.replaceState(null, '', url);
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};
<commit_msg>Use access, direct, egress, and transit mode parameters<commit_after>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('log')('plan');
var defaults = require('model-defaults');
var model = require('model');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 25;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bus: true,
    car: true,
    days: 'M—F',
    end_time: 9,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    per_year: false,
    start_time: 7,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('per_day')
  .attr('per_year')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.fromIsValid() && this.toIsValid();
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback) {
  callback = callback || function() {}; // noop callback

  // Don't set if they're the same
  if (toLowerCase(this[name]()) === toLowerCase(address)) return callback();

  var plan = this;
  var location = new Location({
    address: address
  });

  location.save(function(err, res) {
    if (err) {
      callback(err);
    } else {
      var changes = {};
      changes[name] = address;
      changes[name + '_ll'] = res.body.coordinate;
      changes[name + '_id'] = res.body._id;
      changes[name + '_valid'] = true;

      plan.set(changes);
      callback(null, res.body);
    }
  });
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

/**
 * From is valid
 */

Plan.prototype.fromIsValid = function() {
  var from = this.from_ll();
  return !!from && !!from.lat && !!from.lng;
};

/**
 * To is valid
 */

Plan.prototype.toIsValid = function() {
  var to = this.to_ll();
  return !!to && !!to.lat && !!to.lng;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bus()) modes.push('BUS');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;

  this.bike(csv.indexOf('BICYCLE') !== -1);
  this.bus(csv.indexOf('BUS') !== -1);
  this.train(csv.indexOf('TRAINISH') !== -1);
  this.car(csv.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll();
  var to = this.to_ll();

  // Transit modes
  var accessModes = [ 'WALK' ];
  var directModes = [ 'CAR', 'WALK' ];
  var egressModes = [ 'WALK' ];
  var transitModes = [];

  if (this.bike()) {
    accessModes.push('BICYCLE');
    directModes.push('BICYCLE');
  }
  if (this.bus()) transitModes.push('BUS');
  if (this.car()) accessModes.push('CAR');
  if (this.train()) transitModes.push('TRAINISH');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    accessModes: accessModes.join(','),
    bikeSpeed: scorer.rates.bikeSpeed,
    date: this.nextDate(),
    directModes: directModes.join(','),
    egressModes: egressModes.join(','),
    endTime: endTime,
    from: {
      lat: from.lat,
      lon: from.lng,
      name: 'From'
    },
    startTime: startTime,
    to: {
      lat: to.lat,
      lon: to.lng,
      name: 'To'
    },
    transitModes: transitModes.join(','),
    walkSpeed: scorer.rates.walkSpeed
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
  var url = '?';
  url += 'from=' + this.from();
  url += '&to=' + this.to();
  url += '&modes=' + this.modesCSV();
  url += '&start_time=' + this.start_time();
  url += '&end_time=' + this.end_time();
  url += '&days=' + this.days();

  window.history.replaceState(null, '', url);
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var _ = require('lodash');
var find = require('../../src/blueprints/find');
var ActionTypes = require('lore-utils').ActionTypes;

describe('blueprints#find', function() {
  var modelName = 'todo';
  var blueprint = find;
  var reducer = null;

  beforeEach(function() {
    reducer = blueprint(modelName);
  });

  describe("find sequence", function() {
    var action1, action2, query;

    beforeEach(function() {
      query = {};

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1'
          }]
        }
      };
    });

    it("should add models to the dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, { nextState: {}});
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);
    });
  });

  describe("find/add sequence for empty query", function() {
    var action1, action2, action3, action4, query;

    beforeEach(function() {
      query = {
        where: {}
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1'
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: null,
          cid: 'c2'
        }
      };

      action4 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: '2',
          cid: 'c2'
        }
      };
    });

    it("should add the model to the default dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, {
        nextState: {
          byId: { },
          byCid: { }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(1);
      expect(state3[queryKey].data.length).to.equal(2);

      var state4 = reducer(state3, action4, {
        nextState: {
          byId: {
            '1': action2.payload.data[0],
            '2': action4.payload
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action4.payload
          }
        }
      });
      expect(_.keys(state4).length).to.equal(1);
      expect(state4[queryKey].data.length).to.equal(2);
    });
  });

  describe("find/add sequence for a query", function() {
    var action1, action2, action3, action4, query;

    beforeEach(function() {
      query = {
        where: {
          title: 'foo'
        }
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1',
            data: {
              title: 'foo'
            }
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: null,
          cid: 'c2',
          data: {
            title: 'foo'
          }
        }
      };

      action4 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: '2',
          cid: 'c2',
          data: {
            title: 'foo'
          }
        }
      };
    });

    it("should add the model to the default dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, {
        nextState: {
          byId: { },
          byCid: { }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(1);
      expect(state3[queryKey].data.length).to.equal(2);

      var state4 = reducer(state3, action4, {
        nextState: {
          byId: {
            '1': action2.payload.data[0],
            '2': action4.payload
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action4.payload
          }
        }
      });
      expect(_.keys(state4).length).to.equal(1);
      expect(state4[queryKey].data.length).to.equal(2);
    });
  });

  describe("find/add sequence for multiple queries", function() {
    var action1, action2, action3, query1, query2;

    beforeEach(function() {
      query1 = {
        where: {
          title: 'foo'
        }
      };

      query2 = {
        where: {
          title: 'bar'
        }
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query1,
        payload: {
          data: [{
            id: '1',
            cid: 'c1',
            data: {
              title: 'foo'
            }
          }]
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query2,
        payload: {
          data: [{
            id: '2',
            cid: 'c2',
            data: {
              title: 'bar'
            }
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        payload: {
          id: '3',
          cid: 'c3',
          data: {
            title: 'foo'
          }
        }
      };
    });

    it("should update each query properly", function() {
      var query1Key = JSON.stringify(query1);
      var query2Key = JSON.stringify(query2);

      var state = reducer(null, action1, {
        nextState: {
          byId: {
            '1': action1.payload.data[0]
          },
          byCid: {
            'c1': action1.payload.data[0]
          }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[query1Key].data.length).to.equal(1);
      expect(state[query2Key]).to.equal(undefined);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action1.payload.data[0],
            '2': action2.payload.data[0]
          },
          byCid: {
            'c1': action1.payload.data[0],
            'c2': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(2);
      expect(state2[query1Key].data.length).to.equal(1);
      expect(state2[query2Key].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action1.payload.data[0],
            '2': action2.payload.data[0],
            '3': action3.payload
          },
          byCid: {
            'c1': action1.payload.data[0],
            'c2': action2.payload.data[0],
            'c3': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(2);
      expect(state3[query1Key].data.length).to.equal(2);
      expect(state3[query2Key].data.length).to.equal(1);
    });
  });

});

<commit_msg>[lore-hook-reducers] fix tests<commit_after>var expect = require('chai').expect;
var _ = require('lodash');
var find = require('../../src/blueprints/find');
var ActionTypes = require('lore-utils').ActionTypes;

describe('blueprints#find', function() {
  var modelName = 'todo';
  var blueprint = find;
  var reducer = null;

  beforeEach(function() {
    reducer = blueprint(modelName);
  });

  describe("find sequence", function() {
    var action1, action2, query;

    beforeEach(function() {
      query = {};

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1'
          }]
        }
      };
    });

    it("should add models to the dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, { nextState: {}});
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);
    });
  });

  describe("find/add sequence for empty query", function() {
    var action1, action2, action3, action4, query;

    beforeEach(function() {
      query = {
        where: {}
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1'
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: null,
          cid: 'c2'
        }
      };

      action4 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: '2',
          cid: 'c2'
        }
      };
    });

    it.skip("should add the model to the default dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, {
        nextState: {
          byId: { },
          byCid: { }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(1);
      expect(state3[queryKey].data.length).to.equal(2);

      var state4 = reducer(state3, action4, {
        nextState: {
          byId: {
            '1': action2.payload.data[0],
            '2': action4.payload
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action4.payload
          }
        }
      });
      expect(_.keys(state4).length).to.equal(1);
      expect(state4[queryKey].data.length).to.equal(2);
    });
  });

  describe("find/add sequence for a query", function() {
    var action1, action2, action3, action4, query;

    beforeEach(function() {
      query = {
        where: {
          title: 'foo'
        }
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: []
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query,
        payload: {
          data: [{
            id: '1',
            cid: 'c1',
            data: {
              title: 'foo'
            }
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: null,
          cid: 'c2',
          data: {
            title: 'foo'
          }
        }
      };

      action4 = {
        type: ActionTypes.add(modelName),
        query: query,
        payload: {
          id: '2',
          cid: 'c2',
          data: {
            title: 'foo'
          }
        }
      };
    });

    it.skip("should add the model to the default dictionary", function() {
      var queryKey = JSON.stringify(query);

      var state = reducer(null, action1, {
        nextState: {
          byId: { },
          byCid: { }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[queryKey].data.length).to.equal(0);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(1);
      expect(state2[queryKey].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action2.payload.data[0]
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(1);
      expect(state3[queryKey].data.length).to.equal(2);

      var state4 = reducer(state3, action4, {
        nextState: {
          byId: {
            '1': action2.payload.data[0],
            '2': action4.payload
          },
          byCid: {
            'c1': action2.payload.data[0],
            'c2': action4.payload
          }
        }
      });
      expect(_.keys(state4).length).to.equal(1);
      expect(state4[queryKey].data.length).to.equal(2);
    });
  });

  describe("find/add sequence for multiple queries", function() {
    var action1, action2, action3, query1, query2;

    beforeEach(function() {
      query1 = {
        where: {
          title: 'foo'
        }
      };

      query2 = {
        where: {
          title: 'bar'
        }
      };

      action1 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query1,
        payload: {
          data: [{
            id: '1',
            cid: 'c1',
            data: {
              title: 'foo'
            }
          }]
        }
      };

      action2 = {
        type: ActionTypes.fetchPlural(modelName),
        query: query2,
        payload: {
          data: [{
            id: '2',
            cid: 'c2',
            data: {
              title: 'bar'
            }
          }]
        }
      };

      action3 = {
        type: ActionTypes.add(modelName),
        payload: {
          id: '3',
          cid: 'c3',
          data: {
            title: 'foo'
          }
        }
      };
    });

    it.skip("should update each query properly", function() {
      var query1Key = JSON.stringify(query1);
      var query2Key = JSON.stringify(query2);

      var state = reducer(null, action1, {
        nextState: {
          byId: {
            '1': action1.payload.data[0]
          },
          byCid: {
            'c1': action1.payload.data[0]
          }
        }
      });
      expect(_.keys(state).length).to.equal(1);
      expect(state[query1Key].data.length).to.equal(1);
      expect(state[query2Key]).to.equal(undefined);

      var state2 = reducer(state, action2, {
        nextState: {
          byId: {
            '1': action1.payload.data[0],
            '2': action2.payload.data[0]
          },
          byCid: {
            'c1': action1.payload.data[0],
            'c2': action2.payload.data[0]
          }
        }
      });
      expect(_.keys(state2).length).to.equal(2);
      expect(state2[query1Key].data.length).to.equal(1);
      expect(state2[query2Key].data.length).to.equal(1);

      var state3 = reducer(state2, action3, {
        nextState: {
          byId: {
            '1': action1.payload.data[0],
            '2': action2.payload.data[0],
            '3': action3.payload
          },
          byCid: {
            'c1': action1.payload.data[0],
            'c2': action2.payload.data[0],
            'c3': action3.payload
          }
        }
      });
      expect(_.keys(state3).length).to.equal(2);
      expect(state3[query1Key].data.length).to.equal(2);
      expect(state3[query2Key].data.length).to.equal(1);
    });
  });

});

<|endoftext|>


<commit_before>describe("Channel", function() {
  var mediator;

  beforeEach(function() {
    channel = new Mediator.Channel();
  });

  describe("AddSubscriber", function(){
    it("should add a callback to the collection", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel._callbacks.length).toBe(1);
    });

    it("should give callbacks an id", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel._callbacks[0].id).toBeDefined();
      expect(channel._callbacks[0].id).not.toBe('');
    });

    it("should add a callback to the collection with context", function(){
      var spy = jasmine.createSpy("adding a callback with context"),
          contextObj = { derp: "herp" };

      channel.AddSubscriber(spy, {}, contextObj);
      expect(channel._callbacks[0].context).toBe(contextObj);
    });

    it("should add a callback to the collection with options", function(){
      var spy = jasmine.createSpy("adding a callback with context"),
          contextObj = window,
          optionsObj = { derp: "herp" };

      channel.AddSubscriber(spy, optionsObj, contextObj);
      expect(channel._callbacks[0].options).toBe(optionsObj);
    });

    it("should be able to set top priority", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2, { priority: 0 });
      channel.AddSubscriber(spy3);

      expect(channel._callbacks[0].fn).toBe(spy2);
    });

    it("should be able to set arbitrary priority", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      channel.AddSubscriber(spy3, { priority: 1 });

      expect(channel._callbacks[1].fn).toBe(spy3);
    });

    it("should be able to change priority after adding it", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      var sub = channel.AddSubscriber(spy, { num: 1 });
      channel.AddSubscriber(spy2, { num: 2 });
      channel.AddSubscriber(spy3, { num: 3 });

      channel.SetPriority(sub.id, 1);

      expect(channel._callbacks[1].fn).toBe(spy);

    });
  });

  describe("GetSubscriber", function(){
    it("should get a callback by its id", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel.GetSubscriber(channel._callbacks[0].id)).toBeDefined();
    });
  });

  describe("AddChannel", function(){
    it("should add a channel to the collection", function(){
      var channelName = "test";
      channel.AddChannel(channelName);

      expect(channel._channels[channelName]).toBeDefined();
    });
  });

  describe("HasChannel", function(){
    it("should return true if the channel exists", function(){
      var channelName = "test";
      channel.AddChannel(channelName);

      expect(channel.HasChannel(channelName)).toBe(true);
    });

    it("should return true if the channel does not exist", function(){
      var channelName = "test",
          badChannelName = "herp";

      channel.AddChannel(channelName);

      expect(channel.HasChannel(badChannelName)).toBe(false);
    });
  });

  describe("ReturnChannel", function(){
    it("should return a reference to a channel by name", function(){
      var channelName = "test";

      channel.AddChannel(channelName);

      expect(channel.ReturnChannel(channelName)).toBe(channel._channels[channelName]);
    });
  });

  describe("RemoveSubscriber", function(){
    it("should remove callbacks if no fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback");

      channel.AddSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);

      channel.RemoveSubscriber();
      expect(channel._callbacks.length).toBe(0);
    });

    it("should remove matching callbacks a valid fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding a second test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);
      expect(channel._callbacks[0].fn).toBe(spy2);
    });

    it("should remove matching callbacks a valid id is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding a second test callback");

      var sub = channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(sub.id);
      expect(channel._callbacks.length).toBe(1);
      expect(channel._callbacks[0].fn).toBe(spy2);
    });

    it("should do nothing if an valid fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          invalidFn = "derp";

      channel.AddSubscriber(spy);
      channel.AddSubscriber(function() {});
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(invalidFn);
      expect(channel._callbacks.length).toBe(2);
    });

    it("should do nothing if a non-matching fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
        spy2 = jasmine.createSpy("adding another test callback");

      channel.AddSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);

      channel.RemoveSubscriber(spy2);
      expect(channel._callbacks.length).toBe(1);
    });
  });

  describe("Publish", function(){
    it("should call all matching callbacks", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          data = ["data"];

      channel.AddSubscriber(spy);
      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });

    it("should call all matching callbacks with predicates", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          data = ["data"];

      channel.AddSubscriber(spy, window, { predicate: function(data){ return data.length == 4 } });
      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });

    it("should call all matching callbacks with context", function(){
      var spy = jasmine.createSpy("context for callback"),
          data = ["data"];

      channel.AddSubscriber(function() { this(); }, {}, spy );
      channel.Publish(data);

      expect(spy).toHaveBeenCalled();
    });

    it("should call all matching for nested channels", function(){
      var channelName = "test",
          spy = jasmine.createSpy("inner function"),
          data = ["data"];

      channel.AddChannel(channelName);
      channel._channels[channelName].AddSubscriber(spy);

      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });
  });
});
<commit_msg>Channel namespace and setpriority test betterment<commit_after>describe("Channel", function() {
  var mediator;

  beforeEach(function() {
    channel = new Mediator.Channel();
  });

  describe("Initialization", function(){
    it("should set its namespace property", function(){
      expect(channel.namespace).toBe("");
    });
  });

  describe("AddSubscriber", function(){
    it("should add a callback to the collection", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel._callbacks.length).toBe(1);
    });

    it("should give callbacks an id", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel._callbacks[0].id).toBeDefined();
      expect(channel._callbacks[0].id).not.toBe('');
    });

    it("should add a callback to the collection with context", function(){
      var spy = jasmine.createSpy("adding a callback with context"),
          contextObj = { derp: "herp" };

      channel.AddSubscriber(spy, {}, contextObj);
      expect(channel._callbacks[0].context).toBe(contextObj);
    });

    it("should add a callback to the collection with options", function(){
      var spy = jasmine.createSpy("adding a callback with context"),
          contextObj = window,
          optionsObj = { derp: "herp" };

      channel.AddSubscriber(spy, optionsObj, contextObj);
      expect(channel._callbacks[0].options).toBe(optionsObj);
    });

    it("should be able to set top priority", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2, { priority: 0 });
      channel.AddSubscriber(spy3);

      expect(channel._callbacks[0].fn).toBe(spy2);
      expect(channel._callbacks[1].fn).toBe(spy);
      expect(channel._callbacks[2].fn).toBe(spy3);
    });

    it("should be able to set arbitrary priority", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      channel.AddSubscriber(spy3, { priority: 1 });

      expect(channel._callbacks[0].fn).toBe(spy);
      expect(channel._callbacks[1].fn).toBe(spy3);
      expect(channel._callbacks[2].fn).toBe(spy2);
    });

    it("should be able to change priority after adding it", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding another test callback"),
          spy3 = jasmine.createSpy("adding a third test callback");

      var sub = channel.AddSubscriber(spy, { num: 1 });
      channel.AddSubscriber(spy2, { num: 2 });
      channel.AddSubscriber(spy3, { num: 3 });

      channel.SetPriority(sub.id, 2);

      expect(channel._callbacks[0].fn).toBe(spy2);
      expect(channel._callbacks[1].fn).toBe(spy3);
      expect(channel._callbacks[2].fn).toBe(spy);

    });
  });

  describe("GetSubscriber", function(){
    it("should get a callback by its id", function(){
      var spy = jasmine.createSpy("adding a test callback");
      channel.AddSubscriber(spy);

      expect(channel.GetSubscriber(channel._callbacks[0].id)).toBeDefined();
    });
  });

  describe("AddChannel", function(){
    it("should add a channel to the collection", function(){
      var channelName = "test";
      channel.AddChannel(channelName);

      expect(channel._channels[channelName]).toBeDefined();
    });
  });

  describe("HasChannel", function(){
    it("should return true if the channel exists", function(){
      var channelName = "test";
      channel.AddChannel(channelName);

      expect(channel.HasChannel(channelName)).toBe(true);
    });

    it("should return true if the channel does not exist", function(){
      var channelName = "test",
          badChannelName = "herp";

      channel.AddChannel(channelName);

      expect(channel.HasChannel(badChannelName)).toBe(false);
    });
  });

  describe("ReturnChannel", function(){
    it("should return a reference to a channel by name", function(){
      var channelName = "test";

      channel.AddChannel(channelName);

      expect(channel.ReturnChannel(channelName)).toBe(channel._channels[channelName]);
    });
  });

  describe("RemoveSubscriber", function(){
    it("should remove callbacks if no fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback");

      channel.AddSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);

      channel.RemoveSubscriber();
      expect(channel._callbacks.length).toBe(0);
    });

    it("should remove matching callbacks a valid fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding a second test callback");

      channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);
      expect(channel._callbacks[0].fn).toBe(spy2);
    });

    it("should remove matching callbacks a valid id is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          spy2 = jasmine.createSpy("adding a second test callback");

      var sub = channel.AddSubscriber(spy);
      channel.AddSubscriber(spy2);
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(sub.id);
      expect(channel._callbacks.length).toBe(1);
      expect(channel._callbacks[0].fn).toBe(spy2);
    });

    it("should do nothing if an valid fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          invalidFn = "derp";

      channel.AddSubscriber(spy);
      channel.AddSubscriber(function() {});
      expect(channel._callbacks.length).toBe(2);

      channel.RemoveSubscriber(invalidFn);
      expect(channel._callbacks.length).toBe(2);
    });

    it("should do nothing if a non-matching fn is given", function(){
      var spy = jasmine.createSpy("adding a test callback"),
        spy2 = jasmine.createSpy("adding another test callback");

      channel.AddSubscriber(spy);
      expect(channel._callbacks.length).toBe(1);

      channel.RemoveSubscriber(spy2);
      expect(channel._callbacks.length).toBe(1);
    });
  });

  describe("Publish", function(){
    it("should call all matching callbacks", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          data = ["data"];

      channel.AddSubscriber(spy);
      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });

    it("should call all matching callbacks with predicates", function(){
      var spy = jasmine.createSpy("adding a test callback"),
          data = ["data"];

      channel.AddSubscriber(spy, window, { predicate: function(data){ return data.length == 4 } });
      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });

    it("should call all matching callbacks with context", function(){
      var spy = jasmine.createSpy("context for callback"),
          data = ["data"];

      channel.AddSubscriber(function() { this(); }, {}, spy );
      channel.Publish(data);

      expect(spy).toHaveBeenCalled();
    });

    it("should call all matching for nested channels", function(){
      var channelName = "test",
          spy = jasmine.createSpy("inner function"),
          data = ["data"];

      channel.AddChannel(channelName);
      channel._channels[channelName].AddSubscriber(spy);

      channel.Publish(data);

      expect(spy).toHaveBeenCalledWith(data[0]);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * metalsmith-kalastatic-dot-module
*/

'use strict';

var debug = require("debug")("metalsmith-kalastatic-dot-module"),
    request = require("request");

module.exports = function plugin( data ) {

    data = (('object' === typeof data)? data : undefined) || {};

    var stylesURL = data.stylesURL,
        scriptsURL = data.scriptsURL;

    return function through (files, metalsmith, done) {

      function requestResource(url,cb) {
        request(url, function(err,res,bod){
          if( !err && res.statusCode === 200 ) {
            cb(bod);
          } else {
            console.log(err);
            cb(err);
          }
        });
      }

      function asyncDone(){
        if(metadata.kstaticResources.styles && metadata.kstaticResources.scripts) {
          done();
        }
      }

      var metadata = metalsmith.metadata();
      metadata.kstaticResources = {};
      requestResource(stylesURL, function(res){
          metadata.kstaticResources.styles = res;
          asyncDone();
      });
      requestResource(scriptsURL, function(res){
        metadata.kstaticResources.scripts = res;
        asyncDone();
      });

    };
}
<commit_msg>removed libe/index.js and just moved the meat to /index.js<commit_after><|endoftext|>


<commit_before>(function (angular) {
    'use strict';
    var archivoPerfilControllerApp = angular.module('archivoPerfil', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.grid', 'ngTouch', 'ui.grid.edit', 'ui.grid.autoResize', 'ui.grid.selection', 'ui.grid.cellNav', 'xeditable'])
    .controller('archivoPerfilController', ['$scope', '$http', '$window', '$location', '$filter', 'uiGridConstants', 'i18nService', '$scope', function ($scope, $http, $window, $location, $filter, i18nService, uiGridConstants) {
        var init = function () {
            $scope.archivoID = $window.localStorage.getItem("archivoID");
            // DATOS PRINCIPALES
            $scope.cargarDatosPrincipales();
            // ANOTACIONES
            $scope.cargarNotas();
        };

        //Datos principales
        $scope.archivoDatos = {};
        $scope.datosPrincipales = {};
        $scope.datosPrincipales.archivoTitulo = "";
        $scope.datosPrincipales.archivoNombre = "";
        $scope.datosPrincipales.institucionFondo = "";
        $scope.datosPrincipales.seccion = "";
        $scope.datosPrincipales.numRefDentroFondo = "";
        $scope.datosPrincipales.archivoFecha = "";
        $scope.datosPrincipales.folioInicial = "";
        $scope.datosPrincipales.folioFinal = "";
        $scope.datosPrincipales.legajo = "";
        $scope.datosPrincipales.numOrden = "";
        $scope.datosPrincipales.numPaginas = "";
        $scope.datosPrincipales.palabrasClaves = {};
        $scope.datosPrincipales.disponibilidad = "";

        //Bandera para saber cuando guardar o no
        $scope.datosPrincipales.editado = false;

        $scope.cargarDatosPrincipales = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/ConsultaArchivo?archivoID=' + $scope.archivoID).then(function (data) {
                //Obtener los datos JSON
                $scope.archivoDatos = data.data[0];
                //Log
                console.log($scope.archivoDatos);

                //Llenamos los datos del archivo
                $scope.datosPrincipales.archivoTitulo = $scope.archivoDatos.titulo;
                $scope.datosPrincipales.archivoNombre = $scope.archivoDatos.fondo;
                $scope.datosPrincipales.institucionFondo = $scope.archivoDatos.institucionFondo;
                $scope.datosPrincipales.seccion = $scope.archivoDatos.seccion;
                $scope.datosPrincipales.numRefDentroFondo = $scope.archivoDatos.numRefDentroFondo;
                $scope.datosPrincipales.archivoFecha = $filter('date')(new Date($scope.archivoDatos.fechaInicial), String($scope.archivoDatos.fechaInicialFormato).toLowerCase()) + " - " + $filter('date')(new Date($scope.archivoDatos.fechaFinal), String($scope.archivoDatos.fechaFinalFormato).toLowerCase());
                $scope.datosPrincipales.folioInicial = $scope.archivoDatos.folioInicial;
                $scope.datosPrincipales.folioFinal = $scope.archivoDatos.folioFinal;
                $scope.datosPrincipales.legajo = $scope.archivoDatos.legajo;
                $scope.datosPrincipales.numOrden = $scope.archivoDatos.numOrden;
                $scope.datosPrincipales.numPaginas = $scope.archivoDatos.numPaginas;
                $scope.datosPrincipales.palabrasClaves = $scope.archivoDatos.palabrasClaves.split(",");
                $scope.datosPrincipales.palabrasClaves = $scope.datosPrincipales.palabrasClaves.map(function (e) { return e.trim(); });

                $scope.datosPrincipales.disponibilidad = $scope.archivoDatos.disponibilidad;
                //Limpiamos la bandera de editado
                $scope.datosPrincipales.editado = false;

                //Para palabras claves
                $scope.palabraNueva = {mensaje:"+Agregar"};

            });
        };

        // Anotaciones
        $scope.notas = "";
        $scope.notasAgregadas = false;
        $scope.cargarNotas = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/Consulta/ArchivosNotas?archivoID=' + $scope.archivoID).then(function (data) {
                if (String(data).startsWith("[WARNING]")) {
                    $scope.notas = data.data;
                    // LOG
                    console.log($scope.notas);
                }
            });

        };
        $scope.agregarNotaVacia = function () {
            if ($scope.notas === "") {
                $scope.notas = [{
                    nota:"",
                    referencia:"",
                    fechaHistorica:"",
                    fechaHistFormato:""
                }];
            } else {
                $scope.notas.push({
                nota:"",
                referencia:"",
                fechaHistorica:"",
                fechaHistFormato:""
            });
            }
            $scope.notasAgregadas = true;
        }

        // Initialization fucntion
        init();

        // Para borrar palabras claves
        $scope.borrarSiVacio = function (indexEditada, palabra) {
            if (palabra == "") {
                $scope.datosPrincipales.palabrasClaves.splice(indexEditada,1);
            }
        }
        //Para agregar palabras claves
        $scope.palabraNueva = {mensaje: '+Agregar'};

        $scope.borrarCampo = function () {
            $scope.palabraNueva.mensaje = "";
        }
        $scope.mostrarCampo = function () {
            $scope.palabraNueva.mensaje = "+Agregar";
        }
        $scope.agregarPalabraNueva = function (palabra) {
            if (!$scope.datosPrincipales.palabrasClaves.includes(palabra) && palabra.length != 0) {
                $scope.datosPrincipales.palabrasClaves.push(palabra);
            }
            $scope.palabraNueva.mensaje = "+Agregar";
        }

        //Para guardar borrar y barra
        $scope.ultimaAccion = "";
        // Button functions
        $scope.borrarCambios = function () {
            if (window.confirm("Esta Seguro que quiere borrar los cambios?") === true) {
                init();
            }
        };
        $scope.guardarCambios = function () {
            if($scope.notasAgregadas) {
                $scope.notasAgregadas = false;
                $scope.notas.forEach(function (nota) {
                    if (nota.nota.length != 0)
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Modificar/ArchivosNotas?idUnico=archivoID&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                })
            }
            //Revisamos datos principales editados
            if ($scope.datosPrincipales.editado) {

            }
                init();
        };

    }]);
    archivoPerfilControllerApp.run(function (editableOptions,editableThemes) {
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableOptions.theme = 'bs3';
        editableOptions.buttons = 'no';
    });
})(window.angular);

<commit_msg>Agregar Notas<commit_after>(function (angular) {
    'use strict';
    var archivoPerfilControllerApp = angular.module('archivoPerfil', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.grid', 'ngTouch', 'ui.grid.edit', 'ui.grid.autoResize', 'ui.grid.selection', 'ui.grid.cellNav', 'xeditable'])
    .controller('archivoPerfilController', ['$scope', '$http', '$window', '$location', '$filter', 'uiGridConstants', 'i18nService', '$scope', function ($scope, $http, $window, $location, $filter, i18nService, uiGridConstants) {
        var init = function () {
            $scope.archivoID = $window.localStorage.getItem("archivoID");
            // DATOS PRINCIPALES
            $scope.cargarDatosPrincipales();
            // ANOTACIONES
            $scope.cargarNotas();
        };

        //Datos principales
        $scope.archivoDatos = {};
        $scope.datosPrincipales = {};
        $scope.datosPrincipales.archivoTitulo = "";
        $scope.datosPrincipales.archivoNombre = "";
        $scope.datosPrincipales.institucionFondo = "";
        $scope.datosPrincipales.seccion = "";
        $scope.datosPrincipales.numRefDentroFondo = "";
        $scope.datosPrincipales.archivoFecha = "";
        $scope.datosPrincipales.folioInicial = "";
        $scope.datosPrincipales.folioFinal = "";
        $scope.datosPrincipales.legajo = "";
        $scope.datosPrincipales.numOrden = "";
        $scope.datosPrincipales.numPaginas = "";
        $scope.datosPrincipales.palabrasClaves = {};
        $scope.datosPrincipales.disponibilidad = "";

        //Bandera para saber cuando guardar o no
        $scope.datosPrincipales.editado = false;

        $scope.cargarDatosPrincipales = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/ConsultaArchivo?archivoID=' + $scope.archivoID).then(function (data) {
                //Obtener los datos JSON
                $scope.archivoDatos = data.data[0];
                //Log
                console.log($scope.archivoDatos);

                //Llenamos los datos del archivo
                $scope.datosPrincipales.archivoTitulo = $scope.archivoDatos.titulo;
                $scope.datosPrincipales.archivoNombre = $scope.archivoDatos.fondo;
                $scope.datosPrincipales.institucionFondo = $scope.archivoDatos.institucionFondo;
                $scope.datosPrincipales.seccion = $scope.archivoDatos.seccion;
                $scope.datosPrincipales.numRefDentroFondo = $scope.archivoDatos.numRefDentroFondo;
                $scope.datosPrincipales.archivoFecha = $filter('date')(new Date($scope.archivoDatos.fechaInicial), String($scope.archivoDatos.fechaInicialFormato).toLowerCase()) + " - " + $filter('date')(new Date($scope.archivoDatos.fechaFinal), String($scope.archivoDatos.fechaFinalFormato).toLowerCase());
                $scope.datosPrincipales.folioInicial = $scope.archivoDatos.folioInicial;
                $scope.datosPrincipales.folioFinal = $scope.archivoDatos.folioFinal;
                $scope.datosPrincipales.legajo = $scope.archivoDatos.legajo;
                $scope.datosPrincipales.numOrden = $scope.archivoDatos.numOrden;
                $scope.datosPrincipales.numPaginas = $scope.archivoDatos.numPaginas;
                $scope.datosPrincipales.palabrasClaves = $scope.archivoDatos.palabrasClaves.split(",");
                $scope.datosPrincipales.palabrasClaves = $scope.datosPrincipales.palabrasClaves.map(function (e) { return e.trim(); });

                $scope.datosPrincipales.disponibilidad = $scope.archivoDatos.disponibilidad;
                //Limpiamos la bandera de editado
                $scope.datosPrincipales.editado = false;

                //Para palabras claves
                $scope.palabraNueva = {mensaje:"+Agregar"};

            });
        };

        // Anotaciones
        $scope.notas = "";
        $scope.notasAgregadas = false;
        $scope.cargarNotas = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/Consulta/ArchivosNotas?archivoID=' + $scope.archivoID).then(function (data) {
                if (String(data).startsWith("[WARNING]")) {
                    $scope.notas = data.data;
                    // LOG
                    console.log($scope.notas);
                }
            });

        };
        $scope.agregarNotaVacia = function () {
            if ($scope.notas === "") {
                $scope.notas = [{
                    nota:"",
                    referencia:"",
                    fechaHistorica:"",
                    fechaHistFormato:""
                }];
            } else {
                $scope.notas.push({
                nota:"",
                referencia:"",
                fechaHistorica:"",
                fechaHistFormato:""
            });
            }
            $scope.notasAgregadas = true;
        }

        // Initialization fucntion
        init();

        // Para borrar palabras claves
        $scope.borrarSiVacio = function (indexEditada, palabra) {
            if (palabra == "") {
                $scope.datosPrincipales.palabrasClaves.splice(indexEditada,1);
            }
        }
        //Para agregar palabras claves
        $scope.palabraNueva = {mensaje: '+Agregar'};

        $scope.borrarCampo = function () {
            $scope.palabraNueva.mensaje = "";
        }
        $scope.mostrarCampo = function () {
            $scope.palabraNueva.mensaje = "+Agregar";
        }
        $scope.agregarPalabraNueva = function (palabra) {
            if (!$scope.datosPrincipales.palabrasClaves.includes(palabra) && palabra.length != 0) {
                $scope.datosPrincipales.palabrasClaves.push(palabra);
            }
            $scope.palabraNueva.mensaje = "+Agregar";
        }

        //Para guardar borrar y barra
        $scope.ultimaAccion = "";
        // Button functions
        $scope.borrarCambios = function () {
            if (window.confirm("Esta Seguro que quiere borrar los cambios?") === true) {
                init();
            }
        };
        $scope.guardarCambios = function () {
            if($scope.notasAgregadas) {
                $scope.notasAgregadas = false;
                $scope.notas.forEach(function (nota) {
                    if (nota.nota.length != 0)
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Insertar/ArchivosNotas?idUnico=archivoID&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                })
            }
            //Revisamos datos principales editados
            if ($scope.datosPrincipales.editado) {

            }
                init();
        };

    }]);
    archivoPerfilControllerApp.run(function (editableOptions,editableThemes) {
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableOptions.theme = 'bs3';
        editableOptions.buttons = 'no';
    });
})(window.angular);

<|endoftext|>


<commit_before>window.onload = function () {
    // Get container elements
    var containers = [
        document.getElementById('currentCurator'),
        document.getElementById('nextCurator'),
        document.getElementById('followingCurator')
    ];
    var successive = document.getElementById('successiveCurators');
    var alertClose = document.getElementById('alert-close');

    // Get file path, add time-stamp to prevent caching
    var filePath = 'https://scratchtools.tk/fpc/api/v2/json/?u=' + new Date().getTime();

    // Init http request
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.ontimeout = function() {
        console.log('Timeout');
        error();
    };

    xmlHttp.onerror = function() {
        console.log('Error');
        error();
    };

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
            try {
                downloaded(JSON.parse(xmlHttp.responseText));
            } catch(e) {
                if (e instanceof SyntaxError) {
                    error();
                    console.log('Bad JSON syntax');
                } else {
                    throw e;
                }
            }
        }
    };

    xmlHttp.open('GET', filePath, true);
    xmlHttp.timeout = 5000;

    // Send http request
    xmlHttp.send(null);

    // Interpret downloaded data
    function downloaded(result) {
        // Check response was successful
        if (result['response']['code'] === 0) {

            // Load current, next and following curators
            for (var i = 0; i < 3; i++) {

                // Get container parent
                var parent = containers[i].parentElement;

                // Display week range

                var date = document.createElement('span');

                date.className = 'date';
                date.innerHTML =
                        formatDate(new Date(result['curators'][i]['start'])) +
                        ' - ' +
                        formatDate(new Date(result['curators'][i]['end']));

                parent.insertBefore(
                        date,
                        parent.childNodes[0]
                );

                // Load curator

                // Check curator is known

                if (result['curators'][i]['user']) {
                    // Curator is known

                    // Check if FPC is confirmed

                    if (result['curators'][i]['confirmed']) {
                        // FPC was confirmed

                        // Check if FPC has any remaining slots

                        if (!result['curators'][i]['full']) {
                            // FPC has remaining slots

                            containers[i].innerHTML = '@' + result['curators'][i]['user'];
                            containers[i].className = '';

                            parent.className = 'box shadow-box hover';
                            parent.title = '@' + result['curators'][i]['user'];
                            parent.href = result['curators'][i]['suggest_url'];
                        } else {
                            // FPC is full

                            containers[i].innerHTML = '@' + result['curators'][i]['user'] + ' (FULL)';
                            containers[i].className = 'gray';

                            parent.title = 'This FPC is full';
                        }
                    } else {
                        // FPC not confirmed

                        containers[i].innerHTML = '@' + result['curators'][i]['user'] + ' (TBC)';
                        containers[i].className = 'gray';

                        parent.title = 'This FPC has not yet been confirmed';
                    }
                } else {
                    // Curator not known

                    containers[i].innerHTML = 'Unknown';

                    parent.title = 'The FPC during this period is currently unknown';
                }
            }

            // Check if there are successive curators

            if (result['curators'].length > 3) {
                // There are successive curators

                // For each successive curator
                for (var i = 3; i < result['curators'].length; i++) {
                    // Add date
                    successive.innerHTML +=
                            '' +
                            formatDate(new Date(result['curators'][i]['start'])) +
                            ' - ' +
                            formatDate(new Date(result['curators'][i]['end'])) +
                            '';

                    // Check if curator has been suggested
                    if (result['curators'][i]['user']) {
                        // Curator has been suggested

                        // Check if curator is confirmed

                        if (result['curators'][i]['confirmed']) {
                            // Curator is confirmed

                            // Check if curator has any remaining slots

                            if (!result['curators'][i]['full']) {
                                // Curator has remaining slots

                                successive.innerHTML +=
                                        '@' +
                                        result['curators'][i]['user'] + '';
                            } else {
                                // Curator is full

                                successive.innerHTML +=
                                        '@' +
                                        result['curators'][i]['user'] +
                                        ' (FULL)';
                            }
                        } else {
                            // Curator isn't confirmed, so display TBC label
                            // and add no link

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] +
                                    ' (TBC)';
                        }
                    } else {
                        // No known FPC for this period

                        // Display unknown message
                        successive.innerHTML +=
                                'Unknown';
                    }
                }

                // Show container for successive curators
                document.getElementById('successiveContainer').className = 'box shadow-box hover';
            }

            // Show notice
            if (result['message']) {
                document.getElementById('alert-text').innerHTML = result['message'];
                document.getElementById('alert').className = 'box';
            }
        } else {
            error();
            console.log(
                    'Error: code ' +
                    result['response']['code'] +
                    ' - ' +
                    result['response']['description']
            );
        }
    }

    // Display error messages in every container
    function error() {
        // TODO: on error, hide containers and show separate div
        containers[0].innerHTML = 'Error';
        containers[1].innerHTML = 'Error';
        containers[2].innerHTML = 'Error';
    }

    // Makes a date human readable
    // Uses browser language to match users prefrences
    function formatDate(d) {
        return d.toLocaleString(navigator.language, {
            day: 'numeric',
            month: 'short'
        });
    }

    // Add close button click event
    alertClose.onclick = function() {
        document.getElementById('alert').className = 'hidden';
    };
};<commit_msg>Force error message to be given on error	<commit_after>window.onload = function () {
    // Get container elements
    var containers = [
        document.getElementById('currentCurator'),
        document.getElementById('nextCurator'),
        document.getElementById('followingCurator')
    ];
    var successive = document.getElementById('successiveCurators');
    var alertClose = document.getElementById('alert-close');

    // Get file path, add time-stamp to prevent caching
    var filePath = 'https://scratchtools.tk/fpc/api/v2/json/?u=' + new Date().getTime();

    // Init http request
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.ontimeout = function() {
        error('Response timeout (took longer than ' + xmlHttp.timeout + 'ms)');
    };

    xmlHttp.onerror = function() {
        error('Status code error: ' + xmlHttp.status);
    };

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
            try {
                downloaded(JSON.parse(xmlHttp.responseText));
            } catch(e) {
                if (e instanceof SyntaxError) {
                    error('Bad JSON syntax');
                } else {
                    throw e;
                }
            }
        }
    };

    xmlHttp.open('GET', filePath, true);
    xmlHttp.timeout = 5000;

    // Send http request
    xmlHttp.send(null);

    // Interpret downloaded data
    function downloaded(result) {
        // Check response was successful
        if (result['response']['code'] === 0) {

            // Load current, next and following curators
            for (var i = 0; i < 3; i++) {

                // Get container parent
                var parent = containers[i].parentElement;

                // Display week range

                var date = document.createElement('span');

                date.className = 'date';
                date.innerHTML =
                        formatDate(new Date(result['curators'][i]['start'])) +
                        ' - ' +
                        formatDate(new Date(result['curators'][i]['end']));

                parent.insertBefore(
                        date,
                        parent.childNodes[0]
                );

                // Load curator

                // Check curator is known

                if (result['curators'][i]['user']) {
                    // Curator is known

                    // Check if FPC is confirmed

                    if (result['curators'][i]['confirmed']) {
                        // FPC was confirmed

                        // Check if FPC has any remaining slots

                        if (!result['curators'][i]['full']) {
                            // FPC has remaining slots

                            containers[i].innerHTML = '@' + result['curators'][i]['user'];
                            containers[i].className = '';

                            parent.className = 'box shadow-box hover';
                            parent.title = '@' + result['curators'][i]['user'];
                            parent.href = result['curators'][i]['suggest_url'];
                        } else {
                            // FPC is full

                            containers[i].innerHTML = '@' + result['curators'][i]['user'] + ' (FULL)';
                            containers[i].className = 'gray';

                            parent.title = 'This FPC is full';
                        }
                    } else {
                        // FPC not confirmed

                        containers[i].innerHTML = '@' + result['curators'][i]['user'] + ' (TBC)';
                        containers[i].className = 'gray';

                        parent.title = 'This FPC has not yet been confirmed';
                    }
                } else {
                    // Curator not known

                    containers[i].innerHTML = 'Unknown';

                    parent.title = 'The FPC during this period is currently unknown';
                }
            }

            // Check if there are successive curators

            if (result['curators'].length > 3) {
                // There are successive curators

                // For each successive curator
                for (var i = 3; i < result['curators'].length; i++) {
                    // Add date
                    successive.innerHTML +=
                            '' +
                            formatDate(new Date(result['curators'][i]['start'])) +
                            ' - ' +
                            formatDate(new Date(result['curators'][i]['end'])) +
                            '';

                    // Check if curator has been suggested
                    if (result['curators'][i]['user']) {
                        // Curator has been suggested

                        // Check if curator is confirmed

                        if (result['curators'][i]['confirmed']) {
                            // Curator is confirmed

                            // Check if curator has any remaining slots

                            if (!result['curators'][i]['full']) {
                                // Curator has remaining slots

                                successive.innerHTML +=
                                        '@' +
                                        result['curators'][i]['user'] + '';
                            } else {
                                // Curator is full

                                successive.innerHTML +=
                                        '@' +
                                        result['curators'][i]['user'] +
                                        ' (FULL)';
                            }
                        } else {
                            // Curator isn't confirmed, so display TBC label
                            // and add no link

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] +
                                    ' (TBC)';
                        }
                    } else {
                        // No known FPC for this period

                        // Display unknown message
                        successive.innerHTML +=
                                'Unknown';
                    }
                }

                // Show container for successive curators
                document.getElementById('successiveContainer').className = 'box shadow-box hover';
            }

            // Show notice
            if (result['message']) {
                document.getElementById('alert-text').innerHTML = result['message'];
                document.getElementById('alert').className = 'box';
            }
        } else {
            error(
                'Error: code ' +
                result['response']['code'] +
                ' - ' +
                result['response']['description']
            );
        }
    }

    // Display error messages in every container
    function error(message) {
        // TODO: on error, hide containers and show separate div
        containers[0].innerHTML = 'Error';
        containers[1].innerHTML = 'Error';
        containers[2].innerHTML = 'Error';
        console.error(message);
    }

    // Makes a date human readable
    // Uses browser language to match users prefrences
    function formatDate(d) {
        return d.toLocaleString(navigator.language, {
            day: 'numeric',
            month: 'short'
        });
    }

    // Add close button click event
    alertClose.onclick = function() {
        document.getElementById('alert').className = 'hidden';
    };
};<|endoftext|>


<commit_before>var gulp = require("gulp");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var watchify = require("watchify");
var tsify = require("tsify");
var gutil = require("gulp-util");
var sourcemaps = require("gulp-sourcemaps");
var buffer = require("vinyl-buffer");
var watch = require("gulp-watch");

var resourcesGlob = "resources/*"

var watchedBrowserify = watchify(browserify({
    basedir: ".",
    debug: true,
    entries: ["src/main.ts"],
    cache: {},
    packageCache: {},
})
.plugin(tsify)
.transform("babelify", {presets: ["es2015"], sourcemaps: true}));

gulp.task("copy-resources", function () {
    return gulp.src(resourcesGlob)
        .pipe(gulp.dest("build"));
});

gulp.task("watch-resources", function() {
    gulp.watch(resourcesGlob, ["copy-resources"]);
});

function bundle() {
    return watchedBrowserify
        .bundle()
        .pipe(source("bundle.js"))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest("build"));
}

gulp.task("watch-and-compile", function() {
    return bundle();
});

gulp.task("default", ["watch-resources", "watch-and-compile"]);
watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);
<commit_msg>Fix gulp not copying resources initially<commit_after>var gulp = require("gulp");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var watchify = require("watchify");
var tsify = require("tsify");
var gutil = require("gulp-util");
var sourcemaps = require("gulp-sourcemaps");
var buffer = require("vinyl-buffer");
var watch = require("gulp-watch");

var resourcesGlob = "resources/*"

var watchedBrowserify = watchify(browserify({
    basedir: ".",
    debug: true,
    entries: ["src/main.ts"],
    cache: {},
    packageCache: {},
})
.plugin(tsify)
.transform("babelify", {presets: ["es2015"], sourcemaps: true}));

gulp.task("copy-resources", function () {
    return gulp.src(resourcesGlob)
        .pipe(gulp.dest("build"));
});

gulp.task("watch-resources", function() {
    gulp.watch(resourcesGlob, ["copy-resources"]);
});

function bundle() {
    return watchedBrowserify
        .bundle()
        .pipe(source("bundle.js"))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest("build"));
}

gulp.task("compile-and-watch", function() {
    return bundle();
});

gulp.task("default", ["copy-resources", "watch-resources", "compile-and-watch"]);
watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);
<|endoftext|>


<commit_before>// Execute truncate on document load
$(document).ready(function(){
	truncateAll();
});

// Execute truncate on window resize
$( window ).resize(function() {
	truncateAll();
});
<commit_msg>Delete truncate-triggers.js<commit_after><|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>import React from 'react';
import {connect} from "react-redux";
import  SampleAction from './../actions/SampleAction';
import TopLevelScreenComponent from './../components/TopLevelScreenComponent'
import {
    StyleSheet,
    Text,
    View,
    Dimensions,
    Button
} from 'react-native';

let {height, width} = Dimensions.get('window');

class EntryScreen extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            message: 'Welcome to top level component of this app.',
            dispatchMessage: 'Dispatch an action to:',
            passActionDispatchValue: 1,
            failActionDispatchValue: 0,
        };
        this.passDispatchedAction = this.passDispatchedAction.bind(this);
        this.failDispatchedAction = this.failDispatchedAction.bind(this)
    }

    passDispatchedAction() {
        this.props.dispatch(SampleAction(this.state.passActionDispatchValue))
    }

    failDispatchedAction() {
        this.props.dispatch(SampleAction(this.state.failActionDispatchValue))

    }

    componentDidMount() {

    }

    componentWillReceiveProps() {

    }

    render() {

        return (
            <View style={styles.container}>
                <TopLevelScreenComponent
                    passDispatchedAction={this.passDispatchedAction}
                    failDispatchedAction={this.failDispatchedAction}
                    message={this.props.sampleReducer.message}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        width: width,
        height: height,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

function mapStateToProps(state) {
    return ({
            sampleReducer: state.sampleReducer
        }

    )
}

export default connect(mapStateToProps)(EntryScreen);

<commit_msg>update: Dimensions API to '%' :art:<commit_after>import React from 'react';
import {connect} from "react-redux";
import  SampleAction from './../actions/SampleAction';
import TopLevelScreenComponent from './../components/TopLevelScreenComponent'
import {
    StyleSheet,
    View,
} from 'react-native';

class EntryScreen extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            message: 'Welcome to top level component of this app.',
            dispatchMessage: 'Dispatch an action to:',
            passActionDispatchValue: 1,
            failActionDispatchValue: 0,
        };
        this.passDispatchedAction = this.passDispatchedAction.bind(this);
        this.failDispatchedAction = this.failDispatchedAction.bind(this)
    }

    passDispatchedAction() {
        this.props.dispatch(SampleAction(this.state.passActionDispatchValue))
    }

    failDispatchedAction() {
        this.props.dispatch(SampleAction(this.state.failActionDispatchValue))

    }

    componentDidMount() {

    }

    componentWillReceiveProps() {

    }

    render() {

        return (
            <View style={styles.container}>
                <TopLevelScreenComponent
                    passDispatchedAction={this.passDispatchedAction}
                    failDispatchedAction={this.failDispatchedAction}
                    message={this.props.sampleReducer.message}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

function mapStateToProps(state) {
    return ({
            sampleReducer: state.sampleReducer
        }

    )
}

export default connect(mapStateToProps)(EntryScreen);

<|endoftext|>