<commit_before>'use strict';

var Substance = require('substance');
var _ = require('substance/helpers');
var $$ = React.createElement;
var AnnotationToolMixin = require("substance/writer").AnnotationToolMixin;

var SubjectReferenceToolMixin = _.extend({}, AnnotationToolMixin, {

  getAnnotationData: function() {
    return {
      container: "content",
      target: []
    }
  },

  // When there's no existing annotation overlapping, we create a new one.
  canCreate: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    return (writerCtrl.state.contextId !== "editSubjectReference" && !sel.isCollapsed());
  },

  getActiveAnno: function(annos) {
    var writerCtrl = this.props.writerCtrl;
    return _.filter(annos, function(a) {
      return a.id === writerCtrl.state.subjectReferenceId;
    })[0];
  },

  // When there's some overlap with only a single annotation we do an expand
  canExpand: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    if (annos.length === 0) return false;
    if (writerCtrl.state.contextId !== "editSubjectReference") return false;

    var activeAnno = this.getActiveAnno(annos);
    if (!activeAnno) return false;

    var annoSel = activeAnno.getSelection();

    return sel.overlaps(annoSel) && !sel.isCollapsed();
  },

  canFusion: function() {
    return false; // never ever
  },

  canRemove: function(annos, sel) {
    return false; // never through toggling
  },

  canTruncate: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    if (annos.length === 0) return false;
    if (writerCtrl.state.contextId !== "editSubjectReference") return false;

    var activeAnno = this.getActiveAnno(annos);
    if (!activeAnno) return false;
    var annoSel = activeAnno.getSelection();
    var canTruncate = (sel.isLeftAlignedWith(annoSel) || sel.isRightAlignedWith(annoSel)) && !sel.equals(annoSel);
    return canTruncate;
  },

  // Same implementation as on AnnotationTool, except we get the active
  // subjectReference id
  handleTruncate: function(state) {
    var doc = this.getDocument();
    var sel = state.sel;
    var tx = doc.startTransaction({ selection: sel });
    try {

      var anno = this.getActiveAnno(state.annos);
      if (!anno) return false;

      var annoSel = anno.getSelection(); // state.annoSels[0];
      var newAnnoSel = annoSel.truncate(sel);
      anno.updateRange(tx, newAnnoSel);
      tx.save({ selection: sel });
      this.afterTruncate();
    } finally {
      tx.cleanup();
    }
  },

  // Same implementation as on AnnotationTool, except we get the active
  // subjectReference id
  handleExpand: function(state) {
    var doc = this.getDocument();
    var sel = state.sel;
    var tx = doc.startTransaction({ selection: sel });
    try {
      var anno = this.getActiveAnno(state.annos);
      if (!anno) return false;
      var annoSel = anno.getSelection(); // state.annoSels[0];
      var newAnnoSel = annoSel.expand(sel);
      anno.updateRange(tx, newAnnoSel);
      tx.save({ selection: sel });
      this.afterExpand();
    } finally {
      tx.cleanup();
    }
  },

  disabledModes: ["remove", "fusion"],
  afterCreate: function(anno) {
    this.props.writerCtrl.replaceState({
      contextId: "editSubjectReference",
      subjectReferenceId: anno.id
    });
  }
});

var SubjectReferenceTool = React.createClass({
  mixins: [SubjectReferenceToolMixin],
  displayName: "SubjectReferenceTool",
  title: "Tag Subject",
  annotationType: "subject_reference",
  toolIcon: "fa-tag",
});

module.exports = SubjectReferenceTool;
<commit_msg>Fix TagSubjectTool.<commit_after>'use strict';

var Substance = require('substance');
var _ = require('substance/helpers');
var $$ = React.createElement;
var AnnotationToolMixin = require("substance/writer").AnnotationToolMixin;

var SubjectReferenceToolMixin = _.extend({}, AnnotationToolMixin, {

  getAnnotationData: function() {
    return {
      container: "content",
      target: []
    }
  },

  // When there's no existing annotation overlapping, we create a new one.
  canCreate: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    var canCreate = writerCtrl.state.contextId !== "editSubjectReference" && !sel.isCollapsed();
    console.log('canCreate', canCreate);
    return canCreate;
  },

  getActiveAnno: function(annos) {
    var writerCtrl = this.props.writerCtrl;
    return _.filter(annos, function(a) {
      return a.id === writerCtrl.state.subjectReferenceId;
    })[0];
  },

  // When there's some overlap with only a single annotation we do an expand
  canExpand: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    if (annos.length === 0) return false;
    if (writerCtrl.state.contextId !== "editSubjectReference") return false;

    var activeAnno = this.getActiveAnno(annos);
    if (!activeAnno) return false;

    var annoSel = activeAnno.getSelection();
    var canExpand = sel.overlaps(annoSel) && !sel.isCollapsed() && !sel.isInsideOf(annoSel);
    return canExpand;
  },

  canFusion: function() {
    return false; // never ever
  },

  canRemove: function(annos, sel) {
    return false; // never through toggling
  },

  canTruncate: function(annos, sel) {
    var writerCtrl = this.props.writerCtrl;
    if (annos.length === 0) return false;
    if (writerCtrl.state.contextId !== "editSubjectReference") return false;

    var activeAnno = this.getActiveAnno(annos);
    if (!activeAnno) return false;
    var annoSel = activeAnno.getSelection();
    var canTruncate = (sel.isLeftAlignedWith(annoSel) || sel.isRightAlignedWith(annoSel)) && !sel.equals(annoSel);
    console.log('canTruncate', canTruncate);
    return canTruncate;
  },

  // Same implementation as on AnnotationTool, except we get the active
  // subjectReference id
  handleTruncate: function(state) {
    var doc = this.getDocument();
    var sel = state.sel;
    var tx = doc.startTransaction({ selection: sel });
    try {

      var anno = this.getActiveAnno(state.annos);
      if (!anno) return false;

      var annoSel = anno.getSelection(); // state.annoSels[0];
      var newAnnoSel = annoSel.truncate(sel);
      anno.updateRange(tx, newAnnoSel);
      tx.save({ selection: sel });
      this.afterTruncate();
    } finally {
      tx.cleanup();
    }
  },

  // Same implementation as on AnnotationTool, except we get the active
  // subjectReference id
  handleExpand: function(state) {
    var doc = this.getDocument();
    var sel = state.sel;
    var tx = doc.startTransaction({ selection: sel });
    try {
      var anno = this.getActiveAnno(state.annos);
      if (!anno) return false;
      var annoSel = anno.getSelection(); // state.annoSels[0];
      var newAnnoSel = annoSel.expand(sel);
      anno.updateRange(tx, newAnnoSel);
      tx.save({ selection: sel });
      this.afterExpand();
    } finally {
      tx.cleanup();
    }
  },

  disabledModes: ["remove", "fusion"],
  afterCreate: function(anno) {
    this.props.writerCtrl.replaceState({
      contextId: "editSubjectReference",
      subjectReferenceId: anno.id
    });
  }
});

var SubjectReferenceTool = React.createClass({
  mixins: [SubjectReferenceToolMixin],
  displayName: "SubjectReferenceTool",
  title: "Tag Subject",
  annotationType: "subject_reference",
  toolIcon: "fa-tag",
});

module.exports = SubjectReferenceTool;
<|endoftext|>


<commit_before>
zeit.cms.declare_namespace('zeit.content.cp');

zeit.cms.in_cp_editor = function() {
    return Boolean(jQuery('.cp-editor-inner').length);
};

zeit.content.cp.LoadAndReloadWithConfirm = zeit.edit.LoadAndReload.extend({
    construct: function(context_element) {
        var self = this;
        if (confirm('Wirklich löschen?')) {
            arguments.callee.$.construct.call(self, context_element);
        }
    }
});

zeit.content.cp.BlockHover = gocept.Class.extend({

    construct: function() {
        var self = this;
        MochiKit.Signal.connect('cp-content', 'onmouseover', self, self.over);
        MochiKit.Signal.connect('cp-content', 'onmouseout', self, self.out);
    },

    over: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.addElementClass(block, 'hover');
        }
    },

    out: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.removeElementClass(block, 'hover');
        }
    },

    get_block: function(element) {
        var css_class = 'block';
        if (MochiKit.DOM.hasElementClass(element, css_class)) {
            return element;
        }
        return MochiKit.DOM.getFirstParentByTagAndClassName(
            element, null, css_class);
    }
});

MochiKit.Signal.connect(window, 'cp-editor-loaded', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }
    zeit.content.cp.block_hover = new zeit.content.cp.BlockHover();
});

zeit.content.cp.ContainerMover = gocept.Class.extend({

    construct: function(container_type) {
        var self = this;
        self.movers = [];
        self.container_type = container_type;
        self.selector = '.type-' + container_type;
        self.__name__ = ('zeit.content.cp.ContainerMover('
            + self.container_type + ')');
        new zeit.edit.context.Editor(self);
    },

    connect: function() {
        var self = this;
        jQuery(self.selector).each(function() {
            var mover = new zeit.edit.sortable.BlockMover(
                this.id, '#' + this.id + ' > div.block-inner');
            mover.__name__ = ('zeit.content.cp.BlockMover('
                + self.container_type + ', id=' + this.id + ')');
            self.movers.push(mover);
        });
    },

    disconnect: function() {
        var self = this;
        while (self.movers.length) {
            var mover = self.movers.pop();
            log("Destroying mover " + mover.container);
            mover.__context__.deactivate();
            mover.__context__.destroy();
        }
    }

});

var ident = MochiKit.Signal.connect(
    window, 'script-loading-finished', function() {
    MochiKit.Signal.disconnect(ident);
    if (! zeit.cms.in_cp_editor()) {
        return;
    }

    zeit.content.cp.body_mover = new zeit.edit.sortable.BlockMover(
        'body', '#body > div.block-inner');
    zeit.content.cp.body_mover.__name__ = (
        'zeit.content.cp.ContainerMover(body)');

    zeit.content.cp.region_mover = new zeit.content.cp.ContainerMover(
        'region');
    zeit.content.cp.area_mover = new zeit.content.cp.ContainerMover('area');
});

(function() {

    var added = function(id) {
        log('added');
        log('added ' + id);
        if (isNull($(id))) {
            log("Added but not found: " + id);
            return;
        }
        log('Added ' + id + $(id));
        MochiKit.Style.setOpacity($(id), 0.0);
        MochiKit.Visual.appear(id);
        MochiKit.Async.callLater(2, function() {
            $(id).style['opacity'] = 1;
        });
    };

    var deleted  = function(id) {
        log('Deleted ' + id + $(id));
        MochiKit.Visual.fade(id, {duration: 0.5,
                                  to: 0.01});
    };

    var ident = MochiKit.Signal.connect(
        window, 'script-loading-finished', function() {
        MochiKit.Signal.disconnect(ident);
            if (! zeit.cms.in_cp_editor()) {
                return;
            }
            MochiKit.Signal.connect(zeit.edit.editor, 'added', added);
            MochiKit.Signal.connect(zeit.edit.editor, 'deleted', deleted);
    });
}());
<commit_msg>Re DEV-53: Make regions sortable<commit_after>
zeit.cms.declare_namespace('zeit.content.cp');

zeit.cms.in_cp_editor = function() {
    return Boolean(jQuery('.cp-editor-inner').length);
};

zeit.content.cp.LoadAndReloadWithConfirm = zeit.edit.LoadAndReload.extend({
    construct: function(context_element) {
        var self = this;
        if (confirm('Wirklich löschen?')) {
            arguments.callee.$.construct.call(self, context_element);
        }
    }
});

zeit.content.cp.BlockHover = gocept.Class.extend({

    construct: function() {
        var self = this;
        MochiKit.Signal.connect('cp-content', 'onmouseover', self, self.over);
        MochiKit.Signal.connect('cp-content', 'onmouseout', self, self.out);
    },

    over: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.addElementClass(block, 'hover');
        }
    },

    out: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.removeElementClass(block, 'hover');
        }
    },

    get_block: function(element) {
        var css_class = 'block';
        if (MochiKit.DOM.hasElementClass(element, css_class)) {
            return element;
        }
        return MochiKit.DOM.getFirstParentByTagAndClassName(
            element, null, css_class);
    }
});

MochiKit.Signal.connect(window, 'cp-editor-loaded', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }
    zeit.content.cp.block_hover = new zeit.content.cp.BlockHover();
});

zeit.content.cp.ContainerMover = gocept.Class.extend({

    construct: function(container_type) {
        var self = this;
        self.movers = [];
        self.container_type = container_type;
        self.selector = '.type-' + container_type;
        self.__name__ = ('zeit.content.cp.ContainerMover('
            + self.container_type + ')');
        new zeit.edit.context.Editor(self);
    },

    connect: function() {
        var self = this;
        jQuery(self.selector).each(function() {
            var mover = new zeit.edit.sortable.BlockMover(
                this.id, '#' + this.id + ' > div.block-inner');
            mover.__name__ = ('zeit.content.cp.BlockMover('
                + self.container_type + ', id=' + this.id + ')');
            self.movers.push(mover);
        });
    },

    disconnect: function() {
        var self = this;
        while (self.movers.length) {
            var mover = self.movers.pop();
            log("Destroying mover " + mover.container);
            mover.__context__.deactivate();
            mover.__context__.destroy();
        }
    }

});

var ident = MochiKit.Signal.connect(
    window, 'script-loading-finished', function() {
    MochiKit.Signal.disconnect(ident);
    if (! zeit.cms.in_cp_editor()) {
        return;
    }

    zeit.content.cp.body_mover = new zeit.edit.sortable.BlockSorter(
        'body', '#body');
    zeit.content.cp.body_mover.__name__ = (
        'zeit.content.cp.ContainerMover(body)');

    zeit.content.cp.region_mover = new zeit.content.cp.ContainerMover(
        'region');
    zeit.content.cp.area_mover = new zeit.content.cp.ContainerMover('area');
});

(function() {

    var added = function(id) {
        log('added');
        log('added ' + id);
        if (isNull($(id))) {
            log("Added but not found: " + id);
            return;
        }
        log('Added ' + id + $(id));
        MochiKit.Style.setOpacity($(id), 0.0);
        MochiKit.Visual.appear(id);
        MochiKit.Async.callLater(2, function() {
            $(id).style['opacity'] = 1;
        });
    };

    var deleted  = function(id) {
        log('Deleted ' + id + $(id));
        MochiKit.Visual.fade(id, {duration: 0.5,
                                  to: 0.01});
    };

    var ident = MochiKit.Signal.connect(
        window, 'script-loading-finished', function() {
        MochiKit.Signal.disconnect(ident);
            if (! zeit.cms.in_cp_editor()) {
                return;
            }
            MochiKit.Signal.connect(zeit.edit.editor, 'added', added);
            MochiKit.Signal.connect(zeit.edit.editor, 'deleted', deleted);
    });
}());
<|endoftext|>


<commit_before>requirejs.config({
    paths: {
        leaflet: "/bower_components/leaflet-0.7.3/leaflet",
        jquery: "/bower_components/jquery/dist/jquery.min",
        q: "/bower_components/q/q"
    }
});

require(['leaflet', 'jquery'], function(leaflet, $) {
    "use strict";
    var attribution = "© 2014 ArenaNet, LLC. All rights reserved. NCSOFT, the interlocking NC logo, ArenaNet, Guild Wars, Guild Wars Factions, Guild Wars Nightfall, Guild Wars: Eye of the North, Guild Wars 2, and all associated logos and designs are trademarks or registered trademarks of NCSOFT Corporation. All other trademarks are the property of their respective owners.";
    var continents = $.getJSON("https://api.guildwars2.com/v1/continents.json");
    var floor = $.getJSON("https://api.guildwars2.com/v1/map_floor.json?continent_id=1&floor=1");
    var map_parts = $.getJSON("https://api.guildwars2.com/v1/maps.json");
    var realMaps = [15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 39, 50, 51, 53, 54, 62,
        65, 73, 91, 139, 326, 873, 988];
    //var falseMaps = [33, 38, 63, 66, 67, 70, 75, 81, 94, 95, 96, 111, 112, 211, 336, 350, 536, 549, 554, 698, 776, 795, 807, 864, 865, 872, 875, 877, 894, 897, 900, 918, 919, 929, 935, 936, 940, 955, 956, 957, 968, 984];

    continents.done(function(continents) {
        var selectedContinent = 1;
        var startFloor = 0;
        //continents.continents[selectedContinent].floors
        var baseLayers = {};
        [0,1,2,3].forEach(function(floor_id) {
            baseLayers[floor_id] = leaflet.tileLayer('https://tiles{s}.guildwars2.com/{continent}/{floor}/{z}/{x}/{y}.jpg', {
                attribution: attribution,
                minZoom: 2,
                maxZoom: 7,
                continuousWorld: true,
                subdomains: [1, 2, 3, 4 ],
                floor: floor_id,
                continent: selectedContinent,
                detectRetina: true
            });
        });
        var overlayLayers = {};
        overlayLayers['regions'] = leaflet.layerGroup();
        overlayLayers['zones'] = leaflet.layerGroup();

        var map = leaflet.map('map', {
            crs: leaflet.CRS.Simple,
            layers: [baseLayers[startFloor]]
        });

        leaflet.control.layers(baseLayers, overlayLayers).addTo(map);
        var boundaries = new leaflet.LatLngBounds(map.unproject([0, 32768], map.getMaxZoom()), map.unproject([32768, 0], map.getMaxZoom()));
        map.setView(map.unproject([32768/2, 32768/2], map.getMaxZoom()), 3);
        map.setMaxBounds(boundaries);

        //Draw Regions
        floor.done(function(floors) {
            $.each(floors.regions, function(id, region) {
                leaflet.marker(map.unproject([region.label_coord[0], region.label_coord[1]], map.getMaxZoom()), {
                    title: region.name
                }).bindPopup(region.name).addTo(overlayLayers['regions']);
            });
        });

        //Draw Zones
        map_parts.done(function(map_parts) {
            var already_drawn = {};
            $.each(map_parts.maps, function(id, map_part) {
                var xCoord = (map_part.continent_rect[0][0]+map_part.continent_rect[1][0]) / 2;
                var yCoord = (map_part.continent_rect[0][1]+map_part.continent_rect[1][1]) / 2;
                if(!already_drawn[xCoord+","+yCoord]) {
                    already_drawn[xCoord+","+yCoord] = true;
                    if(realMaps.indexOf(parseInt(id)) !== -1) {
                        leaflet.marker(map.unproject([xCoord, yCoord], map.getMaxZoom()), {
                            title: map_part.map_name + ", " + id
                        }).bindPopup(map_part.map_name + ", " + id).addTo(overlayLayers['zones']);
                    }
                }
            });
        })
    });
});
<commit_msg>Added sector markers.<commit_after>requirejs.config({
    paths: {
        leaflet: "/bower_components/leaflet-0.7.3/leaflet",
        jquery: "/bower_components/jquery/dist/jquery.min",
        q: "/bower_components/q/q"
    }
});

require(['leaflet', 'jquery'], function(leaflet, $) {
    "use strict";
    var attribution = "© 2014 ArenaNet, LLC. All rights reserved. NCSOFT, the interlocking NC logo, ArenaNet, Guild Wars, Guild Wars Factions, Guild Wars Nightfall, Guild Wars: Eye of the North, Guild Wars 2, and all associated logos and designs are trademarks or registered trademarks of NCSOFT Corporation. All other trademarks are the property of their respective owners.";
    var continents = $.getJSON("https://api.guildwars2.com/v1/continents.json");
    var floor = $.getJSON("https://api.guildwars2.com/v1/map_floor.json?continent_id=1&floor=1");
    var map_parts = $.getJSON("https://api.guildwars2.com/v1/maps.json");
    var realMaps = [15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 39, 50, 51, 53, 54, 62,
        65, 73, 91, 139, 326, 873, 988];
    //var falseMaps = [33, 38, 63, 66, 67, 70, 75, 81, 94, 95, 96, 111, 112, 211, 336, 350, 536, 549, 554, 698, 776, 795, 807, 864, 865, 872, 875, 877, 894, 897, 900, 918, 919, 929, 935, 936, 940, 955, 956, 957, 968, 984];

    continents.done(function(continents) {
        var selectedContinent = 1;
        var startFloor = 0;
        //continents.continents[selectedContinent].floors
        var baseLayers = {};
        [0,1,2,3].forEach(function(floor_id) {
            baseLayers[floor_id] = leaflet.tileLayer('https://tiles{s}.guildwars2.com/{continent}/{floor}/{z}/{x}/{y}.jpg', {
                attribution: attribution,
                minZoom: 2,
                maxZoom: 7,
                continuousWorld: true,
                subdomains: [1, 2, 3, 4 ],
                floor: floor_id,
                continent: selectedContinent,
                detectRetina: true
            });
        });
        var overlayLayers = {};
        overlayLayers['regions'] = leaflet.layerGroup();
        overlayLayers['zones'] = leaflet.layerGroup();
        overlayLayers['sectors'] = leaflet.layerGroup();

        var map = leaflet.map('map', {
            crs: leaflet.CRS.Simple,
            layers: [baseLayers[startFloor]]
        });

        leaflet.control.layers(baseLayers, overlayLayers).addTo(map);
        var boundaries = new leaflet.LatLngBounds(map.unproject([0, 32768], map.getMaxZoom()), map.unproject([32768, 0], map.getMaxZoom()));
        map.setView(map.unproject([32768/2, 32768/2], map.getMaxZoom()), 3);
        map.setMaxBounds(boundaries);

        //Draw Regions
        floor.done(function(floors) {
            $.each(floors.regions, function(id, region) {
                leaflet.marker(map.unproject([region.label_coord[0], region.label_coord[1]], map.getMaxZoom()), {
                    title: region.name
                }).bindPopup(region.name).addTo(overlayLayers['regions']);

                var already_drawn = {};
                $.each(region.maps, function(id, zone) {
                    var xCoord = (zone.continent_rect[0][0]+zone.continent_rect[1][0]) / 2;
                    var yCoord = (zone.continent_rect[0][1]+zone.continent_rect[1][1]) / 2;
                    if(!already_drawn[xCoord+","+yCoord]) {
                        already_drawn[xCoord+","+yCoord] = true;
                        if(realMaps.indexOf(parseInt(id)) !== -1) {
                            leaflet.marker(map.unproject([xCoord, yCoord], map.getMaxZoom()), {
                                title: zone.name
                            }).bindPopup(zone.name).addTo(overlayLayers['zones']);

                            $.each(zone.sectors, function(index, sector) {
                                leaflet.marker(map.unproject([sector.coord[0], sector.coord[1]], map.getMaxZoom()), {
                                    title: sector.name + " (" + sector.level + ")"
                                }).bindPopup(sector.name + " (" + sector.level + ")").addTo(overlayLayers['sectors']);
                            });
                        }
                    }
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/*
 * requirejs configuration file used to build the compiled/minified CDF js files.
 * Base on https://github.com/jrburke/r.js/blob/master/build/example.build.js
 */

({
  //The directory path to save the output. All relative paths are relative to the build file.
  dir: "../bin/scriptOutput",

  //By default, all modules are located relative to this path. If appDir is set, then
  //baseUrl should be specified as relative to the appDir.
  baseUrl: ".",

  //How to optimize all the JS files in the build output directory.
  optimize: "uglify2",

  //Allow CSS optimizations. Allowed values:
  //- "standard": @import inlining and removal of comments, unnecessary
  //whitespace and line returns.
  //Removing line returns may have problems in IE, depending on the type
  //of CSS.
  //- "standard.keepLines": like "standard" but keeps line returns.
  //- "none": skip CSS optimizations.
  //- "standard.keepComments": keeps the file comments, but removes line
  //returns.  (r.js 1.0.8+)
  //- "standard.keepComments.keepLines": keeps the file comments and line
  //returns. (r.js 1.0.8+)
  //- "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
  optimizeCss: "standard",

  //The top level directory that contains your app. If this option is used
  //then it assumed your scripts are in a subdirectory under this path.
  //If this option is specified, then all the files from the app directory
  //will be copied to the dir: output area, and baseUrl will assume to be
  //a relative path under this directory.
  appDir: "module-scripts",

  //Introduced in 2.1.3: Some situations do not throw and stop the optimizer
  //when an error occurs. However, you may want to have the optimizer stop
  //on certain kinds of errors and you can configure those situations via
  //this option
  throwWhen: {
    //If there is an error calling the minifier for some JavaScript,
    //instead of just skipping that file throw an error.
    optimize: true
  },

  //Set paths for modules. If relative paths, set relative to baseUrl above.
  //If a special value of "empty:" is used for the path value, then that
  //acts like mapping the path to an empty file. It allows the optimizer to
  //resolve the dependency to path, but then does not include it in the output.
  //Useful to map module names that are to resources on a CDN or other
  //http: URL when running in the browser and during an optimization that
  //file should be skipped because it has no dependencies.
  paths: {
    'requireLib': 'require',
    'common-ui': '../../js-lib/expanded/common-ui',
    'dojo': '../../js-lib/expanded/common-ui/dojo/dojo'
  },

  //By default all the configuration for optimization happens from the command
  //line or by properties in the config file, and configuration that was
  //passed to requirejs as part of the app's runtime "main" JS file is *not*
  //considered. However, if you prefer the "main" JS file configuration
  //to be read for the build so that you do not have to duplicate the values
  //in a separate configuration, set this property to the location of that
  //main JS file. The first requirejs({}), require({}), requirejs.config({}),
  //or require.config({}) call found in that file will be used.
  //As of 2.1.10, mainConfigFile can be an array of values, with the last
  //value's config take precedence over previous values in the array.
  mainConfigFile: 'requireCfg.js',

  //If using UglifyJS2 for script optimization, these config options can be
  //used to pass configuration values to UglifyJS2.
  //For possible `output` values see:
  //https://github.com/mishoo/UglifyJS2#beautifier-options
  //For possible `compress` values see:
  //https://github.com/mishoo/UglifyJS2#compressor-options
  uglify2: {
    output: {
      max_line_len: 80,
      beautify: false
    },
    warnings: true,
    mangle: true
  },

  //If set to true, any files that were combined into a build bundle will be
  //removed from the output folder.
  removeCombined: true,

  //By default, comments that have a license in them are preserved in the
  //output when a minifier is used in the "optimize" option.
  //However, for a larger built files there could be a lot of
  //comment files that may be better served by having a smaller comment
  //at the top of the file that points to the list of all the licenses.
  //This option will turn off the auto-preservation, but you will need
  //work out how best to surface the license information.
  //NOTE: As of 2.1.7, if using xpcshell to run the optimizer, it cannot
  //parse out comments since its native Reflect parser is used, and does
  //not have the same comments option support as esprima.
  preserveLicenseComments: false,

  //Introduced in 2.1.2 and considered experimental.
  //If the minifier specified in the "optimize" option supports generating
  //source maps for the minified code, then generate them. The source maps
  //generated only translate minified JS to non-minified JS, it does not do
  //anything magical for translating minified JS to transpiled source code.
  //Currently only optimize: "uglify2" is supported when running in node or
  //rhino, and if running in rhino, "closure" with a closure compiler jar
  //build after r1592 (20111114 release).
  //The source files will show up in a browser developer tool that supports
  //source maps as ".js.src" files.
  generateSourceMaps: false,

  //If you only intend to optimize a module (and its dependencies), with
  //a single file as the output, you can specify the module options inline,
  //instead of using the 'modules' section above. 'exclude',
  //'excludeShallow', 'include' and 'insertRequire' are all allowed as siblings
  //to name. The name of the optimized file is specified by 'out'.
  exclude: [
    'cdf/cdf-core-require-js-cfg',
    'cdf/cdf-pentaho-base-require-js-cfg',
    'cdf/cdf-pentaho-require-js-cfg',
    'cdf/lib/cdf-core-lib-require-js-cfg',
    //According to https://github.com/guybedford/require-css#basic-usage
    'cdf/lib/require-css/normalize'
  ],

  //Sets up a map of module IDs to other module IDs. For more details, see
  //the http://requirejs.org/docs/api.html#config-map docs.
  //map: {},

  //List the modules that will be optimized. All their immediate and deep
  //dependencies will be included in the module's file when the build is
  //done. If that module or any of its dependencies includes i18n bundles,
  //only the root bundles will be included unless the locale: section is set above.
  modules: [
    //Just specifying a module name means that module will be converted into
    //a built file that contains all of its dependencies. If that module or any
    //of its dependencies includes i18n bundles, they may not be included in the
    //built file unless the locale: section is set above.
    {
      name: "cdf/Dashboard.Blueprint",
      //create: true can be used to create the module layer at the given
      //name, if it does not already exist in the source location. If
      //there is a module at the source location with this name, then
      //create: true is superfluous.
      //create: true,

      //Also combines all the dependencies of the modules listed below
      //and any of their dependencies into one file.
      include: [ // all new
        'cdf/Dashboard',

        'cdf/dashboard/Container',
        'cdf/dashboard/Dashboard.addIns',
        'cdf/dashboard/Dashboard.bookmarkable',
        'cdf/dashboard/Dashboard.components',
        'cdf/dashboard/Dashboard.context',
        'cdf/dashboard/Dashboard.i18n',
        'cdf/dashboard/Dashboard',
        'cdf/dashboard/Dashboard.legacy',
        'cdf/dashboard/Dashboard.lifecycle',
        'cdf/dashboard/Dashboard.notifications',
        'cdf/dashboard/Dashboard.parameters',
        'cdf/dashboard/Dashboard.query',
        'cdf/dashboard/Dashboard.storage',
        'cdf/dashboard/Dashboard.views',
        'cdf/dashboard/OptionsManager',
        'cdf/dashboard/Popups',
        'cdf/dashboard/Query',
        'cdf/dashboard/RefreshEngine',
        'cdf/dashboard/Sprintf',
        'cdf/dashboard/Utf8Encoder',
        'cdf/dashboard/Utils',

        'cdf/Logger',

        "cdf/queries/BaseQuery",
        "cdf/queries/CdaQuery",
        "cdf/queries/CpkQuery",
        "cdf/queries/LegacyQuery"
      ],

      //Exclude the modules listed bellow and their dependencies from the built file. If you want
      //to exclude a module that is also another module being optimized, it is more
      //efficient if you define that module optimization entry before using it
      exclude: [
        // CSSs
        'css!cdf/Dashboard.css',
        'css!cdf/lib/cdf.css',
        'css!cdf/lib/blueprint/screen.css',
        "css!cdf/lib/impromptu/jquery-impromptu.css",
        "css!cdf/lib/theme/cupertino/jquery-ui-1.10.4.custom.css",

        //exclude core included jquery libs otherwise we will not able to use them without load issues
        'cdf/lib/jquery',
        'cdf/lib/jquery.ui',
        'cdf/lib/jquery.blockUI',
        'cdf/lib/jquery.impromptu',
        'cdf/lib/jquery.i18n',
        'cdf/lib/Base',
        "cdf/lib/underscore",
        "cdf/lib/backbone",
        "cdf/lib/shims",
        "cdf/lib/queryParser",
        "cdf/lib/mustache",
        "cdf/lib/cdf.jquery.i18n",
        "cdf/components/BaseComponent",
        "cdf/components/UnmanagedComponent",

        // Extensions might need to be accessed from a context other than Dashboard.Blueprint
        "cdf/components/XactionComponent.ext",
        "cdf/dashboard/Dashboard.ext",
        "cdf/dashboard/Dashboard.context.ext",
        "cdf/dashboard/Dashboard.storage.ext",
        "cdf/dashboard/Dashboard.views.ext",
        "cdf/queries/CdaQuery.ext"
      ]
    },
    {
      name: "cdf/Dashboard.Bootstrap",

      //Also combines all the dependencies of the modules listed below
      //and any of their dependencies into one file.
      include: [ // all new
        'cdf/Dashboard',

        'cdf/dashboard/Container',
        'cdf/dashboard/Dashboard.addIns',
        'cdf/dashboard/Dashboard.bookmarkable',
        'cdf/dashboard/Dashboard.components',
        'cdf/dashboard/Dashboard.context',
        'cdf/dashboard/Dashboard.i18n',
        'cdf/dashboard/Dashboard',
        'cdf/dashboard/Dashboard.legacy',
        'cdf/dashboard/Dashboard.lifecycle',
        'cdf/dashboard/Dashboard.notifications',
        'cdf/dashboard/Dashboard.parameters',
        'cdf/dashboard/Dashboard.query',
        'cdf/dashboard/Dashboard.storage',
        'cdf/dashboard/Dashboard.views',
        'cdf/dashboard/OptionsManager',
        'cdf/dashboard/Popups',
        'cdf/dashboard/Query',
        'cdf/dashboard/RefreshEngine',
        'cdf/dashboard/Sprintf',
        'cdf/dashboard/Utf8Encoder',
        'cdf/dashboard/Utils',

        'cdf/Logger',

        "cdf/queries/BaseQuery",
        "cdf/queries/CdaQuery",
        "cdf/queries/CpkQuery",
        "cdf/queries/LegacyQuery"
      ],

      //Exclude the modules listed bellow and their dependencies from the built file. If you want
      //to exclude a module that is also another module being optimized, it is more
      //efficient if you define that module optimization entry before using it
      exclude: [
        // CSSs
        'css!cdf/Dashboard.css',
        'css!cdf/lib/cdf.css',
        'css!cdf/lib/font-awesome/css/font-awesome.css',
        'css!cdf/lib/Bootstrap/css/bootstrap',
        "css!cdf/lib/impromptu/jquery-impromptu.css",
        "css!cdf/lib/theme/cupertino/jquery-ui-1.10.4.custom.css",

        //exclude core included jquery libs otherwise we will not able to use them without load issues
        'cdf/lib/jquery',
        'cdf/lib/jquery.ui',
        'cdf/lib/jquery.blockUI',
        'cdf/lib/jquery.impromptu',
        'cdf/lib/jquery.i18n',
        'cdf/lib/Base',
        "cdf/lib/underscore",
        "cdf/lib/backbone",
        "cdf/lib/shims",
        "cdf/lib/queryParser",
        "cdf/lib/mustache",
        "cdf/lib/cdf.jquery.i18n",
        "cdf/dashboard/Dashboard.ext",
        "cdf/components/BaseComponent",
        "cdf/components/UnmanagedComponent",

        // Extensions might need to be accessed from a context other than Dashboard.Bootstrap
        "cdf/components/XactionComponent.ext",
        "cdf/dashboard/Dashboard.ext",
        "cdf/dashboard/Dashboard.context.ext",
        "cdf/dashboard/Dashboard.storage.ext",
        "cdf/dashboard/Dashboard.views.ext",
        "cdf/queries/CdaQuery.ext"
      ]
    }
  ]
})
<commit_msg>[CDF-334] - Compilation / Minification 	- jQuery needs to be loaded before Bootstrap, fix load issue by adding bootstrap libs to the (compression) exclude list 	- Avoid compressing Sprintf, Utils and Utf8Encoder because they need to be accessible to other AMD modules (e.g. AddIns) that don't depend on a main dashboard module (e.g. Dashboard.Blueprint)<commit_after>/*
 * requirejs configuration file used to build the compiled/minified CDF js files.
 * Based on https://github.com/jrburke/r.js/blob/master/build/example.build.js
 */

({
  //The directory path to save the output. All relative paths are relative to the build file.
  dir: "../bin/scriptOutput",

  //By default, all modules are located relative to this path. If appDir is set, then
  //baseUrl should be specified as relative to the appDir.
  baseUrl: ".",

  //How to optimize all the JS files in the build output directory.
  optimize: "uglify2",

  //Allow CSS optimizations. Allowed values:
  //- "standard": @import inlining and removal of comments, unnecessary
  //whitespace and line returns.
  //Removing line returns may have problems in IE, depending on the type
  //of CSS.
  //- "standard.keepLines": like "standard" but keeps line returns.
  //- "none": skip CSS optimizations.
  //- "standard.keepComments": keeps the file comments, but removes line
  //returns.  (r.js 1.0.8+)
  //- "standard.keepComments.keepLines": keeps the file comments and line
  //returns. (r.js 1.0.8+)
  //- "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
  optimizeCss: "standard",

  //The top level directory that contains your app. If this option is used
  //then it assumed your scripts are in a subdirectory under this path.
  //If this option is specified, then all the files from the app directory
  //will be copied to the dir: output area, and baseUrl will assume to be
  //a relative path under this directory.
  appDir: "module-scripts",

  //Introduced in 2.1.3: Some situations do not throw and stop the optimizer
  //when an error occurs. However, you may want to have the optimizer stop
  //on certain kinds of errors and you can configure those situations via
  //this option
  throwWhen: {
    //If there is an error calling the minifier for some JavaScript,
    //instead of just skipping that file throw an error.
    optimize: true
  },

  //Set paths for modules. If relative paths, set relative to baseUrl above.
  //If a special value of "empty:" is used for the path value, then that
  //acts like mapping the path to an empty file. It allows the optimizer to
  //resolve the dependency to path, but then does not include it in the output.
  //Useful to map module names that are to resources on a CDN or other
  //http: URL when running in the browser and during an optimization that
  //file should be skipped because it has no dependencies.
  paths: {
    'requireLib': 'require',
    'common-ui': '../../js-lib/expanded/common-ui',
    'dojo': '../../js-lib/expanded/common-ui/dojo/dojo'
  },

  //By default all the configuration for optimization happens from the command
  //line or by properties in the config file, and configuration that was
  //passed to requirejs as part of the app's runtime "main" JS file is *not*
  //considered. However, if you prefer the "main" JS file configuration
  //to be read for the build so that you do not have to duplicate the values
  //in a separate configuration, set this property to the location of that
  //main JS file. The first requirejs({}), require({}), requirejs.config({}),
  //or require.config({}) call found in that file will be used.
  //As of 2.1.10, mainConfigFile can be an array of values, with the last
  //value's config take precedence over previous values in the array.
  mainConfigFile: 'requireCfg.js',

  //If using UglifyJS2 for script optimization, these config options can be
  //used to pass configuration values to UglifyJS2.
  //For possible `output` values see:
  //https://github.com/mishoo/UglifyJS2#beautifier-options
  //For possible `compress` values see:
  //https://github.com/mishoo/UglifyJS2#compressor-options
  uglify2: {
    output: {
      max_line_len: 80,
      beautify: false
    },
    warnings: true,
    mangle: true
  },

  //If set to true, any files that were combined into a build bundle will be
  //removed from the output folder.
  removeCombined: true,

  //By default, comments that have a license in them are preserved in the
  //output when a minifier is used in the "optimize" option.
  //However, for a larger built files there could be a lot of
  //comment files that may be better served by having a smaller comment
  //at the top of the file that points to the list of all the licenses.
  //This option will turn off the auto-preservation, but you will need
  //work out how best to surface the license information.
  //NOTE: As of 2.1.7, if using xpcshell to run the optimizer, it cannot
  //parse out comments since its native Reflect parser is used, and does
  //not have the same comments option support as esprima.
  preserveLicenseComments: false,

  //Introduced in 2.1.2 and considered experimental.
  //If the minifier specified in the "optimize" option supports generating
  //source maps for the minified code, then generate them. The source maps
  //generated only translate minified JS to non-minified JS, it does not do
  //anything magical for translating minified JS to transpiled source code.
  //Currently only optimize: "uglify2" is supported when running in node or
  //rhino, and if running in rhino, "closure" with a closure compiler jar
  //build after r1592 (20111114 release).
  //The source files will show up in a browser developer tool that supports
  //source maps as ".js.src" files.
  generateSourceMaps: false,

  //If you only intend to optimize a module (and its dependencies), with
  //a single file as the output, you can specify the module options inline,
  //instead of using the 'modules' section above. 'exclude',
  //'excludeShallow', 'include' and 'insertRequire' are all allowed as siblings
  //to name. The name of the optimized file is specified by 'out'.
  exclude: [
    'cdf/cdf-core-require-js-cfg',
    'cdf/cdf-pentaho-base-require-js-cfg',
    'cdf/cdf-pentaho-require-js-cfg',
    'cdf/lib/cdf-core-lib-require-js-cfg',
    //According to https://github.com/guybedford/require-css#basic-usage
    'cdf/lib/require-css/normalize'
  ],

  //Sets up a map of module IDs to other module IDs. For more details, see
  //the http://requirejs.org/docs/api.html#config-map docs.
  //map: {},

  //List the modules that will be optimized. All their immediate and deep
  //dependencies will be included in the module's file when the build is
  //done. If that module or any of its dependencies includes i18n bundles,
  //only the root bundles will be included unless the locale: section is set above.
  modules: [
    //Just specifying a module name means that module will be converted into
    //a built file that contains all of its dependencies. If that module or any
    //of its dependencies includes i18n bundles, they may not be included in the
    //built file unless the locale: section is set above.
    {
      name: "cdf/Dashboard.Blueprint",
      //create: true can be used to create the module layer at the given
      //name, if it does not already exist in the source location. If
      //there is a module at the source location with this name, then
      //create: true is superfluous.
      //create: true,

      //Also combines all the dependencies of the modules listed below
      //and any of their dependencies into one file.
      include: [
        'cdf/Dashboard',

        'cdf/dashboard/Container',
        'cdf/dashboard/Dashboard.addIns',
        'cdf/dashboard/Dashboard.bookmarkable',
        'cdf/dashboard/Dashboard.components',
        'cdf/dashboard/Dashboard.context',
        'cdf/dashboard/Dashboard.i18n',
        'cdf/dashboard/Dashboard',
        'cdf/dashboard/Dashboard.legacy',
        'cdf/dashboard/Dashboard.lifecycle',
        'cdf/dashboard/Dashboard.notifications',
        'cdf/dashboard/Dashboard.parameters',
        'cdf/dashboard/Dashboard.query',
        'cdf/dashboard/Dashboard.storage',
        'cdf/dashboard/Dashboard.views',
        'cdf/dashboard/OptionsManager',
        'cdf/dashboard/Popups',
        'cdf/dashboard/Query',
        'cdf/dashboard/RefreshEngine',

        'cdf/Logger',

        "cdf/queries/BaseQuery",
        "cdf/queries/CdaQuery",
        "cdf/queries/CpkQuery",
        "cdf/queries/LegacyQuery"
      ],

      //Exclude the modules listed bellow and their dependencies from the built file. If you want
      //to exclude a module that is also another module being optimized, it is more
      //efficient if you define that module optimization entry before using it
      exclude: [
        // CSSs
        'css!cdf/Dashboard',
        'css!cdf/lib/cdf',
        'css!cdf/lib/blueprint/screen',
        "css!cdf/lib/impromptu/jquery-impromptu",
        "css!cdf/lib/theme/cupertino/jquery-ui-1.10.4.custom",

        //exclude core included jquery libs otherwise we will not be able to use them without load issues
        'cdf/lib/jquery',
        'cdf/lib/jquery.ui',
        'cdf/lib/jquery.blockUI',
        'cdf/lib/jquery.impromptu',
        'cdf/lib/jquery.i18n',
        'cdf/lib/Base',
        "cdf/lib/underscore",
        "cdf/lib/backbone",
        "cdf/lib/shims",
        "cdf/lib/queryParser",
        "cdf/lib/mustache",
        "cdf/lib/cdf.jquery.i18n",

        //files that need to be accessible to other AMD modules (e.g. addIns)
        "cdf/components/BaseComponent",
        "cdf/components/UnmanagedComponent",
        "cdf/dashboard/Sprintf",
        "cdf/dashboard/Utils",
        "cdf/dashboard/Utf8Encoder",

        // Extensions might need to be accessed from a context other than Dashboard.Blueprint
        "cdf/components/XactionComponent.ext",
        "cdf/dashboard/Dashboard.ext",
        "cdf/dashboard/Dashboard.context.ext",
        "cdf/dashboard/Dashboard.storage.ext",
        "cdf/dashboard/Dashboard.views.ext",
        "cdf/queries/CdaQuery.ext"
      ]
    },
    {
      name: "cdf/Dashboard.Bootstrap",

      //Also combines all the dependencies of the modules listed below
      //and any of their dependencies into one file.
      include: [
        'cdf/Dashboard',

        'cdf/dashboard/Container',
        'cdf/dashboard/Dashboard.addIns',
        'cdf/dashboard/Dashboard.bookmarkable',
        'cdf/dashboard/Dashboard.components',
        'cdf/dashboard/Dashboard.context',
        'cdf/dashboard/Dashboard.i18n',
        'cdf/dashboard/Dashboard',
        'cdf/dashboard/Dashboard.legacy',
        'cdf/dashboard/Dashboard.lifecycle',
        'cdf/dashboard/Dashboard.notifications',
        'cdf/dashboard/Dashboard.parameters',
        'cdf/dashboard/Dashboard.query',
        'cdf/dashboard/Dashboard.storage',
        'cdf/dashboard/Dashboard.views',
        'cdf/dashboard/OptionsManager',
        'cdf/dashboard/Popups',
        'cdf/dashboard/Query',
        'cdf/dashboard/RefreshEngine',

        'cdf/Logger',

        "cdf/queries/BaseQuery",
        "cdf/queries/CdaQuery",
        "cdf/queries/CpkQuery",
        "cdf/queries/LegacyQuery"
      ],

      //Exclude the modules listed bellow and their dependencies from the built file. If you want
      //to exclude a module that is also another module being optimized, it is more
      //efficient if you define that module optimization entry before using it
      exclude: [
        // CSSs
        "css!cdf/Dashboard",
        "css!cdf/lib/cdf",
        "css!cdf/lib/Bootstrap/css/bootstrap",
        "css!cdf/lib/font-awesome/css/font-awesome",
        "css!cdf/lib/impromptu/jquery-impromptu",
        "css!cdf/lib/theme/cupertino/jquery-ui-1.10.4.custom",

        //exclude core included jquery libs otherwise we will not be able to use them without load issues
        "cdf/lib/jquery",
        "cdf/lib/jquery.ui",
        "cdf/lib/jquery.blockUI",
        "cdf/lib/jquery.impromptu",
        "cdf/lib/jquery.i18n",
        "cdf/lib/Base",
        "cdf/lib/underscore",
        "cdf/lib/backbone",
        "cdf/lib/shims",
        "cdf/lib/queryParser",
        "cdf/lib/mustache",
        "cdf/lib/cdf.jquery.i18n",

        "cdf/lib/bootstrap",
        "cdf/lib/html5shiv",
        "cdf/lib/respond",

        //files that need to be accessible to other AMD modules (e.g. addIns)
        "cdf/components/BaseComponent",
        "cdf/components/UnmanagedComponent",
        "cdf/dashboard/Sprintf",
        "cdf/dashboard/Utils",
        "cdf/dashboard/Utf8Encoder",

        // Extensions might need to be accessed from a context other than Dashboard.Bootstrap
        "cdf/dashboard/Dashboard.ext",
        "cdf/components/XactionComponent.ext",
        "cdf/dashboard/Dashboard.ext",
        "cdf/dashboard/Dashboard.context.ext",
        "cdf/dashboard/Dashboard.storage.ext",
        "cdf/dashboard/Dashboard.views.ext",
        "cdf/queries/CdaQuery.ext"
      ]
    }
  ]
})
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
define([
  'i18nObj',
  'jquery' /* $ */,
  'jquery.instructure_date_and_time' /* datepicker */,
  'jquery.templateData' /* fillTemplateData */,
  'jqueryui/datepicker' /* /\.datepicker/ */
], function(I18n, $) {

  var monthNames = I18n.lookup('date.month_names');

  function makeDate(date) {
    return {
      day: date.getDate(),
      month: date.getMonth(),
      year: date.getFullYear()
    }
  }

  return {
    changeMonth: function($month, change) {
      var monthData = $month.data('calendar_objects');
      var data = {};
      var current = null;
      if(typeof(change) == "string") {
        var current = $.datepicker.parseDate('mm/dd/yy', change);
        if(current) {
          current.setDate(1);
        }
      }
      if(!current) {
        var month = parseInt($month.find(".month_number").text(), 10);
        var year = parseInt($month.find(".year_number").text(), 10);
        var current = new Date(year, month + change - 1, 1);
      }
      var data = {
        month_name: monthNames[current.getMonth() + 1],
        month_number: current.getMonth() + 1,
        year_number: current.getFullYear()
      };
      $month.fillTemplateData({data: data});
      var date = new Date();
      var today = makeDate(date);
      var firstDayOfMonth = makeDate(current);
      date = current;
      date.setDate(0);
      date.setDate(date.getDate() - date.getDay());
      var firstDayOfSquare = makeDate(date);
      var lastDayOfPreviousMonth = null;
      if(firstDayOfMonth.day != firstDayOfSquare.day) {
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
        date.setDate(0);
        lastDayOfPreviousMonth = {
          day: date.getDate(),
          month: firstDayOfSquare.month,
          year: firstDayOfSquare.year
        }
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
      }
      date.setMonth(current.getMonth() + 1);
      date.setDate(0);
      var lastDayOfMonth = {
        day: date.getDate(),
        month: firstDayOfMonth.month,
        year: firstDayOfMonth.yearh
      }
      date.setDate(date.getDate() + 1);
      date.setDate(date.getDate() + (6 - date.getDay()));
      date.setDate(date.getDate() + 7);
      var lastDayOfSquare = makeDate(date);
      var $days = $month.data("days");
      if(!$days) {
        $days = $month.find(".calendar_day_holder");
        $month.data("days", $days);
      }
      if($month.hasClass('mini_month')) {
        $days = $month.find(".day");
      }
      $month.find(".calendar_event").remove();
      var idx = 0;
      var day = firstDayOfSquare.day;
      var month = firstDayOfSquare.month;
      var year = firstDayOfSquare.year;
      while(day <= lastDayOfSquare.day || month != lastDayOfSquare.month) {
        var $day = $days.eq(idx);
        if($day.length > 0) {
          var classes = $day.attr('class').split(" ");
          var class_names = [];
          for(var i = 0; i < classes.length; i++) {
            if(classes[i].indexOf('date_') == 0) {
            } else {
              class_names.push(classes[i]);
            }
          }
          $day.attr('class', class_names.join(" "));
        }
        $day.show().addClass('visible').parents("tr").show().addClass('visible');
        var data = {
          day_number: day
        }
        var month_number = month < 9 ? "0" + (month + 1) : (month + 1);
        var day_number = day < 10 ? "0" + day : day;
        id = "day_" + year + "_" + month_number + "_" + day_number
        if($month.hasClass('mini_month')) {
          id = "mini_" + id;
        }
        $day.attr('id', id)
          .addClass("date_" + month_number + "_" + day_number + "_" + year)
          .find(".day_number").text(day).attr('title', month_number + "/" + day_number + "/" + year)
          .addClass("date_" + month_number + "_" + day_number + "_" + year); // left here because I don't know what it'll break...
        var $div = $day.children('div');
        if($month.hasClass('mini_month')) {
          $div = $day;
        }
        $div.removeClass('current_month other_month today');
        if(month == firstDayOfMonth.month) {
          $div.addClass('current_month');
        } else {
          $div.addClass('other_month');
        }
        if(month == today.month && day == today.day && year == today.year) {
          $div.addClass('today');
        }
        day++;
        idx++;
        if((lastDayOfPreviousMonth && day > lastDayOfPreviousMonth.day && month == lastDayOfPreviousMonth.month)
              || (day > lastDayOfMonth.day && month == lastDayOfMonth.month)) {
          month = month + 1;
          if(month >= 12) {
            month -= 12;
            year++;
          }
          day = 1;
        }
      }
      while(idx < $days.length) {
        var $day = $days.eq(idx);
        $day.parents("tr").hide().removeClass('visible');
        $day.hide().removeClass('visible');
        idx++;
      }
      if(!$month.hasClass('mini_month')) {
      }
    }
  };
});
<commit_msg>fix potential m/d/y vs. d/m/y bug<commit_after>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
define([
  'i18nObj',
  'jquery' /* $ */,
  'jquery.instructure_date_and_time' /* datepicker */,
  'jquery.templateData' /* fillTemplateData */,
  'jqueryui/datepicker' /* /\.datepicker/ */
], function(I18n, $) {

  var monthNames = I18n.lookup('date.month_names');

  function makeDate(date) {
    return {
      day: date.getDate(),
      month: date.getMonth(),
      year: date.getFullYear()
    }
  }

  return {
    changeMonth: function($month, change) {
      var monthData = $month.data('calendar_objects');
      var data = {};
      var current = null;
      if(typeof(change) == "string") {
        var current = $.datepicker.oldParseDate('mm/dd/yy', change);
        if(current) {
          current.setDate(1);
        }
      }
      if(!current) {
        var month = parseInt($month.find(".month_number").text(), 10);
        var year = parseInt($month.find(".year_number").text(), 10);
        var current = new Date(year, month + change - 1, 1);
      }
      var data = {
        month_name: monthNames[current.getMonth() + 1],
        month_number: current.getMonth() + 1,
        year_number: current.getFullYear()
      };
      $month.fillTemplateData({data: data});
      var date = new Date();
      var today = makeDate(date);
      var firstDayOfMonth = makeDate(current);
      date = current;
      date.setDate(0);
      date.setDate(date.getDate() - date.getDay());
      var firstDayOfSquare = makeDate(date);
      var lastDayOfPreviousMonth = null;
      if(firstDayOfMonth.day != firstDayOfSquare.day) {
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
        date.setDate(0);
        lastDayOfPreviousMonth = {
          day: date.getDate(),
          month: firstDayOfSquare.month,
          year: firstDayOfSquare.year
        }
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
      }
      date.setMonth(current.getMonth() + 1);
      date.setDate(0);
      var lastDayOfMonth = {
        day: date.getDate(),
        month: firstDayOfMonth.month,
        year: firstDayOfMonth.yearh
      }
      date.setDate(date.getDate() + 1);
      date.setDate(date.getDate() + (6 - date.getDay()));
      date.setDate(date.getDate() + 7);
      var lastDayOfSquare = makeDate(date);
      var $days = $month.data("days");
      if(!$days) {
        $days = $month.find(".calendar_day_holder");
        $month.data("days", $days);
      }
      if($month.hasClass('mini_month')) {
        $days = $month.find(".day");
      }
      $month.find(".calendar_event").remove();
      var idx = 0;
      var day = firstDayOfSquare.day;
      var month = firstDayOfSquare.month;
      var year = firstDayOfSquare.year;
      while(day <= lastDayOfSquare.day || month != lastDayOfSquare.month) {
        var $day = $days.eq(idx);
        if($day.length > 0) {
          var classes = $day.attr('class').split(" ");
          var class_names = [];
          for(var i = 0; i < classes.length; i++) {
            if(classes[i].indexOf('date_') == 0) {
            } else {
              class_names.push(classes[i]);
            }
          }
          $day.attr('class', class_names.join(" "));
        }
        $day.show().addClass('visible').parents("tr").show().addClass('visible');
        var data = {
          day_number: day
        }
        var month_number = month < 9 ? "0" + (month + 1) : (month + 1);
        var day_number = day < 10 ? "0" + day : day;
        id = "day_" + year + "_" + month_number + "_" + day_number
        if($month.hasClass('mini_month')) {
          id = "mini_" + id;
        }
        $day.attr('id', id)
          .addClass("date_" + month_number + "_" + day_number + "_" + year)
          .find(".day_number").text(day).attr('title', month_number + "/" + day_number + "/" + year)
          .addClass("date_" + month_number + "_" + day_number + "_" + year); // left here because I don't know what it'll break...
        var $div = $day.children('div');
        if($month.hasClass('mini_month')) {
          $div = $day;
        }
        $div.removeClass('current_month other_month today');
        if(month == firstDayOfMonth.month) {
          $div.addClass('current_month');
        } else {
          $div.addClass('other_month');
        }
        if(month == today.month && day == today.day && year == today.year) {
          $div.addClass('today');
        }
        day++;
        idx++;
        if((lastDayOfPreviousMonth && day > lastDayOfPreviousMonth.day && month == lastDayOfPreviousMonth.month)
              || (day > lastDayOfMonth.day && month == lastDayOfMonth.month)) {
          month = month + 1;
          if(month >= 12) {
            month -= 12;
            year++;
          }
          day = 1;
        }
      }
      while(idx < $days.length) {
        var $day = $days.eq(idx);
        $day.parents("tr").hide().removeClass('visible');
        $day.hide().removeClass('visible');
        idx++;
      }
      if(!$month.hasClass('mini_month')) {
      }
    }
  };
});
<|endoftext|>


<commit_before>var defaults = {};

$(document).ready(function() {
    $(document).ready(function() {
        $( "button" ).attr('disabled', 'disabled');
        $('#configuration input[type=text].form-control').each(function (i) {
            defaults[$(this).attr('id')] = $(this).val()
        })

        $('#configuration input[type=text].form-control').keyup(function(){
            if ($(this).val() == defaults[$(this).attr('id')]){
                $( "button" ).attr('disabled', 'disabled');
            }
            else{
                $( "button" ).removeAttr( "disabled" )
            }
        })
    })
})

function save_configuration(){
    changed_config ={}
    i = 0
    $('#configuration input[type=text].form-control').each(function (i) {
        if ($(this).val() != defaults[$(this).attr('id')]){
            changed_config[$(this).attr('id')] = ($(this).val())
        }
        if ($('#configuration input[type=text].form-control').length-1 == i){
            $.post("configuration_change/"+$('ul.nav-tabs li.active').attr( "id"), changed_config)
                .done(function(data){
                    if (data == "set"){
                        alert("All OK")
                    }
                    else{
                        alert("An error occoured! " + data)
                    }
                })
        }
        else{
            i++
        }
    })
}

function change_active(tab){
    //alert(tab)
    activetab = $('ul.nav-tabs li.active').attr( "id")
    $('ul.nav-tabs li').each(function(){
        $("#"+[$(this).attr('id')]+"_values").removeClass("active")
        $("#"+[$(this).attr('id')]+"_values").addClass("hide")
    })
    $("#"+tab+"_values").removeClass("hide")
    $("#"+tab+"_values").addClass("active")
    $("#save_changes").attr("onclick",tab)
}<commit_msg>Delete configuration.js<commit_after><|endoftext|>


<commit_before>/*******************************************************************************
* Copyright (c) 2014 IBM Corporation and other Contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial Contribution
*******************************************************************************/

var RealtimeGraph = function(){

	var palette = new Rickshaw.Color.Palette( { scheme: [
        "#7f1c7d",
 		"#00b2ef",
		"#00649d",
		"#00a6a0",
		"#ee3e96",
		"#FF6600",
		"#33CC33",
		"#996633",
		"#00FFFF",
		"#FFFF00",
		"#999966",
		"#003300",
		"#CC0000",
		"#993333",
		"#009933"

    ] } );

	// function to invoke Rickshaw and plot the graph
	this.drawGraph = function(seriesData)
	{
		// instantiate our graph!
		this.palette = palette;
		if(document.getElementById("chart") != null){
			this.graph = new Rickshaw.Graph( {
				element: document.getElementById("chart"),
				width: 600,
				height: 250,
				renderer: 'line',
				stroke: true,
				preserve: true,
				series: seriesData
			} );
		}else{
			return null;
		}

		this.graph.render();

		this.hoverDetail = new Rickshaw.Graph.HoverDetail( {
			graph: this.graph,
			xFormatter: function(x) {
				return new Date(x * 1000).toString();
			}
		} );

		this.annotator = new Rickshaw.Graph.Annotate( {
			graph: this.graph,
			element: document.getElementById('timeline')
		} );

		this.legend = new Rickshaw.Graph.Legend( {
			graph: this.graph,
			element: document.getElementById('legend')

		} );

		this.shelving = new Rickshaw.Graph.Behavior.Series.Toggle( {
			graph: this.graph,
			legend: this.legend
		} );

		this.order = new Rickshaw.Graph.Behavior.Series.Order( {
			graph: this.graph,
			legend: this.legend
		} );

		this.highlighter = new Rickshaw.Graph.Behavior.Series.Highlight( {
			graph: this.graph,
			legend: this.legend
		} );

		this.smoother = new Rickshaw.Graph.Smoother( {
			graph: this.graph,
			element: document.querySelector('#smoother')
		} );

		this.ticksTreatment = 'glow';

		this.xAxis = new Rickshaw.Graph.Axis.Time( {
			graph: this.graph,
			ticksTreatment: this.ticksTreatment,
			timeFixture: new Rickshaw.Fixtures.Time.Local()
		} );

		this.xAxis.render();

		this.yAxis = new Rickshaw.Graph.Axis.Y( {
			graph: this.graph,
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
			ticksTreatment: this.ticksTreatment
		} );

		this.yAxis.render();

		this.controls = new RenderControls( {
			element: document.querySelector('form'),
			graph: this.graph
		} );

	}

	this.updateVal = function(data)
	{
		var i=0;
		var v=0;
		for (var j in data.d)
		{
			if (typeof data.d[j] !== 'string') {
				if((j == 'Loudness') && (document.getElementById('loudness')!= null)){
					document.getElementById('loudness').innerHTML = Math.round(data.d[j] *100) +" %";
				}else if((j == 'Power') && (document.getElementById('power') != null)){
					document.getElementById('power').innerHTML = data.d[j];
				}else if((j == 'Light') && (document.getElementById('light') != null )){
					document.getElementById('light').innerHTML = Math.round(data.d[j]*100) +" %";
				}else if((j == 'Motion') && (document.getElementById('motion') != null)){
					//document.getElementById('motion').innerHTML = data.d[j];
					if(document.getElementById('motion-text') != null){
						if(data.d[j] == 0){
							document.getElementById('motion').className = "fa fa-male fa-5x";
							document.getElementById('motion-text').innerHTML = "No detected presence";
						} else {
							document.getElementById('motion').className = "fa fa-child fa-5x";
							document.getElementById('motion-text').innerHTML = "Detected presence";
						}
					}else{
						document.getElementById('motion').innerHTML = data.d[j];
					}

				}else if((j == 'v_bat') || (j == 'State')) {
					if(document.getElementById('voltage_b') != null ){ //home page
						if(j == 'v_bat'){
							document.getElementById('voltage_b').innerHTML = (data.d[j]/1000)*3;
						}

					}
					if(document.getElementById('charge') != null ){ // Energy production page
						if(j == 'v_bat'){
							document.getElementById('charge').innerHTML = (((data.d[j]/1000)*3)*100)/27;
						}else if(j == 'State'){
							if(data.d[j]=='1'){ // A verifier lamp allumée
								document.getElementById('lamp').innerHTML = "Turned On";
								document.getElementById('charging-img').style.display='none';
								document.getElementById('discharging-img').style.display='block';
							}else {
								document.getElementById('lamp').innerHTML = "Turned Off";
								document.getElementById('charging-img').style.display='block';
								document.getElementById('discharging-img').style.display='none';

							}//A VERIFIER
						}
					}
				}

				else if((j == 'v_iphoto') && (document.getElementById('intensity') != null)){
					document.getElementById('intensity').innerHTML = data.d[j];
					i=data.d[j];
				}else if((j == 'v_vphoto') && (document.getElementById('voltage') != null)){
					document.getElementById('voltage').innerHTML = data.d[j]/1000;
					v=data.d[j]/1000;
				}
			}
		}
		if(document.getElementById('power_s') != null){
			document.getElementById('power_s').innerHTML = i*v;
		}

	}

	this.graphData = function(data)
	{
		if((this.graph != null) && (document.getElementById('charge') == null )){
			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			var maxPoints = 25;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					this.graph.series[key].data.push({x:timestamp,y:data.d[j]});
					if (this.graph.series[key].data.length > maxPoints)
					{
						this.graph.series[key].data.splice(0,1);//only display up to maxPoints
					}
					key++;
				}
			}
			this.graph.render();
		}

	}
	this.graphDataCharge = function(data)
	{
		if(document.getElementById('charge') != null ){
			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			var maxPoints = 25;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'v_bat'){
						this.graph.series[key].data.push({x:timestamp,y:data.d[j]});
						if (this.graph.series[key].data.length > maxPoints)
						{
							this.graph.series[key].data.splice(0,1);//only display up to maxPoints
						}
						key++;
					}

				}
			}
			this.graph.render();
		}

	}
	this.updateGauge = function(data)
	{
		if(document.getElementById('gauge') != null){
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'Loudness'){

						needle.moveTo(data.d[j]);
						break;
					}
				}
			}
		}

	}
	this.displayChart = function(device,data){
		if( document.getElementById('charge') == null ){

			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					seriesData[key]={};
					seriesData[key].name=j;
					seriesData[key].color = palette.color();
					seriesData[key].data=[];

					seriesData[key].data[0]={};
					seriesData[key].data[0].x = timestamp;
					seriesData[key].data[0].y = data.d[j];
					key++;
				}

			}

			this.drawGraph(seriesData);
		}
	}
	this.displayChartCharge = function(device,data){
		if(document.getElementById('charge') != null ){

			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'v_bat'){
						seriesData[key]={};
						seriesData[key].name=j;
						seriesData[key].color = palette.color();
						seriesData[key].data=[];

						seriesData[key].data[0]={};
						seriesData[key].data[0].x = timestamp;
						seriesData[key].data[0].y = (data.d[j]/1000)*3;
						key++;
					}

				}
			}

			this.drawGraph(seriesData);
		}
	}

};
<commit_msg>changes data<commit_after>/*******************************************************************************
* Copyright (c) 2014 IBM Corporation and other Contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial Contribution
*******************************************************************************/

var RealtimeGraph = function(){

	var palette = new Rickshaw.Color.Palette( { scheme: [
        "#7f1c7d",
 		"#00b2ef",
		"#00649d",
		"#00a6a0",
		"#ee3e96",
		"#FF6600",
		"#33CC33",
		"#996633",
		"#00FFFF",
		"#FFFF00",
		"#999966",
		"#003300",
		"#CC0000",
		"#993333",
		"#009933"

    ] } );

	// function to invoke Rickshaw and plot the graph
	this.drawGraph = function(seriesData)
	{
		// instantiate our graph!
		this.palette = palette;
		if(document.getElementById("chart") != null){
			this.graph = new Rickshaw.Graph( {
				element: document.getElementById("chart"),
				width: 600,
				height: 250,
				renderer: 'line',
				stroke: true,
				preserve: true,
				series: seriesData
			} );
		}else{
			return null;
		}

		this.graph.render();

		this.hoverDetail = new Rickshaw.Graph.HoverDetail( {
			graph: this.graph,
			xFormatter: function(x) {
				return new Date(x * 1000).toString();
			}
		} );

		this.annotator = new Rickshaw.Graph.Annotate( {
			graph: this.graph,
			element: document.getElementById('timeline')
		} );

		this.legend = new Rickshaw.Graph.Legend( {
			graph: this.graph,
			element: document.getElementById('legend')

		} );

		this.shelving = new Rickshaw.Graph.Behavior.Series.Toggle( {
			graph: this.graph,
			legend: this.legend
		} );

		this.order = new Rickshaw.Graph.Behavior.Series.Order( {
			graph: this.graph,
			legend: this.legend
		} );

		this.highlighter = new Rickshaw.Graph.Behavior.Series.Highlight( {
			graph: this.graph,
			legend: this.legend
		} );

		this.smoother = new Rickshaw.Graph.Smoother( {
			graph: this.graph,
			element: document.querySelector('#smoother')
		} );

		this.ticksTreatment = 'glow';

		this.xAxis = new Rickshaw.Graph.Axis.Time( {
			graph: this.graph,
			ticksTreatment: this.ticksTreatment,
			timeFixture: new Rickshaw.Fixtures.Time.Local()
		} );

		this.xAxis.render();

		this.yAxis = new Rickshaw.Graph.Axis.Y( {
			graph: this.graph,
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
			ticksTreatment: this.ticksTreatment
		} );

		this.yAxis.render();

		this.controls = new RenderControls( {
			element: document.querySelector('form'),
			graph: this.graph
		} );

	}

	this.updateVal = function(data)
	{
		var i=0;
		var v=0;
		for (var j in data.d)
		{
			if (typeof data.d[j] !== 'string') {
				if((j == 'Loudness') && (document.getElementById('loudness')!= null)){
					document.getElementById('loudness').innerHTML = Math.round(data.d[j] *100) +" %";
				}else if((j == 'Power') && (document.getElementById('power') != null)){
					document.getElementById('power').innerHTML = data.d[j];
				}else if((j == 'Light') && (document.getElementById('light') != null )){
					document.getElementById('light').innerHTML = Math.round(data.d[j]*100) +" %";
				}else if((j == 'Motion') && (document.getElementById('motion') != null)){
					//document.getElementById('motion').innerHTML = data.d[j];
					if(document.getElementById('motion-text') != null){
						if(data.d[j] == 0){
							document.getElementById('motion').className = "fa fa-male fa-5x";
							document.getElementById('motion-text').innerHTML = "No detected presence";
						} else {
							document.getElementById('motion').className = "fa fa-child fa-5x";
							document.getElementById('motion-text').innerHTML = "Detected presence";
						}
					}else{
						document.getElementById('motion').innerHTML = data.d[j];
					}

				}else if((j == 'v_bat') || (j == 'State')) {
					if(document.getElementById('voltage_b') != null ){ //home page
						if(j == 'v_bat'){
							document.getElementById('voltage_b').innerHTML = ((data.d[j]/1000)*3).toFixed(1);
						}

					}
					if(document.getElementById('charge') != null ){ // Energy production page
						if(j == 'v_bat'){
							document.getElementById('charge').innerHTML = ((((data.d[j]/1000)*3)*100)/270).toFixed(1);
						}else if(j == 'State'){
							if(data.d[j]=='1'){ // A verifier lamp allumée
								document.getElementById('lamp').innerHTML = "Turned On";
								document.getElementById('charging-img').style.display='none';
								document.getElementById('discharging-img').style.display='block';
							}else {
								document.getElementById('lamp').innerHTML = "Turned Off";
								document.getElementById('charging-img').style.display='block';
								document.getElementById('discharging-img').style.display='none';

							}//A VERIFIER
						}
					}
				}

				else if((j == 'v_iphoto') && (document.getElementById('intensity') != null)){
					document.getElementById('intensity').innerHTML = data.d[j];
					i=data.d[j];
				}else if((j == 'v_vphoto') && (document.getElementById('voltage') != null)){
					document.getElementById('voltage').innerHTML = (data.d[j]/1000).toFixed(1);
					v=data.d[j]/1000;
				}
			}
		}
		if(document.getElementById('power_s') != null){
			document.getElementById('power_s').innerHTML = (i*v).toFixed(1);
		}

	}

	this.graphData = function(data)
	{
		if((this.graph != null) && (document.getElementById('charge') == null )){
			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			var maxPoints = 25;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					this.graph.series[key].data.push({x:timestamp,y:data.d[j]});
					if (this.graph.series[key].data.length > maxPoints)
					{
						this.graph.series[key].data.splice(0,1);//only display up to maxPoints
					}
					key++;
				}
			}
			this.graph.render();
		}

	}
	this.graphDataCharge = function(data)
	{
		if(document.getElementById('charge') != null ){
			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			var maxPoints = 25;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'v_bat'){
						this.graph.series[key].data.push({x:timestamp,y:data.d[j]});
						if (this.graph.series[key].data.length > maxPoints)
						{
							this.graph.series[key].data.splice(0,1);//only display up to maxPoints
						}
						key++;
					}

				}
			}
			this.graph.render();
		}

	}
	this.updateGauge = function(data)
	{
		if(document.getElementById('gauge') != null){
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'Loudness'){

						needle.moveTo(data.d[j]);
						break;
					}
				}
			}
		}

	}
	this.displayChart = function(device,data){
		if( document.getElementById('charge') == null ){

			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					seriesData[key]={};
					seriesData[key].name=j;
					seriesData[key].color = palette.color();
					seriesData[key].data=[];

					seriesData[key].data[0]={};
					seriesData[key].data[0].x = timestamp;
					seriesData[key].data[0].y = data.d[j];
					key++;
				}

			}

			this.drawGraph(seriesData);
		}
	}
	this.displayChartCharge = function(device,data){
		if(document.getElementById('charge') != null ){

			var key = 0;
			var seriesData = [];
			var timestamp = Date.now()/1000;
			for (var j in data.d)
			{
				if (typeof data.d[j] !== 'string') {
					if(j == 'v_bat'){
						seriesData[key]={};
						seriesData[key].name=j;
						seriesData[key].color = palette.color();
						seriesData[key].data=[];

						seriesData[key].data[0]={};
						seriesData[key].data[0].x = timestamp;
						seriesData[key].data[0].y = (data.d[j]/1000)*3;
						key++;
					}

				}
			}

			this.drawGraph(seriesData);
		}
	}

};
<|endoftext|>


<commit_before>var accounts = new (require('./SocketToAccountMap'))();
var getCommandString = require('./commandMap');

const delimiter = '\r\n';

/**
 * Starts the TCP server and adds event listeners to the HTTP server.
 * @param {object} server
 */
function main(server, app) {

  // start http/socket.io server code

  var io = require('socket.io')(server);
  var config = require('../config/config');

  var passportSocketIo = require('passport.socketio');
  io.use(passportSocketIo.authorize({
    store: app.get('sessionStore'),
    success: onAuthorizeSuccess,
    fail: onAuthorizeFail,
    secret: config.expressSessionSecret
  }));

  function onAuthorizeSuccess(data, accept){
    console.log('successful connection to socket.io');
    console.dir(data.user)
    accept();
  }

  function onAuthorizeFail(data, message, error, accept){
    console.log('failed connection to socket.io:', message);
    if (error) {throw new Error(message);}
    else {accept(new Error(message));}
  }

  io.on('connection', function (socket) {

    accounts.addClient(socket.request.user.username, socket);
    console.log(socket.request.user.username + " account connected");

    socket.on('message', (data)=>{
      console.log(data);
      socket.send('pong');
    });
    socket.on('disconnect', function () {
      accounts.removeClient(socket.request.user.username, socket);
      console.log(socket.request.user.username + " account disconnected");
    });

    // relay commands to the tcp server
    socket.on('command', (data)=>{
      console.dir(data);
      var commandString = getCommandString(data.command.name, data.command.parameters);
      var commandType = data.command.name == "raw" ? "raw command" : "command";
      accounts.sendToRobot(socket.request.user.username, data.robot, commandType, commandString);
    });

  });

  // end http/socket.io server code

  // start tcp server code

  // listen for tcp connections from robots
  var net = require('net');

  var tcpServer = net.createServer((tcpSocket)=>{

  	console.log("unidentified robot connected");

    // test write
  	tcpSocket.write(
      JSON.stringify({message: "hello, it's the tcp server!"}) + delimiter
    );

    let tcpRemainder = '';

  	// relay command results from robot to web server
  	tcpSocket.on('data', (data)=>{
      const parsedTCP = parseTCPData();
      remainder = parsedTCP.remainder;
      const dataJSONList = parsedTCP.messages.map(JSON.parse);

  		// separate tcp data into various messages
      for (var dataJSON of dataJSONList) {
        for (var key in dataJSON) {
          console.log(key, dataJSON[key]);
          if (key == 'id') {
            tcpSocket.id = dataJSON[key];
            if (accounts.getRobot(tcpSocket.id.account, tcpSocket.id.robot)) {
              var errorString = 'a robot called ' + tcpSocket.id.robot +
                ' is already connected to account ' + tcpSocket.id.account;
              disconnectRobot(tcpSocket, errorString);
            }
            else {
              accounts.setRobot(tcpSocket.id.account, tcpSocket.id.robot, tcpSocket);
              console.log("robot " + tcpSocket.id.robot + " identified for account " + tcpSocket.id.account);
            }
          }
          else if (tcpSocket.id && tcpSocket.id.account && tcpSocket.id.robot) {
            accounts.sendToClients(tcpSocket.id.account, key, {data: dataJSON[key], robot: tcpSocket.id.robot});
          }
          else {
            var errorString = 'unidentified robots cannot send messages';
            disconnectRobot(tcpSocket, errorString);
          }
        }
      }

    });

    /**
     * Used to piece together any tcp messages which got broken up,
     * and find any pieces we don't have the end of yet.
     * @param {string} tcpString
     * @param {string} tcpRemainder
     */
    function parseTCPData(tcpString, tcpRemainder) {
      let completeMessages = [];
      const tcpMessageRegExp = new RegExp('.+?(' + delimiter + '|$)', 'g');
      const tcpMessages = tcpString.match(/.+?(\r\n|$)/g);
      for (let tcpMessage of tcpMessages) {

        const assembledTCPMessage = tcpRemainder ? tcpRemainder + tcpMessage : tcpMessage;
        tcpRemainder = '';

        const containsDelimiter = assembledTCPMessage.indexOf(delimiter) != -1;
        if (!containsDelimiter) {
          tcpRemainder = assembledTCPMessage;
        }
        else {
          completeMessages.push(assembledTCPMessage);
        }

      }
      let result = {
        messages: completeMessages,
        remainder: tcpRemainder,
      };
      return result;
    }

    /**
     * Disconnects a robot without notifying the web client.
     * Used for unidentified robots and duplicate identifiers.
     * @param {object} robotSocket
     * @param {string} errorString
     */
    function disconnectRobot(robotSocket, errorString) {
      console.log(errorString);
      robotSocket.write(JSON.stringify({message: errorString}) + delimiter);
      robotSocket.endedByServer = true;
      robotSocket.end();
    }

    /**
     * Tells the web client a robot has disconnected.
     * @param {object} robotSocket
     */
    function notifyOfDisconnect(robotSocket) {
      if (robotSocket.id) {
        accounts.setRobot(robotSocket.id.account, robotSocket.id.robot);
        accounts.sendToClients(robotSocket.id.account, "listen end", {robot: robotSocket.id.robot})
        console.log("robot " + robotSocket.id.robot + " for account " + robotSocket.id.account + " disconnected");
      }
    }

  	tcpSocket.on('error', (error)=>{
      console.dir(error);
      notifyOfDisconnect(tcpSocket);
    });

  	// Remove the client from the list when it leaves
  	tcpSocket.on('end', ()=>{
      if (!tcpSocket.endedByServer) {
        notifyOfDisconnect(tcpSocket);
      }
  	});

  	 tcpSocket.on('close', ()=>{console.log('closed');});

  }).listen(3001);

  // end tcp server code

}

module.exports = main;
<commit_msg>regex actually uses the delimiter now<commit_after>var accounts = new (require('./SocketToAccountMap'))();
var getCommandString = require('./commandMap');

const delimiter = '\r\n';

/**
 * Starts the TCP server and adds event listeners to the HTTP server.
 * @param {object} server
 */
function main(server, app) {

  // start http/socket.io server code

  var io = require('socket.io')(server);
  var config = require('../config/config');

  var passportSocketIo = require('passport.socketio');
  io.use(passportSocketIo.authorize({
    store: app.get('sessionStore'),
    success: onAuthorizeSuccess,
    fail: onAuthorizeFail,
    secret: config.expressSessionSecret
  }));

  function onAuthorizeSuccess(data, accept){
    console.log('successful connection to socket.io');
    console.dir(data.user)
    accept();
  }

  function onAuthorizeFail(data, message, error, accept){
    console.log('failed connection to socket.io:', message);
    if (error) {throw new Error(message);}
    else {accept(new Error(message));}
  }

  io.on('connection', function (socket) {

    accounts.addClient(socket.request.user.username, socket);
    console.log(socket.request.user.username + " account connected");

    socket.on('message', (data)=>{
      console.log(data);
      socket.send('pong');
    });
    socket.on('disconnect', function () {
      accounts.removeClient(socket.request.user.username, socket);
      console.log(socket.request.user.username + " account disconnected");
    });

    // relay commands to the tcp server
    socket.on('command', (data)=>{
      console.dir(data);
      var commandString = getCommandString(data.command.name, data.command.parameters);
      var commandType = data.command.name == "raw" ? "raw command" : "command";
      accounts.sendToRobot(socket.request.user.username, data.robot, commandType, commandString);
    });

  });

  // end http/socket.io server code

  // start tcp server code

  // listen for tcp connections from robots
  var net = require('net');

  var tcpServer = net.createServer((tcpSocket)=>{

  	console.log("unidentified robot connected");

    // test write
  	tcpSocket.write(
      JSON.stringify({message: "hello, it's the tcp server!"}) + delimiter
    );

    let tcpRemainder = '';

  	// relay command results from robot to web server
  	tcpSocket.on('data', (data)=>{
      const parsedTCP = parseTCPData();
      remainder = parsedTCP.remainder;
      const dataJSONList = parsedTCP.messages.map(JSON.parse);

  		// separate tcp data into various messages
      for (var dataJSON of dataJSONList) {
        for (var key in dataJSON) {
          console.log(key, dataJSON[key]);
          if (key == 'id') {
            tcpSocket.id = dataJSON[key];
            if (accounts.getRobot(tcpSocket.id.account, tcpSocket.id.robot)) {
              var errorString = 'a robot called ' + tcpSocket.id.robot +
                ' is already connected to account ' + tcpSocket.id.account;
              disconnectRobot(tcpSocket, errorString);
            }
            else {
              accounts.setRobot(tcpSocket.id.account, tcpSocket.id.robot, tcpSocket);
              console.log("robot " + tcpSocket.id.robot + " identified for account " + tcpSocket.id.account);
            }
          }
          else if (tcpSocket.id && tcpSocket.id.account && tcpSocket.id.robot) {
            accounts.sendToClients(tcpSocket.id.account, key, {data: dataJSON[key], robot: tcpSocket.id.robot});
          }
          else {
            var errorString = 'unidentified robots cannot send messages';
            disconnectRobot(tcpSocket, errorString);
          }
        }
      }

    });

    /**
     * Used to piece together any tcp messages which got broken up,
     * and find any pieces we don't have the end of yet.
     * @param {string} tcpString
     * @param {string} tcpRemainder
     */
    function parseTCPData(tcpString, tcpRemainder) {
      let completeMessages = [];
      const tcpMessageRegExp = new RegExp('.+?(' + delimiter + '|$)', 'g');
      const tcpMessages = tcpString.match(tcpMessageRegExp);
      for (let tcpMessage of tcpMessages) {

        const assembledTCPMessage = tcpRemainder ? tcpRemainder + tcpMessage : tcpMessage;
        tcpRemainder = '';

        const containsDelimiter = assembledTCPMessage.indexOf(delimiter) != -1;
        if (!containsDelimiter) {
          tcpRemainder = assembledTCPMessage;
        }
        else {
          completeMessages.push(assembledTCPMessage);
        }

      }
      let result = {
        messages: completeMessages,
        remainder: tcpRemainder,
      };
      return result;
    }

    /**
     * Disconnects a robot without notifying the web client.
     * Used for unidentified robots and duplicate identifiers.
     * @param {object} robotSocket
     * @param {string} errorString
     */
    function disconnectRobot(robotSocket, errorString) {
      console.log(errorString);
      robotSocket.write(JSON.stringify({message: errorString}) + delimiter);
      robotSocket.endedByServer = true;
      robotSocket.end();
    }

    /**
     * Tells the web client a robot has disconnected.
     * @param {object} robotSocket
     */
    function notifyOfDisconnect(robotSocket) {
      if (robotSocket.id) {
        accounts.setRobot(robotSocket.id.account, robotSocket.id.robot);
        accounts.sendToClients(robotSocket.id.account, "listen end", {robot: robotSocket.id.robot})
        console.log("robot " + robotSocket.id.robot + " for account " + robotSocket.id.account + " disconnected");
      }
    }

  	tcpSocket.on('error', (error)=>{
      console.dir(error);
      notifyOfDisconnect(tcpSocket);
    });

  	// Remove the client from the list when it leaves
  	tcpSocket.on('end', ()=>{
      if (!tcpSocket.endedByServer) {
        notifyOfDisconnect(tcpSocket);
      }
  	});

  	 tcpSocket.on('close', ()=>{console.log('closed');});

  }).listen(3001);

  // end tcp server code

}

module.exports = main;
<|endoftext|>


<commit_before>//financeModelItems service used for financemodels REST endpoint
angular.module('mean.services').factory("FinanceModels", ['$resource', function($resource) {
    return $resource('financeModels/:financeModelId', {
        articleId: '@id'
    }, {
        update: {
            method: 'PUT'
        }
    });
}]);<commit_msg>Rename financemodels.js to financeModels.js<commit_after><|endoftext|>