<commit_before>const Client = require('@bugsnag/core/client')
const Event = require('@bugsnag/core/event')
const runCallbacks = require('@bugsnag/core/lib/callback-runner')

module.exports = {
  name: 'mainEventSync',
  load: client => {
    const onCallbackError = (err, cb) => {
      // errors in callbacks are tolerated but we want to log them out
      client._logger.error('Error occurred in onError callback, continuing anyway…')
      client._logger.error(err)
    }

    const getPayloadInfo = () => {
      return new Promise((resolve, reject) => {
        const event = new Event('BugsnagInternalError', 'Extracting event info from main process for event in renderer')
        event.app = {
          ...event.app,
          releaseStage: client._config.releaseStage,
          version: client._config.appVersion,
          type: client._config.appType
        }
        event.context = event.context || client._context
        event._metadata = { ...event._metadata, ...client._metadata }
        event._user = { ...event._user, ...client._user }
        event.breadcrumbs = client._breadcrumbs.slice()

        // run the event through just the internal onError callbacks
        const callbacks = [].concat(client._cbs.e.filter(e => !!e._internal))
        runCallbacks(callbacks, event, onCallbackError, (err, shouldSend) => {
          if (err) onCallbackError(err)
          if (!shouldSend) return reject(new Error('Event not sent due to onError callback'))

          // extract just the properties we want from the event
          const { app, breadcrumbs, context, device, _metadata, user } = event
          resolve({ app, breadcrumbs, context, device, metadata: _metadata, user })
        })
      })
    }

    const dispatch = (event) => {
      return new Promise((resolve, reject) => {
        const originalSeverity = event.severity

        const callbacks = [].concat(client._cbs.e.filter(e => !e._internal))
        runCallbacks(callbacks, event, onCallbackError, (err, shouldSend) => {
          if (err) onCallbackError(err)

          if (!shouldSend) {
            client._logger.debug('Event not sent due to onError callback')
          }

          if (client._config.enabledBreadcrumbTypes.includes('error')) {
            // only leave a crumb for the error if actually got sent
            Client.prototype.leaveBreadcrumb.call(client, event.errors[0].errorClass, {
              errorClass: event.errors[0].errorClass,
              errorMessage: event.errors[0].errorMessage,
              severity: event.severity
            }, 'error')
          }

          if (originalSeverity !== event.severity) {
            event._handledState.severityReason = { type: 'userCallbackSetSeverity' }
          }

          if (event.unhandled !== event._handledState.unhandled) {
            event._handledState.severityReason.unhandledOverridden = true
            event._handledState.unhandled = event.unhandled
          }

          if (client._session) {
            client._session._track(event)
            event._session = client._session
          }

          client._delivery.sendEvent({
            apiKey: event.apiKey || client._config.apiKey,
            notifier: client._notifier,
            events: [event]
          }, (err) => {
            if (err) return reject(err)
            resolve(event)
          })
        })
      })
    }
    return { getPayloadInfo, dispatch }
  }
}
<commit_msg>refactor(plugin-electron-event-sync): Avoid unnecessary array copy<commit_after>const Client = require('@bugsnag/core/client')
const Event = require('@bugsnag/core/event')
const runCallbacks = require('@bugsnag/core/lib/callback-runner')

module.exports = {
  name: 'mainEventSync',
  load: client => {
    const onCallbackError = (err, cb) => {
      // errors in callbacks are tolerated but we want to log them out
      client._logger.error('Error occurred in onError callback, continuing anyway…')
      client._logger.error(err)
    }

    const getPayloadInfo = () => {
      return new Promise((resolve, reject) => {
        const event = new Event('BugsnagInternalError', 'Extracting event info from main process for event in renderer')
        event.app = {
          ...event.app,
          releaseStage: client._config.releaseStage,
          version: client._config.appVersion,
          type: client._config.appType
        }
        event.context = event.context || client._context
        event._metadata = { ...event._metadata, ...client._metadata }
        event._user = { ...event._user, ...client._user }
        event.breadcrumbs = client._breadcrumbs.slice()

        // run the event through just the internal onError callbacks
        const callbacks = [].concat(client._cbs.e.filter(e => !!e._internal))
        runCallbacks(callbacks, event, onCallbackError, (err, shouldSend) => {
          if (err) onCallbackError(err)
          if (!shouldSend) return reject(new Error('Event not sent due to onError callback'))

          // extract just the properties we want from the event
          const { app, breadcrumbs, context, device, _metadata, user } = event
          resolve({ app, breadcrumbs, context, device, metadata: _metadata, user })
        })
      })
    }

    const dispatch = (event) => {
      return new Promise((resolve, reject) => {
        const originalSeverity = event.severity

        const callbacks = client._cbs.e.filter(e => !e._internal)
        runCallbacks(callbacks, event, onCallbackError, (err, shouldSend) => {
          if (err) onCallbackError(err)

          if (!shouldSend) {
            client._logger.debug('Event not sent due to onError callback')
          }

          if (client._config.enabledBreadcrumbTypes.includes('error')) {
            // only leave a crumb for the error if actually got sent
            Client.prototype.leaveBreadcrumb.call(client, event.errors[0].errorClass, {
              errorClass: event.errors[0].errorClass,
              errorMessage: event.errors[0].errorMessage,
              severity: event.severity
            }, 'error')
          }

          if (originalSeverity !== event.severity) {
            event._handledState.severityReason = { type: 'userCallbackSetSeverity' }
          }

          if (event.unhandled !== event._handledState.unhandled) {
            event._handledState.severityReason.unhandledOverridden = true
            event._handledState.unhandled = event.unhandled
          }

          if (client._session) {
            client._session._track(event)
            event._session = client._session
          }

          client._delivery.sendEvent({
            apiKey: event.apiKey || client._config.apiKey,
            notifier: client._notifier,
            events: [event]
          }, (err) => {
            if (err) return reject(err)
            resolve(event)
          })
        })
      })
    }
    return { getPayloadInfo, dispatch }
  }
}
<|endoftext|>


<commit_before>(function(globals) {
  'use strict';
  console.group('base.js');
  var Helper = (function() {
    return {
      'isDefined': function() {
        var args = [].slice.call(arguments);
        var numArgs = args.length;
        if (numArgs == 1) {
          return typeof arguments[0] !== 'undefined' &&
                  arguments[0] !== null;
        } else if (numArgs == 2 && typeof arguments[1] === 'string') {
          return Helper.isDefined(arguments[0]) &&
                  arguments[1] in arguments[0];
        } else {
          console.error('isDefined: unsupported args: %o', args);
        }
      }
    };
  })();

  var EventBus = (function() {
    var bus = {};
    return {
      'subscribe': function(identifier, handler) {
        if (!Helper.isDefined(bus, identifier)) {
          bus[identifier] = [];
        }
        bus[identifier].push(handler);
      },
      'publish': function(identifier, message) {
        if (!Helper.isDefined(bus, identifier)) {
          console.error('subscribe: invalid identifier `%s`', identifier);
          return;
        }
        for (var i = 0; i < bus[identifier].length; i++) {
          bus[identifier][i](message);
        }
      }
    };
  })();

  var Class = (function() {
    function Class() {};
    Class.extend = function(extendedProperties) {
      var ChildClass = function() { // XXX
        if (this.init) {
          this.init.apply(this, arguments);
        }
      };
      ChildClass.prototype = Object.create(this.prototype); // XXX
      ChildClass.prototype.constructor = ChildClass;
      for (var k in extendedProperties) {
        ChildClass.prototype[k] = extendedProperties[k];
      }
      ChildClass.extend = Class.extend;
      return ChildClass;
    };
    return Class;
  })();

  var Model = Class.extend({
    'init': function(controller) {
      this.mController = controller || this; // logic might be held by delegator
      this.m$dom = null;
      this.m$domParent = null;
      this.mStates = {};
    },
    'defaults': {},
    'template': '
implement me
',
    'render': function() {
      if (globals.Helper.isDefined(this.m$dom)) {
        return; // avoid duplicated rendering
      }
      var $container = this.mController.m$domParent || $('body');
      this.m$dom = $(this.template).appendTo($container); // bone
      this.initDataBindings(); // spirit
      // this.initStates(); // flesh
    },
    'initDataBindings': function() {

    }
  });

  var exported = {
    'Helper': Helper,
    'Class': Class,
    'Model': Model
  };
  for (var k in exported) {
    globals[k] = exported[k];
  }
  console.groupEnd();
})(window);
<commit_msg>introduce uniq id to model instance for registering event<commit_after>(function(globals) {
  'use strict';
  console.group('base.js');
  var Helper = (function() {
    return {
      'isDefined': function() {
        var args = [].slice.call(arguments);
        var numArgs = args.length;
        if (numArgs == 1) {
          return typeof arguments[0] !== 'undefined' &&
                  arguments[0] !== null;
        } else if (numArgs == 2 && typeof arguments[1] === 'string') {
          return Helper.isDefined(arguments[0]) &&
                  arguments[1] in arguments[0];
        } else {
          console.error('isDefined: unsupported args: %o', args);
        }
      }
    };
  })();

  var EventBus = (function() {
    var bus = {};
    return {
      'subscribe': function(identifier, handler) {
        if (!Helper.isDefined(bus, identifier)) {
          bus[identifier] = [];
        }
        bus[identifier].push(handler);
      },
      'publish': function(identifier, message) {
        if (!Helper.isDefined(bus, identifier)) {
          console.error('subscribe: invalid identifier `%s`', identifier);
          return;
        }
        for (var i = 0; i < bus[identifier].length; i++) {
          bus[identifier][i](message);
        }
      }
    };
  })();

  var Class = (function() {
    function Class() {};
    Class.extend = function(extendedProperties) {
      var ChildClass = function() { // XXX
        if (this.init) {
          this.init.apply(this, arguments);
        }
      };
      ChildClass.prototype = Object.create(this.prototype); // XXX
      ChildClass.prototype.constructor = ChildClass;
      for (var k in extendedProperties) {
        ChildClass.prototype[k] = extendedProperties[k];
      }
      ChildClass.extend = Class.extend;
      return ChildClass;
    };
    return Class;
  })();

  var Model = Class.extend({
    'factoryId': 0,
    'init': function(controller) {
      this.mId = ++this.factoryId;
      this.mController = controller || this; // logic might be held by delegator
      this.m$dom = null;
      this.m$domParent = null;
      this.mStates = {};
    },
    'defaults': {},
    'template': '
implement me
',
    'render': function() {
      if (globals.Helper.isDefined(this.m$dom)) {
        return; // avoid duplicated rendering
      }
      var $container = this.mController.m$domParent || $('body');
      this.m$dom = $(this.template).appendTo($container); // bone
      this.initDataBindings(); // spirit
      // this.initStates(); // flesh
    },
    'initDataBindings': function() {

    }
  });

  var exported = {
    'Helper': Helper,
    'Class': Class,
    'Model': Model
  };
  for (var k in exported) {
    globals[k] = exported[k];
  }
  console.groupEnd();
})(window);
<|endoftext|>


<commit_before>var gulp = require("gulp");

require("../gulp-ps-tasks/tasks")(gulp);<commit_msg>Changed gulp-ps-tasks import path<commit_after>var gulp = require("gulp");

require("../tasks")(gulp);<|endoftext|>


<commit_before>var fs = require('fs'),
  request = require('request'),
  async = require('async'),
  secrets = require('./config/secrets'),
  mongoose = require('mongoose'),
  Libraries = require('./models/Library');

var partial = false; //scrape all libraries

//CLI arguments
var opts = {
  city : '',
  state : '',
  zip : ''
}

function usage(){
  var help = 'Usage: node scraper.js [options]\n';
  help = help + 'Options:\n';
  help = help + '  -h --help\n';
  help = help + '  -c --city    Monrovia\n';
  help = help + '  -s --state   California\n';
  help = help + '  -z --zip     91016\n';
  help = help + 'Note: Adds all new libraries to db';
  console.log(help);
  process.exit(1);
}

/**
 * POST request to map url
 *
 */
function scrape(){
  var located = formatLocation();
  var post_data = {
    'action':'MapPageController',
    'method':'remoteSearch',
    'data':
      located,
      'type':'rpc',
      'tid':2,
      'ctx':{
        'csrf':'VmpFPSxNakF4Tmkwd01TMHlNMVF3T1RveE16bzFOUzQxT0RSYSxCcDZHSUU2akU1UkFDdlV2N29ULUJ0LFpUTmhZelkw',
        'vid':'066d00000027Meh',
        'ns':'',
        'ver':29}
  };

  var headers = {
    'User-Agent' : 'GlendoraJS Meetup Group',
    'Referer' : 'http://littlefreelibrary.force.com/mapPage'
  }

  var options = {
    url : 'http://littlefreelibrary.force.com/apexremote',
    method : 'POST',
    headers : headers,
    json : post_data
  }

  request.post(options, function (err, res, body){
      if (err){
        throw new Error('Something bad happened with the POST request:\n' + err);
      } else if (res.statusCode != 200){
        throw new Error('Non-OK status code:' + res.statusCode);
      } else {
        console.log('Found ' + body[0].result.length + ' libraries ...');
        if (body[0].result.length){
          storeLibs(body[0].result);
        } else {
          process.exit(1);
        }
      }
    }
  );
}

var count = 0; //check callback counts
var update_err = []; //failed inserts
var skipped = []; //lib already in db

/**
 * Store scraped libs in db using upsert
 *
 * @results array
 */
function storeLibs(results){

  async.eachSeries(results, function(result){
    result = formatLib(result);
    count++;
    Libraries.update(
      { library_id : result.library_id },
      result,
      { upsert : true },
      function(err, obj){
        count--;
        if (err){
          //don't throw, keep update going
          update_err.push({
            error : err,
            id : result.library_id
          });
        } else if (!obj.upserted){
          skipped.push(result.library_id);
        }
        complete(results.length);
      }
    );
  });
}

function complete(total_libs){
  //all libraries upserted at this point, now log
  if (!count){
    var updated = total_libs - update_err.length - skipped.length;

    console.log(update_err.length + ' libraries with errors.');
    console.log(skipped.length + ' libraries skipped.');
    console.log(updated + ' libraries inserted.');

    process.exit();
  }
}

/**
 * Prepare library fields
 *
 * @lib object
 * TODO normalize data
 */
function formatLib(lib){
  var library = lib.library;
  var libObj = {
    library_id : library.Id,
    name : library.Library_Name__c ? library.Library_Name__c : '',
    story : library.Library_Story__c ? library.Library_Story__c : '',
    charter : library.Official_Charter_Number__c ? parseInt(library.Official_Charter_Number__c) : 0,
    street : library.Street__c ?library.Street__c : '',
    city : library.City__c ? library.City__c : '',
    state : library.State_Province_Region__c ? library.State_Province_Region__c : '',
    zip : library.Postal_Zip_Code__c ? parseInt(library.Postal_Zip_Code__c) : 0,
    country : library.Country__c ? library.Country__c : '',
    coordinates : [
      parseInt(library.Library_Geolocation__c.latitude),
      parseInt(library.Library_Geolocation__c.longitude)
    ],
    email : library.Primary_Steward_s_Email__c ? library.Primary_Steward_s_Email__c : '',
    steward_name : library.Primary_Steward_s_Name__c ? library.Primary_Steward_s_Name__c : '',
    status : true
  };

  var photos = [],
      link = 'http://littlefreelibrary.force.com/servlet/servlet.FileDownload?file=';

  //add all attachments as photos
  var i = 1;
  while (i > 0){
    if (lib['attachment' + i.toString()]){
      photos.push(link + lib['attachment' + i.toString()]);
      i++;
    } else {
      break;
    }
  }

  libObj.photo_url = photos;

  return libObj;
}

/**
 * Format location details in suitable array for POST request
 *
 * zipcode : ['91016','ZipCode',null,null]
 * cityState : ['MonroviaSEPERATECalifornia','CityState',null,null]
 * city : ['BLANKSEPERATECalifornia','CityState',null,null]
 * state : ['MonroviaSEPERATEBLANK','CityState',null,null]
 */
function formatLocation(){
  var located = [];
  if (opts.city || opts.state){
    var cityState = [];
    cityState[0] = opts.city ? opts.city : 'BLANK';
    cityState[1] = 'SEPERATE';
    cityState[2] = opts.state ? opts.state : 'BLANK';

    located[0] = cityState.join('');
    located[1] = 'CityState';
  } else if (opts.zip){
    located[0] = opts.zip;
    located[1] = 'ZipCode';
  }

  if (located.length){
    located[2] = null;
    located[3] = null;
  }
  return located;
}

//Connect to MongoDB
mongoose.connect(secrets.db);
mongoose.connection.on('error', function(){
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

if (process.argv.indexOf('--help') != -1 ||
    process.argv.indexOf('-h') != -1){
  usage();
}

//TODO validate parameter data
// optional params
for (var key in opts){
  if (process.argv.indexOf('--' + key) != -1){
    opts[key] = process.argv[process.argv.indexOf('--' + key) + 1];
    partial = true;
  } else if (process.argv.indexOf('-' + key.charAt(0)) != -1){
    opts[key] = process.argv[process.argv.indexOf('-' + key.charAt(0)) + 1];
    partial = true;
  }
}

//TODO support full scrape
if (partial){
  scrape();
} else{
  console.log('Sorry, full scrape is not supported yet...\n');
  usage();
}

<commit_msg>convert coordinates to float<commit_after>var fs = require('fs'),
  request = require('request'),
  async = require('async'),
  secrets = require('./config/secrets'),
  mongoose = require('mongoose'),
  Libraries = require('./models/Library');

var partial = false; //scrape all libraries

//CLI arguments
var opts = {
  city : '',
  state : '',
  zip : ''
}

function usage(){
  var help = 'Usage: node scraper.js [options]\n';
  help = help + 'Options:\n';
  help = help + '  -h --help\n';
  help = help + '  -c --city    Monrovia\n';
  help = help + '  -s --state   California\n';
  help = help + '  -z --zip     91016\n';
  help = help + 'Note: Adds all new libraries to db';
  console.log(help);
  process.exit(1);
}

/**
 * POST request to map url
 *
 */
function scrape(){
  var located = formatLocation();
  var post_data = {
    'action':'MapPageController',
    'method':'remoteSearch',
    'data':
      located,
      'type':'rpc',
      'tid':2,
      'ctx':{
        'csrf':'VmpFPSxNakF4Tmkwd01TMHlNMVF3T1RveE16bzFOUzQxT0RSYSxCcDZHSUU2akU1UkFDdlV2N29ULUJ0LFpUTmhZelkw',
        'vid':'066d00000027Meh',
        'ns':'',
        'ver':29}
  };

  var headers = {
    'User-Agent' : 'GlendoraJS Meetup Group',
    'Referer' : 'http://littlefreelibrary.force.com/mapPage'
  }

  var options = {
    url : 'http://littlefreelibrary.force.com/apexremote',
    method : 'POST',
    headers : headers,
    json : post_data
  }

  request.post(options, function (err, res, body){
      if (err){
        throw new Error('Something bad happened with the POST request:\n' + err);
      } else if (res.statusCode != 200){
        throw new Error('Non-OK status code:' + res.statusCode);
      } else {
        console.log('Found ' + body[0].result.length + ' libraries ...');
        if (body[0].result.length){
          storeLibs(body[0].result);
        } else {
          process.exit(1);
        }
      }
    }
  );
}

var count = 0; //check callback counts
var update_err = []; //failed inserts
var skipped = []; //lib already in db

/**
 * Store scraped libs in db using upsert
 *
 * @results array
 */
function storeLibs(results){

  async.eachSeries(results, function(result){
    result = formatLib(result);
    count++;
    Libraries.update(
      { library_id : result.library_id },
      result,
      { upsert : true },
      function(err, obj){
        count--;
        if (err){
          //don't throw, keep update going
          update_err.push({
            error : err,
            id : result.library_id
          });
        } else if (!obj.upserted){
          skipped.push(result.library_id);
        }
        complete(results.length);
      }
    );
  });
}

function complete(total_libs){
  //all libraries upserted at this point, now log
  if (!count){
    var updated = total_libs - update_err.length - skipped.length;

    console.log(update_err.length + ' libraries with errors.');
    console.log(skipped.length + ' libraries skipped.');
    console.log(updated + ' libraries inserted.');

    process.exit();
  }
}

/**
 * Prepare library fields
 *
 * @lib object
 * TODO normalize data
 */
function formatLib(lib){
  var library = lib.library;
  var libObj = {
    library_id : library.Id,
    name : library.Library_Name__c ? library.Library_Name__c : '',
    story : library.Library_Story__c ? library.Library_Story__c : '',
    charter : library.Official_Charter_Number__c ? parseInt(library.Official_Charter_Number__c) : 0,
    street : library.Street__c ?library.Street__c : '',
    city : library.City__c ? library.City__c : '',
    state : library.State_Province_Region__c ? library.State_Province_Region__c : '',
    zip : library.Postal_Zip_Code__c ? parseInt(library.Postal_Zip_Code__c) : 0,
    country : library.Country__c ? library.Country__c : '',
    coordinates : [
      parseFloat(library.Library_Geolocation__c.latitude),
      parseFloat(library.Library_Geolocation__c.longitude)
    ],
    email : library.Primary_Steward_s_Email__c ? library.Primary_Steward_s_Email__c : '',
    steward_name : library.Primary_Steward_s_Name__c ? library.Primary_Steward_s_Name__c : '',
    status : true
  };

  var photos = [],
      link = 'http://littlefreelibrary.force.com/servlet/servlet.FileDownload?file=';

  //add all attachments as photos
  var i = 1;
  while (i > 0){
    if (lib['attachment' + i.toString()]){
      photos.push(link + lib['attachment' + i.toString()]);
      i++;
    } else {
      break;
    }
  }

  libObj.photo_url = photos;

  return libObj;
}

/**
 * Format location details in suitable array for POST request
 *
 * zipcode : ['91016','ZipCode',null,null]
 * cityState : ['MonroviaSEPERATECalifornia','CityState',null,null]
 * city : ['BLANKSEPERATECalifornia','CityState',null,null]
 * state : ['MonroviaSEPERATEBLANK','CityState',null,null]
 */
function formatLocation(){
  var located = [];
  if (opts.city || opts.state){
    var cityState = [];
    cityState[0] = opts.city ? opts.city : 'BLANK';
    cityState[1] = 'SEPERATE';
    cityState[2] = opts.state ? opts.state : 'BLANK';

    located[0] = cityState.join('');
    located[1] = 'CityState';
  } else if (opts.zip){
    located[0] = opts.zip;
    located[1] = 'ZipCode';
  }

  if (located.length){
    located[2] = null;
    located[3] = null;
  }
  return located;
}

//Connect to MongoDB
mongoose.connect(secrets.db);
mongoose.connection.on('error', function(){
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

if (process.argv.indexOf('--help') != -1 ||
    process.argv.indexOf('-h') != -1){
  usage();
}

//TODO validate parameter data
// optional params
for (var key in opts){
  if (process.argv.indexOf('--' + key) != -1){
    opts[key] = process.argv[process.argv.indexOf('--' + key) + 1];
    partial = true;
  } else if (process.argv.indexOf('-' + key.charAt(0)) != -1){
    opts[key] = process.argv[process.argv.indexOf('-' + key.charAt(0)) + 1];
    partial = true;
  }
}

//TODO support full scrape
if (partial){
  scrape();
} else{
  console.log('Sorry, full scrape is not supported yet...\n');
  usage();
}

<|endoftext|>


<commit_before>import React, {Component} from 'react'

import GoogleChartComponent from '../GoogleChartComponent'
import Rnd from 'react-resizable-and-movable'
import EditIcon from '../../images/Edit_icon.png'
import DeleteIcon from '../../images/Delete_icon.png'
import {getApiRequest} from '../../Utils'

const style = {
  textAlign: 'center',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
};

export default class Widget extends Component {

  constructor(props) {
    super(props)
    this.widgetIndex = this.props.dashboardIndex + '' + this.props.index
    this.state = {}
  }

  componentWillMount() {
    if (this.props.widgetData) {
      const url = 'http://localhost:8000/squealy-apis/'+this.props.widgetData.api_url
      getApiRequest(url, null, (data)=> this.setState({chartData: data}), ()=>{}, null)
    }
  }
  // Sets the width and height of the widget and rnd component in widget's state
  widgetResizeHandler = (direction, styleSize) => {
    const {dashboardIndex, index} = this.props
    this.props.widgetResizeHandler(dashboardIndex, index, styleSize.width, styleSize.height)

  }

  // Sets the position of the widget in its state
  widgetPositionHandler = (event, uiState) => {
    // Update the position of the widget in the state of dashboard container
    const {dashboardIndex, index} = this.props
    this.props.widgetRepositionHandler(dashboardIndex, index, uiState.position.top, uiState.position.left)
  }

  render() {
    const {chartData} = this.state
    const {
      modalVisibilityEnabler,
      index,
      widgetData,
      deleteWidget,
      widgetDeletionHandler,
      dashboardIndex,
      googleDefined,
    } = this.props
    return(
      (widgetData && googleDefined)?
        <Rnd
          x={widgetData.left}
          y={widgetData.top}
          width={widgetData.width}
          height={widgetData.height}
          onResize={this.widgetResizeHandler}
          onDragStop={this.widgetPositionHandler}
        >

 this.setState({editMode: true})}
            onMouseLeave={() => this.setState({editMode: false})}
          >

              {widgetData.title}

            modalVisibilityEnabler(index)}
                  />
            widgetDeletionHandler(dashboardIndex, index)}
            />

          <GoogleChartComponent config={{
              ...chartData,
              index: this.widgetIndex,
              width: widgetData.width,
              height: widgetData.height,
              chartType: widgetData.chartType,
              chartStyles: widgetData.chartStyles
            }}
          />
        </Rnd>
        :
          null
    )
  }
}
<commit_msg>Fixed height issue in widget<commit_after>import React, {Component} from 'react'

import GoogleChartComponent from '../GoogleChartComponent'
import Rnd from 'react-resizable-and-movable'
import EditIcon from '../../images/Edit_icon.png'
import DeleteIcon from '../../images/Delete_icon.png'
import {getApiRequest} from '../../Utils'

const style = {
  textAlign: 'center',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
};

export default class Widget extends Component {

  constructor(props) {
    super(props)
    this.widgetIndex = this.props.dashboardIndex + '' + this.props.index
    this.state = {
      headerHeight: 50
    }
  }

  componentWillMount() {
    if (this.props.widgetData) {
      const url = 'http://localhost:8000/squealy-apis/'+this.props.widgetData.api_url
      getApiRequest(url, null, (data)=> this.setState({chartData: data}), ()=>{}, null)
    }
  }

  componentDidMount() {
    this.setState({headerHeight: this.refs.header.offsetHeight})
  }

  // Sets the width and height of the widget and rnd component in widget's state
  widgetResizeHandler = (direction, styleSize) => {
    const {dashboardIndex, index} = this.props
    this.props.widgetResizeHandler(dashboardIndex, index, styleSize.width, styleSize.height)

  }

  // Sets the position of the widget in its state
  widgetPositionHandler = (event, uiState) => {
    // Update the position of the widget in the state of dashboard container
    const {dashboardIndex, index} = this.props
    this.props.widgetRepositionHandler(dashboardIndex, index, uiState.position.top, uiState.position.left)
  }

  render() {
    const {chartData} = this.state
    const {
      modalVisibilityEnabler,
      index,
      widgetData,
      deleteWidget,
      widgetDeletionHandler,
      dashboardIndex,
      googleDefined,
    } = this.props
    return(
      (widgetData && googleDefined)?
        <Rnd
          x={widgetData.left}
          y={widgetData.top}
          width={widgetData.width}
          height={widgetData.height}
          onResize={this.widgetResizeHandler}
          onDragStop={this.widgetPositionHandler}
        >

 this.setState({editMode: true})}
            onMouseLeave={() => this.setState({editMode: false})}
          >

              {widgetData.title}

            modalVisibilityEnabler(index)}
                  />
            (dashboardIndex, index)}
            />

          <GoogleChartComponent config={{
              ...chartData,
              index: this.widgetIndex,
              width: widgetData.width,
              height: widgetData.height - this.state.headerHeight,
              chartType: widgetData.chartType,
              chartStyles: widgetData.chartStyles
            }}
          />
        </Rnd>
        :
          null
    )
  }
}
<|endoftext|>


<commit_before>(function(g) {

	var hash = '';
	try {
		hash = g.location.hash;
	} catch(e) {}

	doh.registerUrl('_fake', '../../_fake-doh.html' + hash);

	// Core
	doh.registerUrl('basic-types1', '../../basic-types1.html' + hash);
	doh.registerUrl('nested1', '../../nested1.html' + hash);
	doh.registerUrl('nested2', '../../nested2.html' + hash);
	doh.registerUrl('create-constructor', '../../create-constructor.html' + hash);
	// create with raw constructors/functions
	doh.registerUrl('plain-constructors', '../../required-modules.html' + hash);
	// Non-amd environment limited support
	doh.registerUrl('non-amd', '../../non-amd.html' + hash);

	// wire resolver
	doh.registerUrl('wire-resolver', '../../wire-resolver1.html' + hash);
	doh.registerUrl('wire-factory', '../../wire-factory1.html' + hash);

	// resolver errors
	doh.registerUrl('ref-missing1', '../../ref-missing1.html' + hash);
	doh.registerUrl('ref-missing2', '../../ref-missing2.html' + hash);

	// Facets

	// Base
	doh.registerUrl('init-facet', '../../init.html' + hash);
	doh.registerUrl('destroy-facet', '../../destroy.html' + hash);

	// Factories

	// literal
	doh.registerUrl('literal-factory', '../../literal.html' + hash);

	// wire/dom
	doh.registerUrl('dom-resolver', '../../dom.html' + hash);

	// wire/dom/render
	doh.registerUrl('dom-render', '../../dom-render.html' + hash);

	// wire/aop
	doh.registerUrl('decorate1', '../../wire/aop/decorate1.html' + hash);
	doh.registerUrl('introduce1', '../../wire/aop/introduce1.html' + hash);
	doh.registerUrl('aop-weaving', '../../wire/aop/weave1.html' + hash);

	// wire/sizzle
	doh.registerUrl('sizzle', '../../sizzle.html' + hash);

	// wire/dojo/
	// doh.registerUrl('wire/dojo/pubsub', '../../dojo/pubsub1.html' + hash);

	// Go
	doh.run();

})(this);
<commit_msg>Adding ready facet test to all tests suite<commit_after>(function(g) {

	var hash = '';
	try {
		hash = g.location.hash;
	} catch(e) {}

	doh.registerUrl('_fake', '../../_fake-doh.html' + hash);

	// Core
	doh.registerUrl('basic-types1', '../../basic-types1.html' + hash);
	doh.registerUrl('nested1', '../../nested1.html' + hash);
	doh.registerUrl('nested2', '../../nested2.html' + hash);
	doh.registerUrl('create-constructor', '../../create-constructor.html' + hash);
	// create with raw constructors/functions
	doh.registerUrl('plain-constructors', '../../required-modules.html' + hash);
	// Non-amd environment limited support
	doh.registerUrl('non-amd', '../../non-amd.html' + hash);

	// wire resolver
	doh.registerUrl('wire-resolver', '../../wire-resolver1.html' + hash);
	doh.registerUrl('wire-factory', '../../wire-factory1.html' + hash);

	// resolver errors
	doh.registerUrl('ref-missing1', '../../ref-missing1.html' + hash);
	doh.registerUrl('ref-missing2', '../../ref-missing2.html' + hash);

	// Facets

	// Base
	doh.registerUrl('init-facet', '../../init.html' + hash);
	doh.registerUrl('ready-facet', '../../ready.html' + hash);
	doh.registerUrl('destroy-facet', '../../destroy.html' + hash);

	// Factories

	// literal
	doh.registerUrl('literal-factory', '../../literal.html' + hash);

	// wire/dom
	doh.registerUrl('dom-resolver', '../../dom.html' + hash);

	// wire/dom/render
	doh.registerUrl('dom-render', '../../dom-render.html' + hash);

	// wire/aop
	doh.registerUrl('decorate1', '../../wire/aop/decorate1.html' + hash);
	doh.registerUrl('introduce1', '../../wire/aop/introduce1.html' + hash);
	doh.registerUrl('aop-weaving', '../../wire/aop/weave1.html' + hash);

	// wire/sizzle
	doh.registerUrl('sizzle', '../../sizzle.html' + hash);

	// wire/dojo/
	// doh.registerUrl('wire/dojo/pubsub', '../../dojo/pubsub1.html' + hash);

	// Go
	doh.run();

})(this);
<|endoftext|>


<commit_before>import React              from 'react';
import ReactDOM           from 'react-dom';
import TestUtils          from 'react/lib/ReactTestUtils';
import RadioButton        from './radio_button';
import { CORRECT, INCORRECT, UNGRADED } from "../assessments/universal_input";

describe('radio button', function() {

  var item = {
    id: "1",
    material: "The radio button label"
  };

  var props = {
    item,
    name         : "answer-radio",
    selectAnswer : () => {},
    id           : item.id,
    gradeState   : UNGRADED
  };

  var result;
  var subject;

  beforeEach(function(){
    spyOn(props, "selectAnswer");
    result = TestUtils.renderIntoDocument(<RadioButton {...props} />);
    subject = ReactDOM.findDOMNode(result);
  });

  it('renders the radio button label', function() {
    expect(subject.textContent).toContain(item.material);
  });

  it('renders input attributes', function() {
    expect(subject.innerHTML).toContain('type="radio"');
  });

  it('calls the answerSelected function on click', () => {
    var radio = TestUtils.findRenderedDOMComponentWithTag(result, 'input');
    TestUtils.Simulate.change(radio);

    expect(props.selectAnswer).toHaveBeenCalled();
  });

});
<commit_msg>fix whitespace<commit_after>import React              from 'react';
import ReactDOM           from 'react-dom';
import TestUtils          from 'react/lib/ReactTestUtils';
import RadioButton        from './radio_button';
import { CORRECT, INCORRECT, UNGRADED } from "../assessments/universal_input";

describe('radio button', function() {

  var item = {
    id: "1",
    material: "The radio button label"
  };

  var props = {
    item,
    name         : "answer-radio",
    selectAnswer : () => {},
    id           : item.id,
    gradeState   : UNGRADED
  };

  var result;
  var subject;

  beforeEach(function(){
    spyOn(props, "selectAnswer");

    result = TestUtils.renderIntoDocument(<RadioButton {...props} />);
    subject = ReactDOM.findDOMNode(result);
  });

  it('renders the radio button label', function() {
    expect(subject.textContent).toContain(item.material);
  });

  it('renders input attributes', function() {
    expect(subject.innerHTML).toContain('type="radio"');
  });

  it('calls the answerSelected function on click', () => {
    var radio = TestUtils.findRenderedDOMComponentWithTag(result, 'input');
    TestUtils.Simulate.change(radio);

    expect(props.selectAnswer).toHaveBeenCalled();
  });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var version = process.env.VERSION || require('../../package.json').version;
var content = { '1.0.9': '1.0', '1.1.6': '1.1', '1.2.9': '1.2' };
if (!content[version]) content[version] = '1.3';
fs.writeFileSync(path.resolve(__dirname, '../../examples/versions.json'), JSON.stringify(content));
<commit_msg>update version.js<commit_after>var fs = require('fs');
var path = require('path');
var version = process.env.VERSION || require('../../package.json').version;
var content = { '1.0.9': '1.0', '1.1.6': '1.1', '1.2.9': '1.2', '1.3.7': '1.3' };
if (!content[version]) content[version] = '1.4';
fs.writeFileSync(path.resolve(__dirname, '../../examples/versions.json'), JSON.stringify(content));
<|endoftext|>


<commit_before>'use strict';

var _      = require('lodash');
var d3     = require('d3');
var moment = require('moment');

var api    = require('data/api');
var util   = require('util/data');

/**
 * Return true if all indicators are undefined on this datapoint.
 */
function empty(datapoint) {
	return _(datapoint.indicators)
		.pluck('value')
		.every(function (v) { return !util.defined(v); });
}

/**
 * Return an array with one datapoint per indicator.
 */
function melt(dataset) {
	var o = _(dataset)
		.map(function (d) {
			var base = _.omit(d, 'indicators');

			return _.map(d.indicators, function (indicator) {
				return _.assign({}, base, indicator);
			});
		})
		.flatten()
		.value();

	return o;
}

function seriesObject(d, ind, collection, indicators) {
	return {
		name   : indicators[ind].short_name,
		values : d
	};
}

module.exports = {

	template: require('./management.html'),

	data: function () {
		return {
			region          : null,
			campaign        : null,
			campaigns       : [],
			immunity        : [],
			missedChildren  : [],
			capacity        : [178,228,179,184,180,185,230,226,239],
			polio           : [245,236,192,193,191],
			supply          : [194,219,173,172],
			resources       : [169,233],
			inaccessibility : [],
			microplans      : [],
			cases           : null,
			newCases        : null,
			transitPoints   : {
				showVaccinated : false,
				showInPlace    : false,
				showWithSM     : false,
				vaccinated     : null,
				planned        : null,
				inPlace        : null,
				withSM         : null,
				pctInplace     : [],
				pctWithSM      : []
			}
		};
	},

	computed: {
		campaignName: function () {
			return moment(this.campaign.end, 'YYYY-MM-DD').format('MMM YYYY');
		}
	},

	methods: {
		fetch: function () {
			if (!this.region || !this.campaign) {
				return;
			}

			// Fetch polio cases data for this year to display over the polio cases
			// line chart
			var start = moment(this.campaign.start_date).startOf('year');
			var q     = {
				indicator__in  : 168,
				region__in     : [this.region.id],
				campaign_start : start.format('YYYY-MM-DD'),
				campaign_end   : moment(this.campaign.end_date).format('YYYY-MM-DD')
			};

			var self = this;

			api.datapoints(q)
				.then(function (data) {
					var cases = data.objects.map(function (obj) {
							var datapoint  = _.pick(obj, 'campaign', 'region');
							var indicators = _.indexBy(obj.indicators, 'indicator');

							datapoint.value = indicators['168'].value;

							return datapoint;
						});

					var campaigns = _.indexBy(cases, function (c) {
						return moment(c.campaign.start_date).format('YYYYMMDD');
					});

					if (campaigns.hasOwnProperty(self.campaign.date)) {
						self.newCases = campaigns[self.campaign.date].value;
					} else {
						self.newCases = null;
					}

					self.cases = _.reduce(cases, function (sum, c) {
						return sum + c.value;
					}, 0);
				});

			// Fetch inaccesibility data for this campaign
			var inaccessibility = [442,443,444,445,446,447,448,449,450];

			q = {
				indicator__in  : inaccessibility,
				region__in     : [this.region.id],
				campaign_start : moment(this.campaign.start_date).startOf('month').format('YYYY-MM-DD'),
				campaign_end   : moment(this.campaign.end_date).format('YYYY-MM-DD')
			};

			Promise.all([api.indicators({ id__in: inaccessibility }), api.datapoints(q)])
				.then(function (results) {
					var index      = _.indexBy(results[0].objects, 'id');
					var data       = results[1];
					var objects    = data.objects;
					var indicators = {};

					objects.forEach(function (o) {
						o.indicators.forEach(function (d) {
							indicators[d.indicator] = _.assign({
								name           : index[d.indicator].short_name,
								value          : d3.format('.1f')(d.value * 100),
								hiddenForPrint : d.value === 0,
								datapoints     : [{
									indicator : d.indicator,
									value     : d.value
								}]
							}, _.pick(o, 'campaign', 'region'));
						});
					});

					self.inaccessibility = _(indicators)
						.values()
						.sortBy(function (d) {
							return d.datapoints[0].value;
						})
						.reverse()
						.value();
				});

			// Fetch transit points
			q.indicator__in = [175,176,177,204];
			q.region__in    = [this.region.id];

			api.datapoints(q)
				.then(function (data) {
					if (data.objects.length > 1) {
						console.warn('Multiple campaigns or regions returned, expected one');
					}

					var indicators = data.objects[0].indicators;

					for (var i = indicators.length - 1; i >= 0; i--) {
						var d = indicators[i];

						switch(d.indicator) {
							case '175':
								self.transitPoints.inPlace = d.value;
								break;

							case '176':
								self.transitPoints.withSM = d.value;
								break;

							case '177':
								self.transitPoints.vaccinated     = d.value;
								self.transitPoints.showVaccinated = util.defined(d.value);
								break;

							case '204':
								self.transitPoints.planned = d.value;
								break;

							default:
								break;
						}
					}
					var hasPlanned                 = util.defined(self.transitPoints.planned);
					self.transitPoints.showInPlace = util.defined(self.transitPoints.inPlace) && hasPlanned;
					self.transitPoints.showWithSM  = util.defined(self.transitPoints.withSM) && hasPlanned;

					self.transitPoints.pctInplace = [{
						indicator : 'Transit Points in Place',
						value     : self.transitPoints.inPlace / self.transitPoints.planned
					}];

					self.transitPoints.pctWithSM  = [{
						indicator : 'Transit Points with SM',
						value     : self.transitPoints.withSM / self.transitPoints.inPlace
					}];
				});

			// Fetch the immunity gap data
			q.indicator__in  = [431,432];
			q.campaign_start = moment(this.campaign.start_date)
				.startOf('month')
				.subtract(3, 'years')
				.format('YYYY-MM-DD');

			Promise.all([api.indicators({ id__in : [431,432] }), api.datapoints(q)])
				.then(function (data) {
					var indicators = _.indexBy(data[0].objects, 'id');

					var immunity = _(data[1].objects)
						.reject(empty)
						.thru(melt)
						.forEach(function (d) {
							// Add a property to each datapoint indicating the fiscal quarter
							d.quarter = moment(d.campaign.start_date).format('[Q]Q YYYY');
						})
						.groupBy(function (d) {
							return d.indicator + '-' + d.quarter;
						})
						.map(function (datapoints) {
							var mean = _(datapoints).pluck('value').sum() / datapoints.length;

							var o = _.assign({}, _.omit(datapoints[0], 'value'), {
								'value' : mean
							});

							return o;
						})
						.groupBy('indicator')
						.map(_.curryRight(seriesObject)(indicators))
						.value();

						var stack = d3.layout.stack()
							.offset('zero')
							.values(function (d) { return d.values; })
							.x(function (d) { return d.campaign.start_date; })
							.y(function (d) { return d.value; });

						self.immunity = stack(immunity);
				});

			q.indicator__in = [166,164,167,165];
			q.campaign_start = moment(this.campaign.start_date)
				.startOf('month')
				.subtract(1, 'year')
				.format('YYYY-MM-DD');

			Promise.all([api.indicators({ id__in : [166,164,167,165] }), api.datapoints(q)])
				.then(function (data) {
					var indicators = _.indexBy(data[0].objects, 'id');

					var missedChildren = _(data[1].objects)
						.reject(empty)
						.thru(melt)
						.groupBy('indicator')
						.map(_.curryRight(seriesObject)(indicators))
						.value();

					var stack = d3.layout.stack()
						.offset('zero')
						.values(function (d) { return d.values; })
						.x(function (d) { return d.campaign.start_date; })
						.y(function (d) { return d.value; });

					self.missedChildren = stack(missedChildren);
				});
		},
	},

	watch: {
		'campaign' : 'fetch',
		'region'   : 'fetch'
	}
};
<commit_msg>Don't filter out empty campaigns for Missed Children<commit_after>'use strict';

var _      = require('lodash');
var d3     = require('d3');
var moment = require('moment');

var api    = require('data/api');
var util   = require('util/data');

/**
 * Return true if all indicators are undefined on this datapoint.
 */
function empty(datapoint) {
	return _(datapoint.indicators)
		.pluck('value')
		.every(function (v) { return !util.defined(v); });
}

/**
 * Return an array with one datapoint per indicator.
 */
function melt(dataset) {
	var o = _(dataset)
		.map(function (d) {
			var base = _.omit(d, 'indicators');

			return _.map(d.indicators, function (indicator) {
				return _.assign({}, base, indicator);
			});
		})
		.flatten()
		.value();

	return o;
}

function seriesObject(d, ind, collection, indicators) {
	return {
		name   : indicators[ind].short_name,
		values : d
	};
}

module.exports = {

	template: require('./management.html'),

	data: function () {
		return {
			region          : null,
			campaign        : null,
			campaigns       : [],
			immunity        : [],
			missedChildren  : [],
			capacity        : [178,228,179,184,180,185,230,226,239],
			polio           : [245,236,192,193,191],
			supply          : [194,219,173,172],
			resources       : [169,233],
			inaccessibility : [],
			microplans      : [],
			cases           : null,
			newCases        : null,
			transitPoints   : {
				showVaccinated : false,
				showInPlace    : false,
				showWithSM     : false,
				vaccinated     : null,
				planned        : null,
				inPlace        : null,
				withSM         : null,
				pctInplace     : [],
				pctWithSM      : []
			}
		};
	},

	computed: {
		campaignName: function () {
			return moment(this.campaign.end, 'YYYY-MM-DD').format('MMM YYYY');
		}
	},

	methods: {
		fetch: function () {
			if (!this.region || !this.campaign) {
				return;
			}

			// Fetch polio cases data for this year to display over the polio cases
			// line chart
			var start = moment(this.campaign.start_date).startOf('year');
			var q     = {
				indicator__in  : 168,
				region__in     : [this.region.id],
				campaign_start : start.format('YYYY-MM-DD'),
				campaign_end   : moment(this.campaign.end_date).format('YYYY-MM-DD')
			};

			var self = this;

			api.datapoints(q)
				.then(function (data) {
					var cases = data.objects.map(function (obj) {
							var datapoint  = _.pick(obj, 'campaign', 'region');
							var indicators = _.indexBy(obj.indicators, 'indicator');

							datapoint.value = indicators['168'].value;

							return datapoint;
						});

					var campaigns = _.indexBy(cases, function (c) {
						return moment(c.campaign.start_date).format('YYYYMMDD');
					});

					if (campaigns.hasOwnProperty(self.campaign.date)) {
						self.newCases = campaigns[self.campaign.date].value;
					} else {
						self.newCases = null;
					}

					self.cases = _.reduce(cases, function (sum, c) {
						return sum + c.value;
					}, 0);
				});

			// Fetch inaccesibility data for this campaign
			var inaccessibility = [442,443,444,445,446,447,448,449,450];

			q = {
				indicator__in  : inaccessibility,
				region__in     : [this.region.id],
				campaign_start : moment(this.campaign.start_date).startOf('month').format('YYYY-MM-DD'),
				campaign_end   : moment(this.campaign.end_date).format('YYYY-MM-DD')
			};

			Promise.all([api.indicators({ id__in: inaccessibility }), api.datapoints(q)])
				.then(function (results) {
					var index      = _.indexBy(results[0].objects, 'id');
					var data       = results[1];
					var objects    = data.objects;
					var indicators = {};

					objects.forEach(function (o) {
						o.indicators.forEach(function (d) {
							indicators[d.indicator] = _.assign({
								name           : index[d.indicator].short_name,
								value          : d3.format('.1f')(d.value * 100),
								hiddenForPrint : d.value === 0,
								datapoints     : [{
									indicator : d.indicator,
									value     : d.value
								}]
							}, _.pick(o, 'campaign', 'region'));
						});
					});

					self.inaccessibility = _(indicators)
						.values()
						.sortBy(function (d) {
							return d.datapoints[0].value;
						})
						.reverse()
						.value();
				});

			// Fetch transit points
			q.indicator__in = [175,176,177,204];
			q.region__in    = [this.region.id];

			api.datapoints(q)
				.then(function (data) {
					if (data.objects.length > 1) {
						console.warn('Multiple campaigns or regions returned, expected one');
					}

					var indicators = data.objects[0].indicators;

					for (var i = indicators.length - 1; i >= 0; i--) {
						var d = indicators[i];

						switch(d.indicator) {
							case '175':
								self.transitPoints.inPlace = d.value;
								break;

							case '176':
								self.transitPoints.withSM = d.value;
								break;

							case '177':
								self.transitPoints.vaccinated     = d.value;
								self.transitPoints.showVaccinated = util.defined(d.value);
								break;

							case '204':
								self.transitPoints.planned = d.value;
								break;

							default:
								break;
						}
					}
					var hasPlanned                 = util.defined(self.transitPoints.planned);
					self.transitPoints.showInPlace = util.defined(self.transitPoints.inPlace) && hasPlanned;
					self.transitPoints.showWithSM  = util.defined(self.transitPoints.withSM) && hasPlanned;

					self.transitPoints.pctInplace = [{
						indicator : 'Transit Points in Place',
						value     : self.transitPoints.inPlace / self.transitPoints.planned
					}];

					self.transitPoints.pctWithSM  = [{
						indicator : 'Transit Points with SM',
						value     : self.transitPoints.withSM / self.transitPoints.inPlace
					}];
				});

			// Fetch the immunity gap data
			q.indicator__in  = [431,432];
			q.campaign_start = moment(this.campaign.start_date)
				.startOf('month')
				.subtract(3, 'years')
				.format('YYYY-MM-DD');

			Promise.all([api.indicators({ id__in : [431,432] }), api.datapoints(q)])
				.then(function (data) {
					var indicators = _.indexBy(data[0].objects, 'id');

					var immunity = _(data[1].objects)
						.reject(empty)
						.thru(melt)
						.forEach(function (d) {
							// Add a property to each datapoint indicating the fiscal quarter
							d.quarter = moment(d.campaign.start_date).format('[Q]Q YYYY');
						})
						.groupBy(function (d) {
							return d.indicator + '-' + d.quarter;
						})
						.map(function (datapoints) {
							var mean = _(datapoints).pluck('value').sum() / datapoints.length;

							var o = _.assign({}, _.omit(datapoints[0], 'value'), {
								'value' : mean
							});

							return o;
						})
						.groupBy('indicator')
						.map(_.curryRight(seriesObject)(indicators))
						.value();

						var stack = d3.layout.stack()
							.offset('zero')
							.values(function (d) { return d.values; })
							.x(function (d) { return d.campaign.start_date; })
							.y(function (d) { return d.value; });

						self.immunity = stack(immunity);
				});

			q.indicator__in = [166,164,167,165];
			q.campaign_start = moment(this.campaign.start_date)
				.startOf('month')
				.subtract(1, 'year')
				.format('YYYY-MM-DD');

			Promise.all([api.indicators({ id__in : [166,164,167,165] }), api.datapoints(q)])
				.then(function (data) {
					var indicators = _.indexBy(data[0].objects, 'id');

					var missedChildren = _(data[1].objects)
						.thru(melt)
						.groupBy('indicator')
						.map(_.curryRight(seriesObject)(indicators))
						.value();

					var stack = d3.layout.stack()
						.offset('zero')
						.values(function (d) { return d.values; })
						.x(function (d) { return d.campaign.start_date; })
						.y(function (d) { return d.value; });

					self.missedChildren = stack(missedChildren);
				});
		},
	},

	watch: {
		'campaign' : 'fetch',
		'region'   : 'fetch'
	}
};
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "scm", "Datagrid", "Tree",
        "layout", "settings", "tabManager", "commands", "Divider", "MenuItem",
        "console", "Menu", "preferences.experimental", "c9"
    ];
    main.provides = ["scm.log"];
    return main;

    function main(options, imports, register) {
        var ui = imports.ui;
        var c9 = imports.c9;
        var save = imports.save;
        var Editor = imports.Editor;
        var Tree = imports.Tree;
        var Datagrid = imports.Datagrid;
        var editors = imports.editors;
        var layout = imports.layout;
        var Menu = imports.Menu;
        var Divider = imports.Divider;
        var MenuItem = imports.MenuItem;
        var tabManager = imports.tabManager;
        var settings = imports.settings;
        var cnsl = imports.console;
        var commands = imports.commands;
        var experimental = imports["preferences.experimental"];
        var scm = imports.scm;

        var GitGraph = require("./log/log");

        var basename = require("path").basename;
        var dirname = require("path").dirname;
        var escapeHTML = require("ace/lib/lang").escapeHTML;

        /***** Initialization *****/

        var ENABLED = experimental.addExperiment("git", !c9.hosted, "Panels/Source Control Management")
        if (!ENABLED)
            return register(null, { "scm.log": {} });

        var extensions = [];

        var handle = editors.register("scmlog", "SCM Log Viewer", LogView, extensions);

        handle.on("load", function(){
            // commands.addCommand({
            //     name: "opencoverageview",
            //     // hint: "runs the selected test(s) in the test panel",
            //     // bindKey: { mac: "F6", win: "F6" },
            //     group: "Test",
            //     exec: function(editor, args){
            //         var tab;
            //         if (tabManager.getTabs().some(function(t){
            //             if (t.editorType == "coverageview") {
            //                 tab = t;
            //                 return true;
            //             }
            //         })) {
            //             tabManager.focusTab(tab);
            //         }
            //         else {
            //             cnsl.show();
            //             tabManager.open({
            //                 editorType: "coverageview",
            //                 focus: true,
            //                 pane: cnsl.getPanes()[0]
            //             }, function(){});
            //         }
            //     }
            // }, handle);
        });

        function LogView(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);
            var emit = plugin.getEmitter();

            var datagrid, dropdown, label, tree, detail;

            var arrayCache = [];

            var BGCOLOR = {
                "flat-light": "#f7f7f7",
                "flat-dark": "#3D3D3D",
                "light": "#D3D3D3",
                "light-gray": "#D3D3D3",
                "dark": "#3D3D3D",
                "dark-gray": "#3D3D3D"
            };

            plugin.on("draw", function(e) {
                var container = new ui.bar();
                detail = new ui.bar({
                    width: "25%",
                    class: "scm-statusbar detail-root",
                    visible: false // TODO remember this in state
                });
                var hbox = e.tab.appendChild(new ui.hsplitbox({
                    splitter: true,
                    childNodes: [ container, detail ]
                }));

                detail.$int.innerHTML = "

";
                label = detail.$int.firstChild;
                label.host = { textselect: true };

                drawLog(container.$int);
                drawDetail(detail.$int.lastChild);
            });

            function drawDetail(parentHtml) {
                tree = new Tree({
                    container: parentHtml,
                    scrollMargin: [10, 0],
                    theme: "filetree",
                    enableDragdrop: true,

                    getIconHTML: function(node) {
                        var icon = node.isFolder ? "folder" : "status-icon-" + node.type;
                        // if (node.parent == conflicts)
                        //     icon = "status-icon-conflict";
                        // if (node.status === "loading") icon = "loading";
                        // if (tree.model.twoWay && !node.isFolder)
                        //     icon += " clickable";
                        return ""
                            + (node.type || "") + "";
                    },

                    getCaptionHTML: function(node) {
                        if (node.path) {
                            var path = node.labelPath || node.path;
                            return basename(path)
                                + " - "
                                + dirname(path) + "";
                        }
                        return escapeHTML(node.label || node.name);
                    },

                    getRowIndent: function(node) {
                        return 0; //node.$depth ? node.$depth - 2 : 0;
                    },

                    isLoading: function() {},

                    getEmptyMessage: function(){
                        if (!this.keyword)
                            return this.isLoading()
                                ? "Loading file list. One moment please..."
                                : "No files found.";
                        else
                            return "No files found that match '" + this.keyword + "'";
                    }
                }, plugin);

                tree.container.style.position = "absolute";
                tree.container.style.left = "0";
                tree.container.style.top = "0";
                tree.container.style.right = "0";
                tree.container.style.bottom = "0";
                tree.container.style.height = "";
                tree.renderer.scrollBarV.$minWidth = 10;

                tree.commands.bindKey("Space", function(e) {
                    if (tabManager.previewTab)
                        tabManager.preview({ cancel: true });
                    else
                        openSelection({ preview: true });
                });

                tree.commands.bindKey("Enter", function(e) {
                    openSelection();
                });

                tree.commands.bindKey("Shift-Enter", function(e) {
                    openSelectedFiles();
                });

                tree.commands.bindKey("Left", function(e) {
                    datagrid.focus();
                });
                tree.commands.bindKey("Tab", function(e) {
                    datagrid.focus();
                });

                layout.on("eachTheme", function(e){
                    var height = parseInt(ui.getStyleRule(".filetree .tree-row", "height"), 10) || 22;
                    tree.rowHeightInner = height;
                    tree.rowHeight = height + 1;
                    if (e.changed)
                        tree.resize();
                }, plugin);

                tree.on("afterChoose", function(e) {
                    openSelection();
                });

                tree.on("userSelect", function(e) {
                    if (tabManager.previewTab)
                        openSelection({ preview: true });
                });

                tree.on("drop", function(e) {
                    if (e.target && e.selectedNodes) {
                        var nodes = e.selectedNodes;
                        if (e.target == staged) {
                            scm.addFileToStaging(nodes);
                        } else if (e.target == changed) {
                            scm.unstage(nodes);
                        }
                    }
                });

                tree.on("click", function(e) {
                    if (e.domEvent.target.classList.contains("status-icon")) {
                        var node = e.getNode();
                        if (node.parent == staged) {
                            scm.unstage(node);
                        } else if (node.parent == changed || node.parent == ignored) {
                            scm.addFileToStaging(node);
                        } else if (node.parent == conflicts) {
                            scm.addFileToStaging(node);
                        }
                    }
                });

                tree.setRoot(arrayCache);

                // tree.on("focus", function(){
                //     test.focussedPanel = plugin;
                // });

                // settings.on("read", function(){
                //     test.settingsMenu.append(new MenuItem({
                //         caption: "Collapse Passed and Skipped Groups",
                //         checked: "user/test/@collapsegroups",
                //         type: "check",
                //         position: 300
                //     }));
                // }, plugin);

                // settings.on("user/test/@collapsegroups", function(value){
                //     if (plugin.visible) {
                //         skipNode.isOpen = !value;
                //         passNode.isOpen = !value;
                //         tree.refresh();
                //     }
                // }, plugin);

                scm.on("reload", function(options){
                    reload(options || { hash: 0, force: true }, function(e, status) {

                    });
                }, plugin);

                scm.on("resize", function(){
                    tree && tree.resize();
                });

                plugin.on("select", function(options){
                    if (options && detail.visible)
                        reload(options, function(){});
                }, plugin);

                // Context Menu
                // menuContext = new Menu({ items: [
                //     new MenuItem({ match: "file", class: "strong", caption: "Open Diff", onclick: openSelection }, plugin),
                //     new MenuItem({ match: "file", caption: "Open", onclick: openSelectedFiles }, plugin),
                //     new MenuItem({ match: "file", caption: "Reveal in File Tree", onclick: reveal }, plugin),
                // ]});
                // opts.aml.setAttribute("contextmenu", menuContext.aml);

                reload({ hash: 0, force: true }, function(){});
            }

            function drawLog(parentHtml) {
                datagrid = new Datagrid({
                    container: parentHtml,
                    scrollMargin: [10, 0],
                    theme: "blackdg",

                    columns : [
                        {
                            caption: "Date",
                            width: "100",
                            getText: function(node){
                                return "Today";
                            }
                        },
                        {
                            caption: "User",
                            value: "test",
                            width: "100"
                        },
                        {
                            caption: "Commit Message",
                            value: "label",
                            width: "100%",
                            type: "tree"
                        },
                    ],

                    isLoading: function() {},

                    getEmptyMessage: function(){
                        return "Loading log...";
                    }
                }, plugin);

                datagrid.container.style.position = "absolute";
                datagrid.container.style.left = "0";
                datagrid.container.style.top = "0";
                datagrid.container.style.right = "0px";
                datagrid.container.style.bottom = "0";
                datagrid.container.style.height = "";

                datagrid.renderer.scrollBarV.$minWidth = 10;

                // Enable Git Graph
                new GitGraph().attachToTree(datagrid.acetree);

                // datagrid.tooltip = new Tooltip(tree);
                // logdatagrid.tooltip = new Tooltip(logTree);

                layout.on("eachTheme", function(e){
                    var height = parseInt(ui.getStyleRule(".filetree .tree-row", "height"), 10) || 20;
                    datagrid.rowHeightInner = height;
                    datagrid.rowHeight = height;
                    if (e.changed)
                        datagrid.resize();
                }, plugin);

                datagrid.commands.bindKey("Space", function(e) {
                    // TODO show diff of entire commit
                });

                datagrid.commands.bindKey("Enter", function(e) {
                    // Toggle detail
                    if (detail.visible) detail.hide();
                    else {
                        detail.show();
                        datagrid.select(datagrid.selectedNodes); // Todo async callback and then show
                    }
                });

                var switchToTree = function(e) {
                    tree.focus();
                    if (!tree.selectedNode)
                        tree.select(tree.root[0]);
                };
                datagrid.commands.bindKey("Right", switchToTree);
                datagrid.commands.bindKey("Tab", switchToTree);

                datagrid.on("userSelect", function(e) {
                    var options = {};
                    var nodes = datagrid.selectedNodes;

                    if (!nodes[0])
                        return;

                    options.hash = nodes[0].hash;
                    if (nodes[0].parents)
                        options.base = nodes[0].parents.match(/\S*/)[0] || "4b825dc6";

                    if (nodes[1])
                        options.base = nodes[1].hash;

                    if (!nodes[1] && !options.hash)
                        options.twoWay = true;

                    if (!nodes[1]) {
                        options.commit = nodes[0];
                    }

                    emit("select", options);
                });

                // datagrid.setRoot(rootNode = new Node({
                //     label: "root",
                //     tree: tree
                // }));

                // datagrid.on("focus", function(){
                //     scm.focussedPanel = plugin;
                // });

                // settings.on("read", function(){
                //     scm.settingsMenu.append(new MenuItem({
                //         caption: "Collapse Passed and Skipped Groups",
                //         checked: "user/test/@collapsegroups",
                //         type: "check",
                //         position: 300
                //     }));
                // }, plugin);

                // settings.on("user/test/@collapsegroups", function(value){
                //     if (plugin.visible) {
                //         skipNode.isOpen = !value;
                //         passNode.isOpen = !value;
                //         datagrid.refresh();
                //     }
                // }, plugin);

                scm.on("log", function(node){
                    datagrid.model.loadData(node);
                }, plugin);

                    // scm.on("resize", function(){
                    //     tree && datagrid.resize();
                    // });

                // new Datagrid({
                //     container: container.$int,

                //     columns : [
                //         {
                //             caption: "Hierarchy",
                //             value: "label",
                //             width: "60%",
                //             type: "tree"
                //         },
                //         {
                //             caption: "Covered (%)",
                //             width: "20%",
                //             getText: function(node){
                //                 return node.covered + "%";
                //             }
                //         },
                //         {
                //             caption: "Not Covered",
                //             value: "uncovered",
                //             width: "20%"
                //         }
                //     ]
                // }, plugin);

                // e.htmlNode.style.padding = 0;
            }

            /***** Method *****/

            function reload(options, cb) {
                if (!options) options = { hash: 0 };
                if (!tree.meta.options) tree.meta.options = {};
                if (!options.force)
                if (tree.meta.options.hash == options.hash
                  && tree.meta.options.base == options.base)
                    return;

                scm.getStatus(options, function(e, status) {
                    if (options.commit) {
                        label.innerHTML =  "" + escapeHTML(options.hash) + " "
                            + "" + escapeHTML(options.commit.authorname) + ""
                            + "
" + escapeHTML(options.commit.label) + "
";
                    } else {
                        label.innerHTML =  "" + escapeHTML(options.hash) + ""
                            + " ... "
                            + "" + escapeHTML(options.base) + " ";
                    }
                    label.style.display = "block";

                    tree.setRoot(status.history);
                    tree.select(null);
                    tree.meta.options = options;
                });
            }

            /***** Lifecycle *****/

            plugin.on("documentLoad", function(e) {
                var doc = e.doc;

                function setTheme(e) {
                    var tab = doc.tab;
                    var isDark = e.theme == "dark";

                    tab.backgroundColor = BGCOLOR[e.theme];

                    if (isDark) tab.classList.add("dark");
                    else tab.classList.remove("dark");
                }

                layout.on("themeChange", setTheme, doc);
                setTheme({ theme: settings.get("user/general/@skin") });

                doc.title = "Version Log";
            });

            plugin.on("documentActivate", function(e) {

            });

            plugin.on("resize", function(e) {
                datagrid && datagrid.resize();
            });

            /***** Register and define API *****/

            plugin.freezePublicAPI({});

            plugin.load(null, "scmlog");

            return plugin;
        }

        register(null, {
            "scm.log": handle
        });
    }
});
<commit_msg>Make the log viewer work again.<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "scm", "Datagrid", "Tree",
        "layout", "settings", "tabManager", "commands", "Divider", "MenuItem",
        "console", "Menu", "preferences.experimental", "c9"
    ];
    main.provides = ["scm.log"];
    return main;

    function main(options, imports, register) {
        var ui = imports.ui;
        var c9 = imports.c9;
        var save = imports.save;
        var Editor = imports.Editor;
        var Tree = imports.Tree;
        var Datagrid = imports.Datagrid;
        var editors = imports.editors;
        var layout = imports.layout;
        var Menu = imports.Menu;
        var Divider = imports.Divider;
        var MenuItem = imports.MenuItem;
        var tabManager = imports.tabManager;
        var settings = imports.settings;
        var cnsl = imports.console;
        var commands = imports.commands;
        var experimental = imports["preferences.experimental"];
        var scmProvider = imports.scm;

        var GitGraph = require("./log/log");

        var basename = require("path").basename;
        var dirname = require("path").dirname;
        var escapeHTML = require("ace/lib/lang").escapeHTML;

        /***** Initialization *****/

        var ENABLED = experimental.addExperiment("git", !c9.hosted, "Panels/Source Control Management")
        if (!ENABLED)
            return register(null, { "scm.log": {} });

        var extensions = [];
        var scm;

        var handle = editors.register("scmlog", "SCM Log Viewer", LogView, extensions);

        handle.on("load", function(){
            // commands.addCommand({
            //     name: "opencoverageview",
            //     // hint: "runs the selected test(s) in the test panel",
            //     // bindKey: { mac: "F6", win: "F6" },
            //     group: "Test",
            //     exec: function(editor, args){
            //         var tab;
            //         if (tabManager.getTabs().some(function(t){
            //             if (t.editorType == "coverageview") {
            //                 tab = t;
            //                 return true;
            //             }
            //         })) {
            //             tabManager.focusTab(tab);
            //         }
            //         else {
            //             cnsl.show();
            //             tabManager.open({
            //                 editorType: "coverageview",
            //                 focus: true,
            //                 pane: cnsl.getPanes()[0]
            //             }, function(){});
            //         }
            //     }
            // }, handle);

            scmProvider.on("scm", function(implementation){
                scm = implementation;
            });
        });

        function LogView(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);
            var emit = plugin.getEmitter();

            var datagrid, dropdown, label, tree, detail;

            var arrayCache = [];

            var BGCOLOR = {
                "flat-light": "#f7f7f7",
                "flat-dark": "#3D3D3D",
                "light": "#D3D3D3",
                "light-gray": "#D3D3D3",
                "dark": "#3D3D3D",
                "dark-gray": "#3D3D3D"
            };

            scm.on("log", function(node){
                datagrid.model.loadData(node);
            }, plugin);

            plugin.on("draw", function(e) {
                var container = new ui.bar();
                detail = new ui.bar({
                    width: "25%",
                    class: "scm-statusbar detail-root",
                    visible: false // TODO remember this in state
                });
                var hbox = e.tab.appendChild(new ui.hsplitbox({
                    splitter: true,
                    childNodes: [ container, detail ]
                }));

                detail.$int.innerHTML = "

";
                label = detail.$int.firstChild;
                label.host = { textselect: true };

                drawLog(container.$int);
                drawDetail(detail.$int.lastChild);

                // TODO move to a better place
                scm.getLog({}, function(err, root) {
                    if (err) return console.error(err);
                });
            });

            function drawDetail(parentHtml) {
                tree = new Tree({
                    container: parentHtml,
                    scrollMargin: [10, 0],
                    theme: "filetree",
                    enableDragdrop: true,

                    getIconHTML: function(node) {
                        var icon = node.isFolder ? "folder" : "status-icon-" + node.type;
                        // if (node.parent == conflicts)
                        //     icon = "status-icon-conflict";
                        // if (node.status === "loading") icon = "loading";
                        // if (tree.model.twoWay && !node.isFolder)
                        //     icon += " clickable";
                        return ""
                            + (node.type || "") + "";
                    },

                    getCaptionHTML: function(node) {
                        if (node.path) {
                            var path = node.labelPath || node.path;
                            return basename(path)
                                + " - "
                                + dirname(path) + "";
                        }
                        return escapeHTML(node.label || node.name);
                    },

                    getRowIndent: function(node) {
                        return 0; //node.$depth ? node.$depth - 2 : 0;
                    },

                    isLoading: function() {},

                    getEmptyMessage: function(){
                        if (!this.keyword)
                            return this.isLoading()
                                ? "Loading file list. One moment please..."
                                : "No files found.";
                        else
                            return "No files found that match '" + this.keyword + "'";
                    }
                }, plugin);

                tree.container.style.position = "absolute";
                tree.container.style.left = "0";
                tree.container.style.top = "0";
                tree.container.style.right = "0";
                tree.container.style.bottom = "0";
                tree.container.style.height = "";
                tree.renderer.scrollBarV.$minWidth = 10;

                tree.commands.bindKey("Space", function(e) {
                    if (tabManager.previewTab)
                        tabManager.preview({ cancel: true });
                    else
                        openSelection({ preview: true });
                });

                tree.commands.bindKey("Enter", function(e) {
                    openSelection();
                });

                tree.commands.bindKey("Shift-Enter", function(e) {
                    openSelectedFiles();
                });

                tree.commands.bindKey("Left", function(e) {
                    datagrid.focus();
                });
                tree.commands.bindKey("Tab", function(e) {
                    datagrid.focus();
                });

                layout.on("eachTheme", function(e){
                    var height = parseInt(ui.getStyleRule(".filetree .tree-row", "height"), 10) || 22;
                    tree.rowHeightInner = height;
                    tree.rowHeight = height + 1;
                    if (e.changed)
                        tree.resize();
                }, plugin);

                tree.on("afterChoose", function(e) {
                    openSelection();
                });

                tree.on("userSelect", function(e) {
                    if (tabManager.previewTab)
                        openSelection({ preview: true });
                });

                tree.on("drop", function(e) {
                    if (e.target && e.selectedNodes) {
                        var nodes = e.selectedNodes;
                        if (e.target == staged) {
                            scm.addFileToStaging(nodes);
                        } else if (e.target == changed) {
                            scm.unstage(nodes);
                        }
                    }
                });

                tree.on("click", function(e) {
                    if (e.domEvent.target.classList.contains("status-icon")) {
                        var node = e.getNode();
                        if (node.parent == staged) {
                            scm.unstage(node);
                        } else if (node.parent == changed || node.parent == ignored) {
                            scm.addFileToStaging(node);
                        } else if (node.parent == conflicts) {
                            scm.addFileToStaging(node);
                        }
                    }
                });

                tree.setRoot(arrayCache);

                // tree.on("focus", function(){
                //     test.focussedPanel = plugin;
                // });

                // settings.on("read", function(){
                //     test.settingsMenu.append(new MenuItem({
                //         caption: "Collapse Passed and Skipped Groups",
                //         checked: "user/test/@collapsegroups",
                //         type: "check",
                //         position: 300
                //     }));
                // }, plugin);

                // settings.on("user/test/@collapsegroups", function(value){
                //     if (plugin.visible) {
                //         skipNode.isOpen = !value;
                //         passNode.isOpen = !value;
                //         tree.refresh();
                //     }
                // }, plugin);

                plugin.on("select", function(options){
                    if (options && detail.visible)
                        reload(options, function(){});
                }, plugin);

                // Context Menu
                // menuContext = new Menu({ items: [
                //     new MenuItem({ match: "file", class: "strong", caption: "Open Diff", onclick: openSelection }, plugin),
                //     new MenuItem({ match: "file", caption: "Open", onclick: openSelectedFiles }, plugin),
                //     new MenuItem({ match: "file", caption: "Reveal in File Tree", onclick: reveal }, plugin),
                // ]});
                // opts.aml.setAttribute("contextmenu", menuContext.aml);

                reload({ hash: 0, force: true }, function(){});
            }

            function drawLog(parentHtml) {
                datagrid = new Datagrid({
                    container: parentHtml,
                    scrollMargin: [10, 0],
                    theme: "blackdg",

                    columns : [
                        {
                            caption: "Date",
                            width: "100",
                            getText: function(node){
                                return "Today";
                            }
                        },
                        {
                            caption: "User",
                            value: "test",
                            width: "100"
                        },
                        {
                            caption: "Commit Message",
                            value: "label",
                            width: "100%",
                            type: "tree"
                        },
                    ],

                    isLoading: function() {},

                    getEmptyMessage: function(){
                        return "Loading log...";
                    }
                }, plugin);

                datagrid.container.style.position = "absolute";
                datagrid.container.style.left = "0";
                datagrid.container.style.top = "0";
                datagrid.container.style.right = "0px";
                datagrid.container.style.bottom = "0";
                datagrid.container.style.height = "";

                datagrid.renderer.scrollBarV.$minWidth = 10;

                // Enable Git Graph
                new GitGraph().attachToTree(datagrid.acetree);

                // datagrid.tooltip = new Tooltip(tree);
                // logdatagrid.tooltip = new Tooltip(logTree);

                layout.on("eachTheme", function(e){
                    var height = parseInt(ui.getStyleRule(".filetree .tree-row", "height"), 10) || 20;
                    datagrid.rowHeightInner = height;
                    datagrid.rowHeight = height;
                    if (e.changed)
                        datagrid.resize();
                }, plugin);

                datagrid.commands.bindKey("Space", function(e) {
                    // TODO show diff of entire commit
                });

                datagrid.commands.bindKey("Enter", function(e) {
                    // Toggle detail
                    if (detail.visible) detail.hide();
                    else {
                        detail.show();
                        datagrid.select(datagrid.selectedNodes); // Todo async callback and then show
                    }
                });

                var switchToTree = function(e) {
                    tree.focus();
                    if (!tree.selectedNode)
                        tree.select(tree.root[0]);
                };
                datagrid.commands.bindKey("Right", switchToTree);
                datagrid.commands.bindKey("Tab", switchToTree);

                datagrid.on("userSelect", function(e) {
                    var options = {};
                    var nodes = datagrid.selectedNodes;

                    if (!nodes[0])
                        return;

                    options.hash = nodes[0].hash;
                    if (nodes[0].parents)
                        options.base = nodes[0].parents.match(/\S*/)[0] || "4b825dc6";

                    if (nodes[1])
                        options.base = nodes[1].hash;

                    if (!nodes[1] && !options.hash)
                        options.twoWay = true;

                    if (!nodes[1]) {
                        options.commit = nodes[0];
                    }

                    emit("select", options);
                });

                // datagrid.setRoot(rootNode = new Node({
                //     label: "root",
                //     tree: tree
                // }));

                // datagrid.on("focus", function(){
                //     scm.focussedPanel = plugin;
                // });

                // settings.on("read", function(){
                //     scm.settingsMenu.append(new MenuItem({
                //         caption: "Collapse Passed and Skipped Groups",
                //         checked: "user/test/@collapsegroups",
                //         type: "check",
                //         position: 300
                //     }));
                // }, plugin);

                // settings.on("user/test/@collapsegroups", function(value){
                //     if (plugin.visible) {
                //         skipNode.isOpen = !value;
                //         passNode.isOpen = !value;
                //         datagrid.refresh();
                //     }
                // }, plugin);

                    // scm.on("resize", function(){
                    //     tree && datagrid.resize();
                    // });

                // new Datagrid({
                //     container: container.$int,

                //     columns : [
                //         {
                //             caption: "Hierarchy",
                //             value: "label",
                //             width: "60%",
                //             type: "tree"
                //         },
                //         {
                //             caption: "Covered (%)",
                //             width: "20%",
                //             getText: function(node){
                //                 return node.covered + "%";
                //             }
                //         },
                //         {
                //             caption: "Not Covered",
                //             value: "uncovered",
                //             width: "20%"
                //         }
                //     ]
                // }, plugin);

                // e.htmlNode.style.padding = 0;
            }

            /***** Method *****/

            function reload(options, cb) {
                if (!options) options = { hash: 0 };
                if (!tree.meta.options) tree.meta.options = {};
                if (!options.force)
                if (tree.meta.options.hash == options.hash
                  && tree.meta.options.base == options.base)
                    return;

                scm.getStatus(options, function(e, status) {
                    if (options.commit) {
                        label.innerHTML =  "" + escapeHTML(options.hash) + " "
                            + "" + escapeHTML(options.commit.authorname) + ""
                            + "
" + escapeHTML(options.commit.label) + "
";
                    } else {
                        label.innerHTML =  "" + escapeHTML(options.hash) + ""
                            + " ... "
                            + "" + escapeHTML(options.base) + " ";
                    }
                    label.style.display = "block";

                    tree.setRoot(status.history);
                    tree.select(null);
                    tree.meta.options = options;
                });
            }

            /***** Lifecycle *****/

            plugin.on("documentLoad", function(e) {
                var doc = e.doc;

                function setTheme(e) {
                    var tab = doc.tab;
                    var isDark = e.theme == "dark";

                    tab.backgroundColor = BGCOLOR[e.theme];

                    if (isDark) tab.classList.add("dark");
                    else tab.classList.remove("dark");
                }

                layout.on("themeChange", setTheme, doc);
                setTheme({ theme: settings.get("user/general/@skin") });

                doc.title = "Version Log";
            });

            plugin.on("documentActivate", function(e) {

            });

            plugin.on("resize", function(e) {
                datagrid && datagrid.resize();
            });

            /***** Register and define API *****/

            plugin.freezePublicAPI({});

            plugin.load(null, "scmlog");

            return plugin;
        }

        register(null, {
            "scm.log": handle
        });
    }
});
<|endoftext|>


<commit_before>var express = require('express');
var DataStore = require('./regard-data-store.js');

var router = express.Router();
var dataStore = new DataStore('Adobe', 'Brackets');

router.get('/chartdata/:id?', function (req, res, next) {
  var id = req.params.id || req.query.ids[0];

  dataStore.runQuery(id).then(function (result) {
    res.json(JSON.parse(result).Results);
  }, next);
});

function isJSON(jsonString) {
  try {
    var o = JSON.parse(jsonString);

    if (o && typeof o === "object" && o !== null) {
      return true;
    }
  } catch (e) {}
  return false;
}

router.put('/investigations/:id', function (req, res, next) {
  var queryName = req.params.id;
  var queryDefinition = req.body.investigation.queryDefinition;

  if (!queryDefinition) {
    res.send(400, 'missing query definition');
  }

  if (!isJSON(queryDefinition)) {
    res.send(400, 'query definition is not valid JSON');
  }

  dataStore.registerQuery(queryName, queryDefinition).done(function (response) {
    console.dir("register query: " + response);
    next();
  }, next);
});

module.exports = router;<commit_msg>Not using query ids anymore<commit_after>var express = require('express');
var DataStore = require('./regard-data-store.js');

var router = express.Router();
var dataStore = new DataStore('Adobe', 'Brackets');

router.get('/chartdata/:id', function (req, res, next) {
  var id = req.params.id;

  dataStore.runQuery(id).then(function (result) {
    res.json(JSON.parse(result).Results);
  }, next);
});

function isJSON(jsonString) {
  try {
    var o = JSON.parse(jsonString);

    if (o && typeof o === "object" && o !== null) {
      return true;
    }
  } catch (e) {}
  return false;
}

router.put('/investigations/:id', function (req, res, next) {
  var queryName = req.params.id;
  var queryDefinition = req.body.investigation.queryDefinition;

  if (!queryDefinition) {
    res.send(400, 'missing query definition');
  }

  if (!isJSON(queryDefinition)) {
    res.send(400, 'query definition is not valid JSON');
  }

  dataStore.registerQuery(queryName, queryDefinition).done(function (response) {
    console.dir("register query: " + response);
    next();
  }, next);
});

module.exports = router;<|endoftext|>


<commit_before>import React from "react"

import Dropzone from 'react-dropzone'

const DropFile = (props)=> {
  var keystring
  var message
  try {
    keystring = JSON.parse(props.keystring)
    message =

      Uploaded keystore file for address: {keystring.address}

  } catch (e) {
    console.log(e)
    if (props.error != "") {
      message =

        {props.error}

    } else {
      message =

        Upload a valid keystore file

    }
  }
  //console.log(keystring)
  return (
    <Dropzone onDrop={props.onDrop}>
      {message}
    </Dropzone>)
}

export default DropFile<commit_msg>fix import null address<commit_after>import React from "react"

import Dropzone from 'react-dropzone'

const DropFile = (props)=> {
  var keystring
  var message
  try {
    if(props.keystring){
      keystring = JSON.parse(props.keystring)
      message =

        Uploaded keystore file for address: {keystring.address}

    }
  } catch (e) {
    console.log(e)
    if (props.error != "") {
      message =

        {props.error}

    } else {
      message =

        Upload a valid keystore file

    }
  }
  //console.log(keystring)
  return (
    <Dropzone onDrop={props.onDrop}>
      {message}
    </Dropzone>)
}

export default DropFile<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET books listing. */
var data={
    "book_name":'js权威指南',
    "book_price":"￥123.00"
};
router.get('/', function(req, res, next) {
    var _callback = req.query.callback;
    if (_callback){
        res.type('text/javascript');
        res.send(_callback + '(' + JSON.stringify(data) + ')');
    }
    else{
        res.json(_data);
    }
});

module.exports = router;<commit_msg>aasq1<commit_after>var express = require('express');
var router = express.Router();

/* GET books listing. */
var data={
    "book_name":'js权威指南',
    "book_price":"￥123.00"
};
router.get('/', function(req, res, next) {
    var _callback = req.query.callback;
    if (_callback){
        res.type('text/javascript');
        res.send(_callback + '(' + JSON.stringify(data) + ')');
    }
    else{
        res.json(data);
    }
});

module.exports = router;<|endoftext|>