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

/**
 * Script for template display interactions
 * @class aria.tools.inspector.TemplateInspectorScript
 */
Aria.tplScriptDefinition({
    $classpath : 'aria.tools.inspector.TemplateInspectorScript',
    $prototype : {

        /**
         * Highlight a widget in the application on mouseover
         * @param {Object} event
         * @param {Object} widgetDesc description
         */
        widgetMouseOver : function (event, widgetDesc) {
            var widget = widgetDesc.widget;
            var domElt = widget.getDom();
            if (domElt) {
                this.moduleCtrl.displayHighlight(domElt, "#FF6666");
            }
            this.mouseOver(event);
            event.stopPropagation();
        },

        /**
         * Remove highlight from a widget link on mouseout
         * @param {Object} event
         */
        widgetMouseOut : function (event) {
            this.mouseOut(event);
            // prevent propagation
            event.stopPropagation();
        },

        /**
         * Highlight an element on mouseover
         * @param {Object} event
         */
        mouseOver : function (event) {
            event.target.setStyle("background:#DDDDDD;");
        },

        /**
         * Remove highlight of element on mouseout
         * @param {Object} event
         */
        mouseOut : function (event) {
            event.target.setStyle("");
        },

        /**
         * Display widget details
         * @param {Object} widgetDesc
         */
        displayWidgetDetails : function (event, widgetDesc) {
            this.data.selectedWidget = widgetDesc;
            this.$refresh({
                section : "widgets"
            });
        },

        /**
         * Call the module controller to reload a given template instance
         * @param {Object} event
         */
        reloadTemplate : function (event) {
            this.moduleCtrl.reloadTemplate(this.data.templateCtxt);
        },

        /**
         * Reload source using content from editable source
         */
        reloadTemplateWithSrc : function () {
            this.moduleCtrl.reloadTemplate(this.data.templateCtxt, true);
        },

        /**
         * Call the module controller to refresh a given template
         * @param {Object} event
         */
        refreshTemplate : function (event) {
            this.moduleCtrl.refreshTemplate(this.data.templateCtxt);
        },

        /**
         * Act on module event
         * @param {Object} event
         */
        onModuleEvent : function (event) {

        },

        /**
         * Change visibility of source, and retrieve it if not available
         * @param {aria.DomEvent} event
         */
        toggleSource : function (event) {
            this.data.showSource = !this.data.showSource;
            if (this.data.showSource) {
                this.data.initialSource = true;
                var filePath = this.data.templateCtxt.tplClasspath.replace(/\./g, "/") + ".tpl";
                this.data.source = this.moduleCtrl.getSource(filePath).value;
            }
            this.$refresh();
        },

        /**
         * Edit source code of template
         * @param {aria.DomEvent} event
         */
        editSource : function (event) {
            if (this.data.initialSource) {
                aria.utils.Json.setValue(this.data, "initialSource", false);
                this.$refresh({
                    filterSection : "controls",
                    macro : {
                        name : "displayControls"
                    }
                });
            }
            this.data.tplSrcEdit = event.target.getValue();
        },

        /**
         * Refresh the list of widgets only.
         */
        _refreshWidgetsDisplay : function () {
            this.$refresh({
                section : "widgets"
            });
        }
    }
});<commit_msg>fix #748 debug tools: "reload with source" button no longer appears<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Script for template display interactions
 * @class aria.tools.inspector.TemplateInspectorScript
 */
Aria.tplScriptDefinition({
    $classpath : 'aria.tools.inspector.TemplateInspectorScript',
    $prototype : {

        /**
         * Highlight a widget in the application on mouseover
         * @param {Object} event
         * @param {Object} widgetDesc description
         */
        widgetMouseOver : function (event, widgetDesc) {
            var widget = widgetDesc.widget;
            var domElt = widget.getDom();
            if (domElt) {
                this.moduleCtrl.displayHighlight(domElt, "#FF6666");
            }
            this.mouseOver(event);
            event.stopPropagation();
        },

        /**
         * Remove highlight from a widget link on mouseout
         * @param {Object} event
         */
        widgetMouseOut : function (event) {
            this.mouseOut(event);
            // prevent propagation
            event.stopPropagation();
        },

        /**
         * Highlight an element on mouseover
         * @param {Object} event
         */
        mouseOver : function (event) {
            event.target.setStyle("background:#DDDDDD;");
        },

        /**
         * Remove highlight of element on mouseout
         * @param {Object} event
         */
        mouseOut : function (event) {
            event.target.setStyle("");
        },

        /**
         * Display widget details
         * @param {Object} widgetDesc
         */
        displayWidgetDetails : function (event, widgetDesc) {
            this.data.selectedWidget = widgetDesc;
            this.$refresh({
                section : "widgets"
            });
        },

        /**
         * Call the module controller to reload a given template instance
         * @param {Object} event
         */
        reloadTemplate : function (event) {
            this.moduleCtrl.reloadTemplate(this.data.templateCtxt);
        },

        /**
         * Reload source using content from editable source
         */
        reloadTemplateWithSrc : function () {
            this.moduleCtrl.reloadTemplate(this.data.templateCtxt, true);
        },

        /**
         * Call the module controller to refresh a given template
         * @param {Object} event
         */
        refreshTemplate : function (event) {
            this.moduleCtrl.refreshTemplate(this.data.templateCtxt);
        },

        /**
         * Act on module event
         * @param {Object} event
         */
        onModuleEvent : function (event) {

        },

        /**
         * Change visibility of source, and retrieve it if not available
         * @param {aria.DomEvent} event
         */
        toggleSource : function (event) {
            this.data.showSource = !this.data.showSource;
            if (this.data.showSource) {
                this.data.initialSource = true;
                var filePath = this.data.templateCtxt.tplClasspath.replace(/\./g, "/") + ".tpl";
                this.data.source = this.moduleCtrl.getSource(filePath).value;
            }
            this.$refresh();
        },

        /**
         * Edit source code of template
         * @param {aria.DomEvent} event
         */
        editSource : function (event) {
            if (this.data.initialSource) {
                aria.utils.Json.setValue(this.data, "initialSource", false);
                this.$refresh({
                    section : "controls"
                });
            }
            this.data.tplSrcEdit = event.target.getValue();
        },

        /**
         * Refresh the list of widgets only.
         */
        _refreshWidgetsDisplay : function () {
            this.$refresh({
                section : "widgets"
            });
        }
    }
});<|endoftext|>


<commit_before>/* ===================================================
 * bootstrap-transition.js v2.0.4
 * http://twitter.github.com/bootstrap/javascript.html#transitions
 * ===================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

  $(function () {

    "use strict"; // jshint ;_;

    /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
     * ======================================================= */

    $.support.transition = (function () {

      var transitionEnd = (function () {

        var el = document.createElement('bootstrap')
          , transEndEventNames = {
               'WebkitTransition' : 'webkitTransitionEnd'
            ,  'MozTransition'    : 'transitionend'
            ,  'OTransition'      : 'oTransitionEnd otransitionend'
            ,  'msTransition'     : 'MSTransitionEnd'
            ,  'transition'       : 'transitionend'
            }
          , name

        for (name in transEndEventNames){
          if (el.style[name] !== undefined) {
            return transEndEventNames[name]
          }
        }

      }())

      return transitionEnd && {
        end: transitionEnd
      }

    })()

  })

}(window.jQuery);<commit_msg>IE10 uses 'transition' and 'transitionend'<commit_after>/* ===================================================
 * bootstrap-transition.js v2.0.4
 * http://twitter.github.com/bootstrap/javascript.html#transitions
 * ===================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

  $(function () {

    "use strict"; // jshint ;_;

    /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
     * ======================================================= */

    $.support.transition = (function () {

      var transitionEnd = (function () {

        var el = document.createElement('bootstrap')
          , transEndEventNames = {
               'WebkitTransition' : 'webkitTransitionEnd'
            ,  'MozTransition'    : 'transitionend'
            ,  'OTransition'      : 'oTransitionEnd otransitionend'
            ,  'transition'       : 'transitionend'
            }
          , name

        for (name in transEndEventNames){
          if (el.style[name] !== undefined) {
            return transEndEventNames[name]
          }
        }

      }())

      return transitionEnd && {
        end: transitionEnd
      }

    })()

  })

}(window.jQuery);<|endoftext|>


<commit_before>import { domHelpers, platform } from 'substance'
import { Tool } from '../../kit'

export default class DownloadSupplementaryFileTool extends Tool {
  render ($$) {
    let el = super.render($$)
    let link = $$('a').ref('link')
      // Downloads a non-remote urls
      .attr('download', '')
      // ATTENTION: stop propagation, otherwise infinite loop
      .on('click', domHelpers.stop)

    el.append(link)
    return el
  }

  getClassNames () {
    return 'sc-download-supplementary-file-tool sc-tool'
  }

  _onClick (e) {
    e.stopPropagation()
    e.preventDefault()
    this._triggerDownload()
  }

  _triggerDownload () {
    const archive = this.context.archive
    const editorSession = this.context.editorSession
    const selectionState = editorSession.getSelectionState()
    const node = selectionState.node
    const isLocal = !node.remote
    let url = node.href
    if (isLocal) {
      url = archive.getDownloadLink(node.href)
    }
    if (url) {
      this.refs.link.el.attr({
        'href': url
      })
      // Note: in the browser version we want to open remote files in a new tab
      if (!platform.inElectron && !isLocal) {
        this.refs.link.attr('target', '_blank')
      }
      this.refs.link.el.click()
    }
  }
}
<commit_msg>Improve DownloadSupplementaryFileTool.<commit_after>import { domHelpers, platform } from 'substance'
import { Tool } from '../../kit'

export default class DownloadSupplementaryFileTool extends Tool {
  render ($$) {
    let el = super.render($$)
    let link = $$('a').ref('link')
      // ATTENTION: stop propagation, otherwise infinite loop
      .on('click', domHelpers.stop)

    // Downloading is a bit involved:
    // In electron, everything can be done with one solution,
    // handling a 'will-download' event, which is triggered when the `download`
    // attribute is present.
    // For the browser, the `download` attribute works only for files from the same
    // origin. For remote files the best we can do at the moment, is opening
    // a new tab, and let the browser deal with it.
    // TODO: if this feature is important, one idea is that the DAR server could
    // provide an end-point to provide download-urls, and act as a proxy to
    // cirvumvent the CORS problem.
    const isLocal = this._isLocal()
    if (platform.inElectron || isLocal) {
      link.attr('download', '')
    } else {
      link.attr('target', '_blank')
    }

    el.append(link)
    return el
  }

  getClassNames () {
    return 'sc-download-supplementary-file-tool sc-tool'
  }

  _onClick (e) {
    e.stopPropagation()
    e.preventDefault()
    this._triggerDownload()
  }

  _triggerDownload () {
    const archive = this.context.archive
    const node = this._getNode()
    const isLocal = this._isLocal()
    let url = node.href
    if (isLocal) {
      url = archive.getDownloadLink(node.href)
    }
    if (url) {
      this.refs.link.el.attr({
        'href': url
      })
      this.refs.link.el.click()
    }
  }

  _getNode () {
    return this.props.commandState.node
  }

  _isLocal () {
    let node = this._getNode()
    return (!node || !node.remote)
  }
}
<|endoftext|>


<commit_before>export default class PromiseTimeoutError extends Error {
    constructor(...args) {
        super(...args);

        this.name = 'PromiseTimeoutError';
    }
};<commit_msg>Fix PromiseTimeoutError to properly extend Error<commit_after>module.exports = function PromiseTimeoutError(message) {
    Error.captureStackTrace(this, this.constructor);
    this.name = this.constructor.name;
    this.message = message;
};

require('util').inherits(module.exports, Error);
<|endoftext|>


<commit_before>// deactivate-meeting-hook.js -- Before, patch. sets a meeting to inactive
// if it's going from n to 0 participant before a `patch` event
// will also:
// - generate meeting events for meeting ends
// - end turn computation when a meeting stops
'use strict'
const _ = require('underscore')
const winston = require('winston')

var d3 = require('d3')
var jsdom = require('jsdom')
var nodemailer = require('nodemailer')
var request = require('request')

function shouldMakeMeetingInactive (newParticipants, meetingObject) {
  return (newParticipants.length === 0 &&
          meetingObject.participants.length > 0 &&
          meetingObject.active === true)
}

function reportMeeting (hook) {
  getReportData(hook, (visualizationData, addresses) => {
    sendReport(createVisualization(visualizationData), addresses)
  })
}

function getReportData (hook, callback) {
  winston.log('info', 'Getting report data...')
  // find participant events (-> historical participants)
  var meetingId = hook.id
  if (hook.id === Object(hook.id)) {
    meetingId = hook.id._id
  }
  return hook.app.service('participants').find({
    query: {
      $limit: 1000,
      $select: [ '_id', 'name', 'meetings' ]
    }
  }).then((participants) => {
    var validParticipants = _.filter(participants.data, (participant) => {
      return _.contains(participant.meetings, meetingId)
    })
    // find utterances
    hook.app.service('utterances').find({
      query: {
        meeting: meetingId,
        $select: [ 'participant', 'meeting', 'startTime', 'endTime' ]
      }
    }).then((utterances) => {
      // {'participant': [utteranceObject, ...]}
      var participantUtterances = _.groupBy(utterances, 'participant')
      // {'participant': number of utterances}
      var numUtterances = _.mapObject(participantUtterances, (val, key) => {
        return val.length
      })
      // {'participant': mean length of utterances in seconds}
      var meanLengthUtterances = _.mapObject(participantUtterances, (val, key) => {
        var lengthsUtterances = val.map((utteranceObject) => {
          return (new Date(utteranceObject.endTime).getTime() - new Date(utteranceObject.startTime).getTime()) / 1000
        })
        var sum = lengthsUtterances.reduce((previous, current) => current + previous, 0)
        return sum / lengthsUtterances.length
      })
      // [{'name': ..., 'numUtterances': ..., 'meanLengthUtterances': ...}, ...]
      var visualizationData = validParticipants.map((participant) => {
        var participantId = participant[ '_id' ]
        return {
          name: participant[ 'name' ],
          numUtterances: participantId in numUtterances ? numUtterances[ participantId ] : 0,
          meanLengthUtterances: participantId in meanLengthUtterances ? meanLengthUtterances[ participantId ] : 0
        }
      })
      // get mapping between google id and addresses
      request.get(process.env.MAPPING_URL, function (error, response, body) {
        // {'_id': address, ...}
        var mapping = {}
        if (!error && response.statusCode === 200) {
          var rows = body.split('\n')
          for (var i = 0; i < rows.length; i++) {
            var cols = rows[ i ].split(',')
            mapping[ String(cols[ 0 ]) ] = cols[ 1 ]
          }
        }
        // [address, ...]
        var addresses = validParticipants.map((participant) => {
          return mapping[ participant[ '_id' ] ]
        })
        callback(visualizationData, addresses)
      }).catch(function (error) {
        winston.log('info', '[getReportData] error: ', error)
      })
    })
  })
}

function createVisualization (visualizationData) {
  winston.log('info', 'Creating report visualization...')
  var margin = { top: 20, right: 15, bottom: 60, left: 60 }
  var width = 800 - margin.left - margin.right
  var height = 500 - margin.top - margin.bottom
  var color = d3.scale.category20()

  var x = d3.scale.linear()
    .domain([ 0, d3.max(visualizationData, function (d) { return d.meanLengthUtterances }) + 5 ])
    .range([ 0, width ])

  var y = d3.scale.linear()
    .domain([ 0, d3.max(visualizationData, function (d) { return d.numUtterances }) + 1 ])
    .range([ height, 0 ])

  var document = jsdom.jsdom()
  var chart = d3.select(document.body)
    .append('svg')
    .attr('width', width + margin.right + margin.left)
    .attr('height', height + margin.top + margin.bottom)
    .attr('class', 'chart')

  var main = chart.append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
    .attr('width', width)
    .attr('height', height)
    .attr('class', 'main')

  // draw the x axis
  var xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')

  main.append('g')
    .attr('transform', 'translate(0,' + height + ')')
    .attr('class', 'main axis date')
    .call(xAxis)
    .append('text')
    .attr('class', 'label')
    .attr('x', width)
    .attr('y', -15)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('Avg. Length of Turns')

  // draw the y axis
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient('left')

  main.append('g')
    .attr('transform', 'translate(0,0)')
    .attr('class', 'main axis date')
    .call(yAxis)
    .append('text')
    .attr('class', 'label')
    .attr('transform', 'rotate(-90)')
    .attr('y', 6)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('Turns Taken')

  var g = main.append('svg:g')

  var node = g.selectAll('scatter-dots')
    .data(visualizationData)
    .enter().append('g')

  node.append('svg:circle')
    .style('fill', function (d) { return color(d.name) })
    .attr('cx', function (d, i) { return x(d.meanLengthUtterances) })
    .attr('cy', function (d) { return y(d.numUtterances) })
    .attr('r', 10)

  node.append('text')
    .attr('x', function (d) { return x(d.meanLengthUtterances) + 10 })
    .attr('y', function (d) { return y(d.numUtterances) })
    .text(function (d) { return d.name })

  // create html file
  var htmlStyle = '\n'
  var htmlBody = '\n' +
    '
Your Meeting: Turn Taken
\n' +
    d3.select(document.body).node().innerHTML + '\n' +
    ''
  var html = '<!DOCTYPE html>\n' +
    '<meta charset="utf-8">\n' +
    htmlStyle +
    htmlBody

  return html
}

function sendReport (visualization, addresses) {
  winston.log('info', 'Sending report...')
  // TODO change SMTP configurations
  // define SMTP configurations
  var smtpConfig = {
    host: process.env.REPORT_EMAIL_HOST,
    port: 465,
    secure: true,
    auth: {
      user: process.env.REPORT_EMAIL_LOGIN,
      pass: process.env.REPORT_EMAIL_PASSWORD
    }
  }
  // create transporter object
  var transporter = nodemailer.createTransport(smtpConfig)
  // TODO change email data
  // setup email data
  var mailOptions = {
    from: process.env.REPORT_EMAIL_FROM,
    to: addresses,
    subject: process.env.REPORT_EMAIL_SUBJECT,
    text: process.env.REPORT_EMAIL_TEXT,
    html: process.env.REPORT_EMAIL_TEXT,
    attachments: {
      filename: 'visualization.html',
      content: visualization
    }
  }
  // send email with transporter object
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      return console.log('[sendReport] error: ' + error)
    }
    return console.log('Report was sent: ' + info.response)
  })
}

function createMeetingEndEvent (hook) {
  var meetingId = (hook.method === 'create') ? hook.data._id : hook.id
  return hook.app.service('meetingEvents').create({
    meeting: meetingId,
    event: 'end',
    timestamp: new Date()
  }, {}).then((meetingEvent) => {
    return hook
  })
}

module.exports = function (hook) {
  if (!_.has(hook.data, 'participants')) {
    return hook
  } else {
    return hook.app.service('meetings').get(hook.id)
               .then((meeting) => {
                 if (shouldMakeMeetingInactive(hook.data.participants, meeting)) {
                   hook.data.active = false
                   hook.data.endTime = new Date()
                   if (process.env.SEND_REPORT) {
                     reportMeeting(hook)
                   }
                   return createMeetingEndEvent(hook)
                 } else {
                   return hook
                 }
               })
  }
}
<commit_msg>adding some detail to the reports students see<commit_after>// deactivate-meeting-hook.js -- Before, patch. sets a meeting to inactive
// if it's going from n to 0 participant before a `patch` event
// will also:
// - generate meeting events for meeting ends
// - end turn computation when a meeting stops
'use strict'
const _ = require('underscore')
const winston = require('winston')

var d3 = require('d3')
var jsdom = require('jsdom')
var nodemailer = require('nodemailer')
var request = require('request')

function shouldMakeMeetingInactive (newParticipants, meetingObject) {
  return (newParticipants.length === 0 &&
          meetingObject.participants.length > 0 &&
          meetingObject.active === true)
}

function reportMeeting (hook) {
  getReportData(hook, (visualizationData, addresses) => {
    sendReport(createVisualization(visualizationData), addresses)
  })
}

function getReportData (hook, callback) {
  winston.log('info', 'Getting report data...')
  // find participant events (-> historical participants)
  var meetingId = hook.id
  if (hook.id === Object(hook.id)) {
    meetingId = hook.id._id
  }
  return hook.app.service('participants').find({
    query: {
      $limit: 1000,
      $select: [ '_id', 'name', 'meetings' ]
    }
  }).then((participants) => {
    var validParticipants = _.filter(participants.data, (participant) => {
      return _.contains(participant.meetings, meetingId)
    })
    // find utterances
    hook.app.service('utterances').find({
      query: {
        meeting: meetingId,
        $select: [ 'participant', 'meeting', 'startTime', 'endTime' ]
      }
    }).then((utterances) => {
      // {'participant': [utteranceObject, ...]}
      var participantUtterances = _.groupBy(utterances, 'participant')
      // {'participant': number of utterances}
      var numUtterances = _.mapObject(participantUtterances, (val, key) => {
        return val.length
      })
      // {'participant': mean length of utterances in seconds}
      var meanLengthUtterances = _.mapObject(participantUtterances, (val, key) => {
        var lengthsUtterances = val.map((utteranceObject) => {
          return (new Date(utteranceObject.endTime).getTime() - new Date(utteranceObject.startTime).getTime()) / 1000
        })
        var sum = lengthsUtterances.reduce((previous, current) => current + previous, 0)
        return sum / lengthsUtterances.length
      })
      // [{'name': ..., 'numUtterances': ..., 'meanLengthUtterances': ...}, ...]
      var visualizationData = validParticipants.map((participant) => {
        var participantId = participant[ '_id' ]
        return {
          name: participant[ 'name' ],
          numUtterances: participantId in numUtterances ? numUtterances[ participantId ] : 0,
          meanLengthUtterances: participantId in meanLengthUtterances ? meanLengthUtterances[ participantId ] : 0
        }
      })
      // get mapping between google id and addresses
      request.get(process.env.MAPPING_URL, function (error, response, body) {
        // {'_id': address, ...}
        var mapping = {}
        if (!error && response.statusCode === 200) {
          var rows = body.split('\n')
          for (var i = 0; i < rows.length; i++) {
            var cols = rows[ i ].split(',')
            mapping[ String(cols[ 0 ]) ] = cols[ 1 ]
          }
        }
        // [address, ...]
        var addresses = validParticipants.map((participant) => {
          return mapping[ participant[ '_id' ] ]
        })
        callback(visualizationData, addresses)
      }).catch(function (error) {
        winston.log('info', '[getReportData] error: ', error)
      })
    })
  })
}

function createVisualization (visualizationData) {
  winston.log('info', 'Creating report visualization...')
  var margin = { top: 20, right: 15, bottom: 60, left: 60 }
  var width = 800 - margin.left - margin.right
  var height = 500 - margin.top - margin.bottom
  var color = d3.scale.category20()

  var x = d3.scale.linear()
    .domain([ 0, d3.max(visualizationData, function (d) { return d.meanLengthUtterances }) + 5 ])
    .range([ 0, width ])

  var y = d3.scale.linear()
    .domain([ 0, d3.max(visualizationData, function (d) { return d.numUtterances }) + 1 ])
    .range([ height, 0 ])

  var document = jsdom.jsdom()
  var chart = d3.select(document.body)
    .append('svg')
    .attr('width', width + margin.right + margin.left)
    .attr('height', height + margin.top + margin.bottom)
    .attr('class', 'chart')

  var main = chart.append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
    .attr('width', width)
    .attr('height', height)
    .attr('class', 'main')

  // draw the x axis
  var xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')

  main.append('g')
    .attr('transform', 'translate(0,' + height + ')')
    .attr('class', 'main axis date')
    .call(xAxis)
    .append('text')
    .attr('class', 'label')
    .attr('x', width)
    .attr('y', -15)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('Avg. Length of Turns (in seconds))')

  // draw the y axis
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient('left')

  main.append('g')
    .attr('transform', 'translate(0,0)')
    .attr('class', 'main axis date')
    .call(yAxis)
    .append('text')
    .attr('class', 'label')
    .attr('transform', 'rotate(-90)')
    .attr('y', 6)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('Turns Taken')

  var g = main.append('svg:g')

  var node = g.selectAll('scatter-dots')
    .data(visualizationData)
    .enter().append('g')

  node.append('svg:circle')
    .style('fill', function (d) { return color(d.name) })
    .attr('cx', function (d, i) { return x(d.meanLengthUtterances) })
    .attr('cy', function (d) { return y(d.numUtterances) })
    .attr('r', 10)

  node.append('text')
    .attr('x', function (d) { return x(d.meanLengthUtterances) + 10 })
    .attr('y', function (d) { return y(d.numUtterances) })
    .text(function (d) { return d.name })

  // create html file
  var htmlStyle = '\n'
  var htmlBody = '\n' +
        '
Your Meeting: Turns Taken
\n' +
        '
We count a "turn" any time you speak for more than around a second. The most creative and productive teams might have their dots clumped near each other, showing that they have all contributed somewhat equally.
\n' +
        d3.select(document.body).node().innerHTML + '\n' +
    ''
  var html = '<!DOCTYPE html>\n' +
    '<meta charset="utf-8">\n' +
    htmlStyle +
    htmlBody

  return html
}

function sendReport (visualization, addresses) {
  winston.log('info', 'Sending report...')
  // TODO change SMTP configurations
  // define SMTP configurations
  var smtpConfig = {
    host: process.env.REPORT_EMAIL_HOST,
    port: 465,
    secure: true,
    auth: {
      user: process.env.REPORT_EMAIL_LOGIN,
      pass: process.env.REPORT_EMAIL_PASSWORD
    }
  }
  // create transporter object
  var transporter = nodemailer.createTransport(smtpConfig)
  // TODO change email data
  // setup email data
  var mailOptions = {
    from: process.env.REPORT_EMAIL_FROM,
    to: addresses,
    subject: process.env.REPORT_EMAIL_SUBJECT,
    text: process.env.REPORT_EMAIL_TEXT,
    html: process.env.REPORT_EMAIL_TEXT,
    attachments: {
      filename: 'visualization.html',
      content: visualization
    }
  }
  // send email with transporter object
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      return console.log('[sendReport] error: ' + error)
    }
    return console.log('Report was sent: ' + info.response)
  })
}

function createMeetingEndEvent (hook) {
  var meetingId = (hook.method === 'create') ? hook.data._id : hook.id
  return hook.app.service('meetingEvents').create({
    meeting: meetingId,
    event: 'end',
    timestamp: new Date()
  }, {}).then((meetingEvent) => {
    return hook
  })
}

module.exports = function (hook) {
  if (!_.has(hook.data, 'participants')) {
    return hook
  } else {
    return hook.app.service('meetings').get(hook.id)
               .then((meeting) => {
                 if (shouldMakeMeetingInactive(hook.data.participants, meeting)) {
                   hook.data.active = false
                   hook.data.endTime = new Date()
                   if (process.env.SEND_REPORT) {
                     reportMeeting(hook)
                   }
                   return createMeetingEndEvent(hook)
                 } else {
                   return hook
                 }
               })
  }
}
<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Emitter = require( 'AXON/Emitter' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix = require( 'DOT/Matrix' );
  var waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );

  // constants
  var waveSpeed = 0.5; // The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html
  var waveSpeedSquared = waveSpeed * waveSpeed;
  var numMatrices = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points

  /**
   * @param {number} width - width of the lattice
   * @param {number} height - height of the lattice
   * @param {number} dampX - number of cells on the left and again on the right to use for damping
   * @param {number} dampY - number of cells on the top and again on the bottom to use for damping
   * @param {function} getPotential - function(i,j) that returns true if there is a potential barrier there
   * @constructor
   */
  function Lattice( width, height, dampX, dampY, getPotential ) {

    // @public (read-only) {number} number of cells on the left and again on the right to use for damping
    this.dampX = dampX;

    // @public (read-only) {number} number of cells on the top and again on the bottom to use for damping
    this.dampY = dampY;

    // @private {Matrix[]} matrices for current value, previous value and value before previous
    this.matrices = [];
    for ( var i = 0; i < numMatrices; i++ ) {
      this.matrices.push( new Matrix( width, height ) );
    }

    // @private {number} indicates the current matrix. Previous matrix is one higher (with correct modulus)
    this.currentMatrixIndex = 0;

    // @private {function} returns true if there is a potential barrier there TODO: move to options
    this.getPotential = getPotential || function( i, j ) {return false;};

    // @public {Emitter} sends a notification each time the lattice updates
    this.changedEmitter = new Emitter();

    // @public {number} (read-only) width of the lattice
    this.width = width;

    // @public {number} (read-only) height of the lattice
    this.height = height;
  }

  waveInterference.register( 'Lattice', Lattice );

  return inherit( Object, Lattice, {

    /**
     * Returns the current value in the given cell
     * @param {number} i
     * @param {number} j
     * @public
     */
    getCurrentValue: function( i, j ) {
      return this.matrices[ this.currentMatrixIndex ].get( i, j );
    },

    /**
     * Sets the current value in the given cell
     * @param {number} i
     * @param {number} j
     * @param {number} value
     * @public
     */
    setCurrentValue: function( i, j, value ) {
      this.matrices[ this.currentMatrixIndex ].set( i, j, value );
    },

    /**
     * Returns the previous value in the given cell
     * @param {number} i
     * @param {number} j
     * @private
     */
    getLastValue: function( i, j ) {
      return this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ].get( i, j );
    },

    /**
     * Sets the previous value in the given cell
     * @param {number} i
     * @param {number} j
     * @param {number} value
     * @private
     */
    setLastValue: function( i, j, value ) {
      this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ].set( i, j, value );
    },

    /**
     * Across a horizontal line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} j - y coordinate for the lattice
     * @param {number} dj - distance above or below to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampHorizontalTemporal: function( j, dj, matrix0, matrix2 ) {
      for ( var i = 0; i < this.width; i++ ) {
        matrix0.set( i, j, matrix2.get( i, j + dj ) );
      }
    },

    /**
     * Across a vertical line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} i - x coordinate for the lattice
     * @param {number} di - distance left or right to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampVerticalTemporal: function( i, di, matrix0, matrix2 ) {
      for ( var j = 0; j < this.height; j++ ) {
        matrix0.set( i, j, matrix2.get( i + di, j ) );
      }
    },

    /**
     * Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} i0 - x coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} width - width of the damping region
     * @private
     */
    decayVertical: function( i0, sign, width ) {
      for ( var j = 0; j < this.height; j++ ) {
        for ( var step = 0; step < width; step++ ) {
          var distFromDampBoundary = width - step;
          var damp = this.getDamp( distFromDampBoundary );
          var i = i0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} j0 - y coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} height - height of the damping region
     * @private
     */
    decayHorizontal: function( j0, sign, height ) {
      for ( var i = 0; i < this.width; i++ ) {
        for ( var step = 0; step < height; step++ ) {
          var distFromDampBoundary = height - step;
          var damp = this.getDamp( distFromDampBoundary );
          var j = j0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Damp more aggressively further from the edge of the visible lattice
     * @param {number} depthInDampRegion - number of cells into the damping region
     * @returns {number} scale factor for dampening the wave
     * @private
     */
    getDamp: function( depthInDampRegion ) {
      return (1 - depthInDampRegion * 0.0001);
    },

    /**
     * Propagates the wave by one step.  This is a discrete algorithm and cannot use dt.
     * @public
     */
    step: function() {
      this.currentMatrixIndex = (this.currentMatrixIndex - 1 + this.matrices.length) % this.matrices.length;

      var matrix0 = this.matrices[ (this.currentMatrixIndex + 0) % this.matrices.length ];
      var matrix1 = this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ];
      var matrix2 = this.matrices[ (this.currentMatrixIndex + 2) % this.matrices.length ];
      var width = matrix0.getRowDimension();
      var height = matrix0.getColumnDimension();
      for ( var i = 0; i < width; i++ ) {
        for ( var j = 0; j < height; j++ ) {
          if ( this.getPotential( i, j ) ) {
            matrix0.set( i, j, 0 );
          }
          else {
            var neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
            var m1ij = matrix1.get( i, j );
            var value = m1ij * 2 - matrix2.get( i, j ) + waveSpeedSquared * (neighborSum + m1ij * -4);
            matrix0.set( i, j, value );
          }
        }
      }

      // temporal dampen on the visible region
      this.dampHorizontalTemporal( this.dampY, 1, matrix0, matrix2 );
      this.dampHorizontalTemporal( this.height - 1 - this.dampY, -1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.dampX, +1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.width - 1 - this.dampX, -1, matrix0, matrix2 );

      // decay the wave outside of the visible part
      this.decayVertical( 0, +1, this.dampY / 2 );
      this.decayVertical( this.width - 1, -1, this.dampY / 2 );
      this.decayHorizontal( 0, +1, this.dampX / 2 );
      this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );

      this.changedEmitter.emit();
    }
  } );
} );<commit_msg>Model cleanup and reset<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Emitter = require( 'AXON/Emitter' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix = require( 'DOT/Matrix' );
  var waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );

  // constants
  var waveSpeed = 0.5; // The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html
  var waveSpeedSquared = waveSpeed * waveSpeed;
  var numMatrices = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points

  /**
   * @param {number} width - width of the lattice
   * @param {number} height - height of the lattice
   * @param {number} dampX - number of cells on the left and again on the right to use for damping
   * @param {number} dampY - number of cells on the top and again on the bottom to use for damping
   * @param {function} getPotential - function(i,j) that returns true if there is a potential barrier there
   * @constructor
   */
  function Lattice( width, height, dampX, dampY, getPotential ) {

    // @public (read-only) {number} number of cells on the left and again on the right to use for damping
    this.dampX = dampX;

    // @public (read-only) {number} number of cells on the top and again on the bottom to use for damping
    this.dampY = dampY;

    // @private {Matrix[]} matrices for current value, previous value and value before previous
    this.matrices = [];
    for ( var i = 0; i < numMatrices; i++ ) {
      this.matrices.push( new Matrix( width, height ) );
    }

    // @private {number} indicates the current matrix. Previous matrix is one higher (with correct modulus)
    this.currentMatrixIndex = 0;

    // @private {function} returns true if there is a potential barrier there TODO: move to options
    this.getPotential = getPotential || function( i, j ) {return false;};

    // @public {Emitter} sends a notification each time the lattice updates
    this.changedEmitter = new Emitter();

    // @public {number} (read-only) width of the lattice
    this.width = width;

    // @public {number} (read-only) height of the lattice
    this.height = height;
  }

  waveInterference.register( 'Lattice', Lattice );

  return inherit( Object, Lattice, {

    /**
     * Returns the current value in the given cell
     * @param {number} i
     * @param {number} j
     * @public
     */
    getCurrentValue: function( i, j ) {
      return this.matrices[ this.currentMatrixIndex ].get( i, j );
    },

    /**
     * Sets the current value in the given cell
     * @param {number} i
     * @param {number} j
     * @param {number} value
     * @public
     */
    setCurrentValue: function( i, j, value ) {
      this.matrices[ this.currentMatrixIndex ].set( i, j, value );
    },

    /**
     * Returns the previous value in the given cell
     * @param {number} i
     * @param {number} j
     * @private
     */
    getLastValue: function( i, j ) {
      return this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ].get( i, j );
    },

    /**
     * Sets the previous value in the given cell
     * @param {number} i
     * @param {number} j
     * @param {number} value
     * @private
     */
    setLastValue: function( i, j, value ) {
      this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ].set( i, j, value );
    },

    /**
     * Across a horizontal line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} j - y coordinate for the lattice
     * @param {number} dj - distance above or below to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampHorizontalTemporal: function( j, dj, matrix0, matrix2 ) {
      for ( var i = 0; i < this.width; i++ ) {
        matrix0.set( i, j, matrix2.get( i, j + dj ) );
      }
    },

    /**
     * Across a vertical line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} i - x coordinate for the lattice
     * @param {number} di - distance left or right to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampVerticalTemporal: function( i, di, matrix0, matrix2 ) {
      for ( var j = 0; j < this.height; j++ ) {
        matrix0.set( i, j, matrix2.get( i + di, j ) );
      }
    },

    /**
     * Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} i0 - x coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} width - width of the damping region
     * @private
     */
    decayVertical: function( i0, sign, width ) {
      for ( var j = 0; j < this.height; j++ ) {
        for ( var step = 0; step < width; step++ ) {
          var distFromDampBoundary = width - step;
          var damp = this.getDamp( distFromDampBoundary );
          var i = i0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} j0 - y coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} height - height of the damping region
     * @private
     */
    decayHorizontal: function( j0, sign, height ) {
      for ( var i = 0; i < this.width; i++ ) {
        for ( var step = 0; step < height; step++ ) {
          var distFromDampBoundary = height - step;
          var damp = this.getDamp( distFromDampBoundary );
          var j = j0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Damp more aggressively further from the edge of the visible lattice
     * @param {number} depthInDampRegion - number of cells into the damping region
     * @returns {number} scale factor for dampening the wave
     * @private
     */
    getDamp: function( depthInDampRegion ) {
      return (1 - depthInDampRegion * 0.0001);
    },

    /**
     * Resets all of the wave values to 0
     * @public
     */
    clear: function() {
      for ( var i = 0; i < this.matrices.length; i++ ) {
        this.matrices[ i ].timesEquals( 0 );
      }
    },

    /**
     * Propagates the wave by one step.  This is a discrete algorithm and cannot use dt.
     * @public
     */
    step: function() {
      this.currentMatrixIndex = (this.currentMatrixIndex - 1 + this.matrices.length) % this.matrices.length;

      var matrix0 = this.matrices[ (this.currentMatrixIndex + 0) % this.matrices.length ];
      var matrix1 = this.matrices[ (this.currentMatrixIndex + 1) % this.matrices.length ];
      var matrix2 = this.matrices[ (this.currentMatrixIndex + 2) % this.matrices.length ];
      var width = matrix0.getRowDimension();
      var height = matrix0.getColumnDimension();
      for ( var i = 0; i < width; i++ ) {
        for ( var j = 0; j < height; j++ ) {
          if ( this.getPotential( i, j ) ) {
            matrix0.set( i, j, 0 );
          }
          else {
            var neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
            var m1ij = matrix1.get( i, j );
            var value = m1ij * 2 - matrix2.get( i, j ) + waveSpeedSquared * (neighborSum + m1ij * -4);
            matrix0.set( i, j, value );
          }
        }
      }

      // temporal dampen on the visible region
      this.dampHorizontalTemporal( this.dampY, 1, matrix0, matrix2 );
      this.dampHorizontalTemporal( this.height - 1 - this.dampY, -1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.dampX, +1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.width - 1 - this.dampX, -1, matrix0, matrix2 );

      // decay the wave outside of the visible part
      this.decayVertical( 0, +1, this.dampY / 2 );
      this.decayVertical( this.width - 1, -1, this.dampY / 2 );
      this.decayHorizontal( 0, +1, this.dampX / 2 );
      this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );

      this.changedEmitter.emit();
    }
  } );
} );<|endoftext|>


<commit_before>import React, { Component } from 'react';
import List from './List';
import Message from './Message';
import emitter from '../emitter';
import reqwest from 'reqwest';
import { getMedia } from '../utils';

class Container extends Component {

  constructor(props) {
    super(props);
    this.state = { res: null, type: 'start' };
  }

  componentDidMount () {
    emitter.on('search', (state) => {

      this.setState({ res: null, type: 'loading' });

      reqwest({
        url: 'https://itunes.apple.com/search?media=' + getMedia(state.media || 'all') + '&term=' + state.query.split(' ').join('+'),
        type: 'jsonp'
      })
      .then(response => this.setState({ response, type: response.resultCount || 'noContent'}))
      .fail(err => this.setState({ res: null, type: 'error' }))
      .always(() => emitter.emit('resetLoader'));
    });

  }

  componentWillUnmount () {
    emitter.removeListener('search');
  }

  render () {

    const { type, response } = this.state;

    return (

        <Message type={type} />
        <List {...response} />

    );
  }

}

export default Container;
<commit_msg> add space<commit_after>import React, { Component } from 'react';
import List from './List';
import Message from './Message';
import emitter from '../emitter';
import reqwest from 'reqwest';
import { getMedia } from '../utils';

class Container extends Component {

  constructor(props) {
    super(props);
    this.state = { res: null, type: 'start' };
  }

  componentDidMount () {
    emitter.on('search', (state) => {

      this.setState({ res: null, type: 'loading' });

      reqwest({
        url: 'https://itunes.apple.com/search?media=' + getMedia(state.media || 'all') + '&term=' + state.query.split(' ').join('+'),
        type: 'jsonp'
      })
      .then(response => this.setState({ response, type: response.resultCount || 'noContent' }))
      .fail(err => this.setState({ res: null, type: 'error' }))
      .always(() => emitter.emit('resetLoader'));
    });

  }

  componentWillUnmount () {
    emitter.removeListener('search');
  }

  render () {

    const { type, response } = this.state;

    return (

        <Message type={type} />
        <List {...response} />

    );
  }

}

export default Container;
<|endoftext|>


<commit_before>function convertDiff(name, table) {
  var inline = table.className == 'inline';
  var ths = table.tHead.rows[0].cells;
  var lines = [
    "Index: " + name,
    "===================================================================",
    "--- " + (inline ? ths[0].title : $(ths[0]).find('a').text()),
    "+++ " + (inline ? ths[1].title : $(ths[1]).find('a').text()),
  ];
  var sepIndex = 0;
  var oldOffset = 0, oldLength = 0, newOffset = 0, newLength = 0;

  for (var i = 0; i
 0) {
        if (!oldOffset && oldLength) oldOffset = 1
        if (!newOffset && newLength) newOffset = 1
        lines[sepIndex] = lines[sepIndex]
          .replace("{1}", oldOffset).replace("{2}", oldLength)
          .replace("{3}", newOffset).replace("{4}", newLength);
      }
      sepIndex = lines.length;
      lines.push("@@ -{1},{2}, +{3},{4} @@");
      oldOffset = 0, oldLength = 0, newOffset = 0, newLength = 0;
      if (tBody.className == "skipped") continue;
    }
    var tmpLines = [];
    for (var j = 0; j < tBody.rows.length; j++) {
      var cells = tBody.rows[j].cells;
      var oldLineNo = parseInt($(cells[0]).text());
      var newLineNo = parseInt($(cells[inline ? 1 : 2]).text());
      if (tBody.className == 'unmod') {
        lines.push("  " + $(cells[inline ? 2 : 1]).text());
        oldLength += 1;
        newLength += 1;
        if (!oldOffset) oldOffset = oldLineNo;
        if (!newOffset) newOffset = newLineNo;
      } else {
        var oldLine;
        var newLine;
        if (inline) {
          oldLine = newLine = $(cells[2]).text();
        } else {
          oldLine = $(cells[1]).text();
          newLine = $(cells[3]).text();
        }
        if (!isNaN(oldLineNo)) {
          lines.push("- " + oldLine);
          oldLength += 1;
        }
        if (!isNaN(newLineNo)) {
          tmpLines.push("+ " + newLine);
          newLength += 1;
        }
      }
    }
    if (tmpLines.length > 0) {
      lines = lines.concat(tmpLines);
    }
  }

  if (!oldOffset && oldLength) oldOffset = 1
  if (!newOffset && newLength) newOffset = 1
  lines[sepIndex] = lines[sepIndex]
    .replace("{1}", oldOffset).replace("{2}", oldLength)
    .replace("{3}", newOffset).replace("{4}", newLength);

  return lines.join($.browser.msie ? "\r\n" : "\n");
}

jQuery(document).ready(function($) {
  $("div.diff h2").each(function() {
    var switcher = $("").prependTo(this);
    var name = $.trim($(this).text());
    var table = $(this).siblings("table").get(0);
    if (! table) return;
    var pre = $("

").hide().insertAfter(table);
    $("Tabular").click(function() {
      $(pre).hide();
      $(table).show();
      $(this).addClass("active").siblings("span").removeClass("active");
      return false;
    }).addClass("active").appendTo(switcher);
    $("Unified").click(function() {
      $(table).hide();
      if (!pre.get(0).firstChild) pre.text(convertDiff(name, table));
      $(pre).fadeIn("fast")
      $(this).addClass("active").siblings("span").removeClass("active");
      return false;
    }).appendTo(switcher);
  });
});
<commit_msg>Another r5672 fix: the diff switcher function was not properly namespaced.<commit_after>(function($){

  function convertDiff(name, table) {
    var inline = table.className == 'inline';
    var ths = table.tHead.rows[0].cells;
    var lines = [
      "Index: " + name,
      "===================================================================",
      "--- " + (inline ? ths[0].title : $(ths[0]).find('a').text()),
      "+++ " + (inline ? ths[1].title : $(ths[1]).find('a').text()),
    ];
    var sepIndex = 0;
    var oldOffset = 0, oldLength = 0, newOffset = 0, newLength = 0;

    for (var i = 0; i
 0) {
          if (!oldOffset && oldLength) oldOffset = 1
          if (!newOffset && newLength) newOffset = 1
          lines[sepIndex] = lines[sepIndex]
            .replace("{1}", oldOffset).replace("{2}", oldLength)
            .replace("{3}", newOffset).replace("{4}", newLength);
        }
        sepIndex = lines.length;
        lines.push("@@ -{1},{2}, +{3},{4} @@");
        oldOffset = 0, oldLength = 0, newOffset = 0, newLength = 0;
        if (tBody.className == "skipped") continue;
      }
      var tmpLines = [];
      for (var j = 0; j < tBody.rows.length; j++) {
        var cells = tBody.rows[j].cells;
        var oldLineNo = parseInt($(cells[0]).text());
        var newLineNo = parseInt($(cells[inline ? 1 : 2]).text());
        if (tBody.className == 'unmod') {
          lines.push("  " + $(cells[inline ? 2 : 1]).text());
          oldLength += 1;
          newLength += 1;
          if (!oldOffset) oldOffset = oldLineNo;
          if (!newOffset) newOffset = newLineNo;
        } else {
          var oldLine;
          var newLine;
          if (inline) {
            oldLine = newLine = $(cells[2]).text();
          } else {
            oldLine = $(cells[1]).text();
            newLine = $(cells[3]).text();
          }
          if (!isNaN(oldLineNo)) {
            lines.push("- " + oldLine);
            oldLength += 1;
          }
          if (!isNaN(newLineNo)) {
            tmpLines.push("+ " + newLine);
            newLength += 1;
          }
        }
      }
      if (tmpLines.length > 0) {
        lines = lines.concat(tmpLines);
      }
    }

    if (!oldOffset && oldLength) oldOffset = 1
    if (!newOffset && newLength) newOffset = 1
    lines[sepIndex] = lines[sepIndex]
      .replace("{1}", oldOffset).replace("{2}", oldLength)
      .replace("{3}", newOffset).replace("{4}", newLength);

    return lines.join($.browser.msie ? "\r\n" : "\n");
  }

  $(document).ready(function($) {
    $("div.diff h2").each(function() {
      var switcher = $("").prependTo(this);
      var name = $.trim($(this).text());
      var table = $(this).siblings("table").get(0);
      if (! table) return;
      var pre = $("

").hide().insertAfter(table);
      $("Tabular").click(function() {
        $(pre).hide();
        $(table).show();
        $(this).addClass("active").siblings("span").removeClass("active");
        return false;
      }).addClass("active").appendTo(switcher);
      $("Unified").click(function() {
        $(table).hide();
        if (!pre.get(0).firstChild) pre.text(convertDiff(name, table));
        $(pre).fadeIn("fast")
        $(this).addClass("active").siblings("span").removeClass("active");
        return false;
      }).appendTo(switcher);
    });
  });

})(jQuery);
<|endoftext|>


<commit_before>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$('.dropdown-inverse li > a').click(function(e){
		    $('.status').text(this.innerHTML);
		});

		$(".dropdown-inverse li a").click( function() {
		    var yourText = $(this).text();
		    var temp = yourText.slice(0,1);
		    var duration = parseInt(duration, temp);
		});

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

		$scope.courts = [];

    $scope.initCourts = function(facId){
        console.log(facId);
        var url = '/courts/fac/'+facId;
        $http({method:'GET',url:url}).
            success(function(data,status){
                console.log(data);

            for(var x in data){
                $scope.courts.push(data[x]);

                 $('.courtBox').append(
                 	'
'+
                   	'
'+
							'
'+
								'
'+
      							''+
      							'
'+
        							'
'+
          								'
'+
                  							'
'+data[x].name+'
'+
                    					'
'+
                    				'
'+
                    			'
'+
                    			'
'+
                    				'
'+
                                    	'
'+
                                    		''+
                  						'
'+
                  					'
'+
                  				'
'+
		                  		'
'+
		                  			'
'+
		          						'
Availability
'+
		          						'
Time slots available
'+
		          					'
'+
		          				'
'+
	          				'
'+
	          			'
'+
	          		'
'+
          		'
');

                console.log(data[x].image);
            }
            console.log($scope.courts);
        });
    };

    console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
		$scope.court = {
			name: "",
			facId: "",
			image: "",
			id: ""
		}

 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];

		$scope.getCourts = function(){
			var path = '/courts/fac/' + $scope.court.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						$scope.courts =  data[0];
					}
				});
		}

		$scope.getCourt = function(){
			var path = '/courts/' + $scope.court.name;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var courtVals = data[0];
						$scope.court.name = courtVals.name;
						$scope.court.facId = courtVals.facId;
						$scope.court.image = courtVals.image;
					}
				});
		}

	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<commit_msg>angular<commit_after>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$('.dropdown-inverse li > a').click(function(e){
		    $('.status').text(this.innerHTML);
		});

		$(".dropdown-inverse li a").click( function() {
		    var yourText = $(this).text();
		    var temp = yourText.slice(0,1);
		    var duration = parseInt(duration, temp);
		});

		$('td').click(function(){
		  var col = $(this).parent().children().index($(this));
		  var row = $(this).parent().parent().children().index($(this).parent());
		  alert('Row: ' + row + ', Column: ' + col);
		});

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

		$scope.courts = [];

    $scope.initCourts = function(facId){
        console.log(facId);
        var url = '/courts/fac/'+facId;
        $http({method:'GET',url:url}).
            success(function(data,status){
                console.log(data);

            for(var x in data){
                $scope.courts.push(data[x]);

                 $('.courtBox').append(
                 	'
'+
                   	'
'+
							'
'+
								'
'+
      							''+
      							'
'+
        							'
'+
          								'
'+
                  							'
'+data[x].name+'
'+
                    					'
'+
                    				'
'+
                    			'
'+
                    			'
'+
                    				'
'+
                                    	'
'+
                                    		''+
                  						'
'+
                  					'
'+
                  				'
'+
		                  		'
'+
		                  			'
'+
		          						'
Availability
'+
		          						'
Time slots available
'+
		          					'
'+
		          				'
'+
	          				'
'+
	          			'
'+
	          		'
'+
          		'
');

                console.log(data[x].image);
            }
            console.log($scope.courts);
        });
    };

    console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
		$scope.court = {
			name: "",
			facId: "",
			image: "",
			id: ""
		}

 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];

		$scope.getCourts = function(){
			var path = '/courts/fac/' + $scope.court.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						$scope.courts =  data[0];
					}
				});
		}

		$scope.getCourt = function(){
			var path = '/courts/' + $scope.court.name;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var courtVals = data[0];
						$scope.court.name = courtVals.name;
						$scope.court.facId = courtVals.facId;
						$scope.court.image = courtVals.image;
					}
				});
		}

	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'

// Material UI
import RaisedButton from 'material-ui/RaisedButton'

// components
import Loading from '../Loading/Loading'

// actions
import { getCurrentUserRepositories } from '../../actions/repository-actions'

class Repositories extends Component {
  componentDidMount() {
    this.props.getCurrentUserRepositories()
  }
  render() {
    if (!this.props.repositories) {
      return <Loading />
    }
    return (

        {JSON.stringify(this.props.repositories)}

    )
  }
}

// Grab a reference to the current URL. If this is a web app and you are
// using React Router, you can use `ownProps` to find the URL. Other
// platforms (Native) or routing libraries have similar ways to find
// the current position in the app.

const mapStateToProps = (state, ownProps) => ({
  repositories: state.repository.current,
})

const mapDispatchToProps = (dispatch, ownProps) => ({
  getCurrentUserRepositories: parameters => dispatch(getCurrentUserRepositories(parameters))
})

export default connect(mapStateToProps, mapDispatchToProps)(Repositories)
<commit_msg>removed imported RaisedButton from Repositories<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'

// Material UI

// components
import Loading from '../Loading/Loading'

// actions
import { getCurrentUserRepositories } from '../../actions/repository-actions'

class Repositories extends Component {
  componentDidMount() {
    this.props.getCurrentUserRepositories()
  }
  render() {
    if (!this.props.repositories) {
      return <Loading />
    }
    return (

        {JSON.stringify(this.props.repositories)}

    )
  }
}

// Grab a reference to the current URL. If this is a web app and you are
// using React Router, you can use `ownProps` to find the URL. Other
// platforms (Native) or routing libraries have similar ways to find
// the current position in the app.

const mapStateToProps = (state, ownProps) => ({
  repositories: state.repository.current,
})

const mapDispatchToProps = (dispatch, ownProps) => ({
  getCurrentUserRepositories: parameters => dispatch(getCurrentUserRepositories(parameters))
})

export default connect(mapStateToProps, mapDispatchToProps)(Repositories)
<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var Property = require( 'AXON/Property' );
  var HSlider = require( 'SUN/HSlider' );
  var ABSwitch = require( 'SUN/ABSwitch' );
  var Text = require( 'SCENERY/nodes/Text' );

  var sun = require( 'SUN/sun' );

  function ComponentHolder( createFunction ) {
    var componentHolder = this;
    this.dispose = function() {
      componentHolder.instance.dispose();
    };
    this.create = function() {
      componentHolder.instance = createFunction();
    };
  }

  var numberProperty = new Property( 0 );
  var booleanProperty = new Property( false );

  var components = [
    new ComponentHolder( function() {
      return new HSlider( numberProperty, { min: 0, max: 10 } );
    } ),
    new ComponentHolder( function() {
      return new ABSwitch( booleanProperty, true, new Text( 'true' ), false, new Text( 'false' ) );
    } )
  ];

  function MemoryTestsView() {
    ScreenView.call( this );
  }

  sun.register( 'MemoryTestsView', MemoryTestsView );

  return inherit( ScreenView, MemoryTestsView, {
    step: function() {

      for ( var i = 0; i < components.length; i++ ) {
        var holder = components[ i ];

        // dispose first, then remove so they will be visible on the screen during animation.
        holder.instance && this.removeChild( holder.instance );
        holder.instance && holder.dispose();

        holder.create();
        this.addChild( holder.instance );
      }
      console.log( 'create' );
    }
  } );
} );<commit_msg>Updated docs, see https://github.com/phetsims/scenery-phet/issues/234<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var Property = require( 'AXON/Property' );
  var HSlider = require( 'SUN/HSlider' );
  var ABSwitch = require( 'SUN/ABSwitch' );
  var Text = require( 'SCENERY/nodes/Text' );

  var sun = require( 'SUN/sun' );

  function ComponentHolder( createFunction ) {
    var componentHolder = this;
    this.dispose = function() {
      componentHolder.instance.dispose();
    };
    this.create = function() {
      componentHolder.instance = createFunction();
    };
  }

  var numberProperty = new Property( 0 );
  var booleanProperty = new Property( false );

  var components = [
    new ComponentHolder( function() {
      return new HSlider( numberProperty, { min: 0, max: 10 } );
    } ),
    new ComponentHolder( function() {
      return new ABSwitch( booleanProperty, true, new Text( 'true' ), false, new Text( 'false' ) );
    } )
  ];

  function MemoryTestsView() {
    ScreenView.call( this );
  }

  sun.register( 'MemoryTestsView', MemoryTestsView );

  return inherit( ScreenView, MemoryTestsView, {
    step: function() {

      for ( var i = 0; i < components.length; i++ ) {
        var holder = components[ i ];

        // dispose first, then create and add at the end of the loop so components will be visible on the screen during
        // animation.
        holder.instance && this.removeChild( holder.instance );
        holder.instance && holder.dispose();

        holder.create();
        this.addChild( holder.instance );
      }
      console.log( 'create' );
    }
  } );
} );<|endoftext|>