<commit_before>import Component from '@ember/component';
import layout from '../../templates/components/nypr-ui/brand-header';
import { getOwner } from '@ember/application';
import { computed  } from '@ember/object';

export default Component.extend({
  layout,
  tagName: '',
  init() {
    let menuItems = [
      {
        name: 'WNYC',
        url: `https://www.wnyc.org`,
        svg: 'wnyc-logo',
      },
      {
        name: 'Gothamist',
        url: `https://www.gothamist.com`,
        svg: 'gothamist-logo',
      },
      {
        name: 'WNYC Studios',
        url: `https://www.wnycstudios.org`,
        svg: 'wnyc-studios-logo',
      },
      {
        name: 'NJPR',
        url: `http://www.njpublicradio.org`,
        svg: 'njpr-logo',
      },
      {
        name: 'WQXR',
        url: `https://www.wqxr.org`,
        svg: 'wqxr-logo',
      },
      {
        name: 'New Sounds',
        url: `https://www.newsounds.org`,
        svg: 'new-sounds-logo',
      },
      {
        name: 'The Greene Space',
        url: `https://www.thegreenespace.org`,
        svg: 'greene-space-logo',
      },
    ];
    this.set('menuItems', menuItems);

    this._super(...arguments);
  },
  siteSlug: computed(function() {
    let config = getOwner(this).resolveRegistration('config:environment');
    return config.siteSlug;
  })
});
<commit_msg>Add slugs to brand header obj<commit_after>import Component from '@ember/component';
import layout from '../../templates/components/nypr-ui/brand-header';
import {getOwner} from '@ember/application';
import {computed} from '@ember/object';

export default Component.extend({
  layout,
  tagName: '',
  init() {
    let menuItems = [
      {
        name: 'WNYC',
        slug: 'wnyc',
        url: `https://www.wnyc.org`,
        svg: 'wnyc-logo',
      },
      {
        name: 'Gothamist',
        slug: 'gothamist',
        url: `https://www.gothamist.com`,
        svg: 'gothamist-logo',
      },
      {
        name: 'WNYC Studios',
        slug: 'wnycstudios',
        url: `https://www.wnycstudios.org`,
        svg: 'wnyc-studios-logo',
      },
      {
        name: 'NJPR',
        slug: 'njpr',
        url: `http://www.njpublicradio.org`,
        svg: 'njpr-logo',
      },
      {
        name: 'WQXR',
        slug: 'wqxr',
        url: `https://www.wqxr.org`,
        svg: 'wqxr-logo',
      },
      {
        name: 'New Sounds',
        slug: 'newsounds',
        url: `https://www.newsounds.org`,
        svg: 'new-sounds-logo',
      },
      {
        name: 'The Greene Space',
        slug: 'thegreenespace',
        url: `https://www.thegreenespace.org`,
        svg: 'greene-space-logo',
      },
    ];
    this.set('menuItems', menuItems);

    this._super(...arguments);
  },
  siteSlug: computed(function() {
    let config = getOwner(this).resolveRegistration('config:environment');
    return config.siteSlug;
  }),
});
<|endoftext|>


<commit_before>/**
 * @module ember-paper
 */
import PaperMenuContent from './paper-menu-content';
import Ember from 'ember';

const { run, $ } = Ember;
const MutObserver = window.MutationObserver || window.WebKitMutationObserver;

function waitForAnimations(element, callback) {
  let computedStyle = window.getComputedStyle(element);
  if (computedStyle.transitionDuration && computedStyle.transitionDuration !== '0s') {
    let eventCallback = function() {
      element.removeEventListener('transitionend', eventCallback);
      callback();
    };
    element.addEventListener('transitionend', eventCallback);
  } else if (computedStyle.animationName !== 'none' && computedStyle.animationPlayState === 'running') {
    let eventCallback = function() {
      element.removeEventListener('animationend', eventCallback);
      callback();
    };
    element.addEventListener('animationend', eventCallback);
  } else {
    callback();
  }
}

/**
 * @class PaperSelectContent
 * @extends PaperMenuContent
 */
export default PaperMenuContent.extend({
  animateIn() {
    run.next(() => {
      run.scheduleOnce('afterRender', this, () => {
        let dropdown = this.get('dropdown');
        dropdown.actions.reposition();
        this.set('isActive', true);
        this.dropdownElement.style.transform = '';
      });
    });
  },
  animateOut(dropdownElement) {
    let parentElement = this.get('renderInPlace') ? dropdownElement.parentElement.parentElement : dropdownElement.parentElement;
    let clone = dropdownElement.cloneNode(true);
    clone.id = `${clone.id}--clone`;
    let $clone = $(clone);
    parentElement.appendChild(clone);
    $(clone.children[0].children[0]).scrollTop($(dropdownElement.children[0].children[0]).scrollTop());
    window.requestAnimationFrame(() => {
      if (!this.get('isDestroyed')) {
        this.set('isActive', false);
        $clone.addClass('md-leave');
        waitForAnimations(clone, function() {
          $clone.removeClass('md-active');
          parentElement.removeChild(clone);
        });
      }
    });
  },
  addGlobalEvents() {
    window.addEventListener('scroll', this.runloopAwareReposition);
    window.addEventListener('resize', this.runloopAwareReposition);
    window.addEventListener('orientationchange', this.runloopAwareReposition);
    if (MutObserver) {
      this.mutationObserver = new MutObserver((mutations) => {
        // e-b-d incorrectly counts ripples as a mutation, triggering a problematic repositon
        let addedNodes = Array.from(mutations[0].addedNodes).filter((node) => !$(node).hasClass('md-ripple') && (node.nodeName !== '#comment'));
        if (addedNodes.length || mutations[0].removedNodes.length) {
          this.runloopAwareReposition();
        }
      });
      this.mutationObserver.observe(this.dropdownElement, { childList: true, subtree: true });
    } else {
      this.dropdownElement.addEventListener('DOMNodeInserted', this.runloopAwareReposition, false);
      this.dropdownElement.addEventListener('DOMNodeRemoved', this.runloopAwareReposition, false);
    }
  }
});
<commit_msg>dont use Array.from<commit_after>/**
 * @module ember-paper
 */
import PaperMenuContent from './paper-menu-content';
import Ember from 'ember';

const { run, $ } = Ember;
const MutObserver = window.MutationObserver || window.WebKitMutationObserver;

function waitForAnimations(element, callback) {
  let computedStyle = window.getComputedStyle(element);
  if (computedStyle.transitionDuration && computedStyle.transitionDuration !== '0s') {
    let eventCallback = function() {
      element.removeEventListener('transitionend', eventCallback);
      callback();
    };
    element.addEventListener('transitionend', eventCallback);
  } else if (computedStyle.animationName !== 'none' && computedStyle.animationPlayState === 'running') {
    let eventCallback = function() {
      element.removeEventListener('animationend', eventCallback);
      callback();
    };
    element.addEventListener('animationend', eventCallback);
  } else {
    callback();
  }
}

/**
 * @class PaperSelectContent
 * @extends PaperMenuContent
 */
export default PaperMenuContent.extend({
  animateIn() {
    run.next(() => {
      run.scheduleOnce('afterRender', this, () => {
        let dropdown = this.get('dropdown');
        dropdown.actions.reposition();
        this.set('isActive', true);
        this.dropdownElement.style.transform = '';
      });
    });
  },
  animateOut(dropdownElement) {
    let parentElement = this.get('renderInPlace') ? dropdownElement.parentElement.parentElement : dropdownElement.parentElement;
    let clone = dropdownElement.cloneNode(true);
    clone.id = `${clone.id}--clone`;
    let $clone = $(clone);
    parentElement.appendChild(clone);
    $(clone.children[0].children[0]).scrollTop($(dropdownElement.children[0].children[0]).scrollTop());
    window.requestAnimationFrame(() => {
      if (!this.get('isDestroyed')) {
        this.set('isActive', false);
        $clone.addClass('md-leave');
        waitForAnimations(clone, function() {
          $clone.removeClass('md-active');
          parentElement.removeChild(clone);
        });
      }
    });
  },
  addGlobalEvents() {
    window.addEventListener('scroll', this.runloopAwareReposition);
    window.addEventListener('resize', this.runloopAwareReposition);
    window.addEventListener('orientationchange', this.runloopAwareReposition);
    if (MutObserver) {
      this.mutationObserver = new MutObserver((mutations) => {
        // e-b-d incorrectly counts ripples as a mutation, triggering a problematic repositon
        // convert NodeList to Array
        let addedNodes = Array.prototype.slice.call(mutations[0].addedNodes).filter((node) => !$(node).hasClass('md-ripple') && (node.nodeName !== '#comment'));
        if (addedNodes.length || mutations[0].removedNodes.length) {
          this.runloopAwareReposition();
        }
      });
      this.mutationObserver.observe(this.dropdownElement, { childList: true, subtree: true });
    } else {
      this.dropdownElement.addEventListener('DOMNodeInserted', this.runloopAwareReposition, false);
      this.dropdownElement.addEventListener('DOMNodeRemoved', this.runloopAwareReposition, false);
    }
  }
});
<|endoftext|>


<commit_before>/**
 * @module esdf/test/DummyEventSink
 */

var when = require('when');

/**
 * Create a dummy Event Sink. The Event Sink can fully simulate sinking and rehydration, and stays in compliance with Promises/A.
 *
 * @constructor
 */
function DummyEventSink(){
	/**
	 * Whether the next sink() attempt should succeed.
	 * @public
	 */
	this._want_success = true;
	/**
	 * The type of failure to enrich the error with when a failure is requested via _want_success=false.
	 * @public
	 */
	this._failure_type = 'DummyEventSink test failure';
	/**
	 * The event streams holding the sunk data.
	 * @private
	 */
	this._streams = {};
};

/**
 * Attempts to save a commit (array of event objects) into the Event Store. Returns a promise which resolves upon a successful save and is rejected on any error (with the error being the rejection reason verbatim).
 * Since this is only a dummy Event Sink, all events are only saved into a temporary object, and are discarded when the DummyEventSink is destroyed.
 *
 * @param {Array} events The commit of events to save to the in-memory temporary database.
 * @param {string} stream_id The stream ID under which the commit should be saved. Typically, this is equal to the Aggregate Root ID.
 * @param {number} sequence_number The sequence number to save the commit under. Only one commit within a given stream ID can occupy each sequence number.
 */
DummyEventSink.prototype.sink = function sink(events, stream_id, sequence_number){
	var r = when.defer().resolver;
	var sink_error = new Error('DummyEventSink.sink:reject');
	sink_error.type = this._failure_type;
	if(this._want_success){
		var event_envelope = events;
		if(typeof(this._streams[stream_id]) === 'undefined'){
			this._streams[stream_id] = [event_envelope];
		}
		else{
			this._streams[stream_id].push(event_envelope);
		}
		return r.resolve('DummyEventSink.sink:resolve');
	}
	else{
		return r.reject(sink_error);
	}
};

/**
 * Apply all the events from a given stream ID to the object passed using the object's emit() method (as in EventEmitter).
 *
 * @param {Object} object The object to apply the events to.
 * @param {string} stream_id The stream ID from which to load the events.
 */
DummyEventSink.prototype.rehydrate = function rehydrate(object, stream_id){
	var rehydration_deferred = when.defer();
	var rehydrate_error = new Error('DummyEventSink rehydration event retrieval failure');
	rehydrate_error.type = this._failure_type;
	if(this._want_success){
		if(Array.isArray(this._streams[stream_id])){
			this._streams[stream_id].forEach(function(streamed_commit){
				object.applyCommit(streamed_commit);
				rehydration_deferred.resolver.notify('DummyEventSink.rehydrate:progress');
			});
		}
		return rehydration_deferred.resolver.resolve('DummyEventSink.rehydrate:resolve');
	}
	else{
		return rehydration_deferred.resolver.reject(rehydrate_error);
	}
};

module.exports.DummyEventSink = DummyEventSink;<commit_msg>Changed DummyEventSink's error controls to more precise ones.<commit_after>/**
 * @module esdf/test/DummyEventSink
 */

var when = require('when');

/**
 * Create a dummy Event Sink. The Event Sink can fully simulate sinking and rehydration, and stays in compliance with Promises/A.
 *
 * @constructor
 */
function DummyEventSink(){
	/**
	 * Whether the next sink() attempt should succeed.
	 * @public
	 */
	this._wantSinkSuccess = true;
	/**
	 * Whether the next rehydration attempt should succeed.
	 * @public
	 */
	this._wantRehydrateSuccess = true;
	/**
	 * The type of failure to enrich the error with when a failure is requested via _want_success=false.
	 * @public
	 */
	this._failureType = 'DummyEventSink test failure';
	/**
	 * The event streams holding the sunk data.
	 * @private
	 */
	this._streams = {};
};

/**
 * Attempts to save a commit (array of event objects) into the Event Store. Returns a promise which resolves upon a successful save and is rejected on any error (with the error being the rejection reason verbatim).
 * Since this is only a dummy Event Sink, all events are only saved into a temporary object, and are discarded when the DummyEventSink is destroyed.
 *
 * @param {Array} events The commit of events to save to the in-memory temporary database.
 * @param {string} stream_id The stream ID under which the commit should be saved. Typically, this is equal to the Aggregate Root ID.
 * @param {number} sequence_number The sequence number to save the commit under. Only one commit within a given stream ID can occupy each sequence number.
 */
DummyEventSink.prototype.sink = function sink(events, stream_id, sequence_number){
	var r = when.defer().resolver;
	var sink_error = new Error('DummyEventSink.sink:reject');
	sink_error.type = this._failureType;
	if(this._wantSinkSuccess){
		var event_envelope = events;
		if(typeof(this._streams[stream_id]) === 'undefined'){
			this._streams[stream_id] = [event_envelope];
		}
		else{
			this._streams[stream_id].push(event_envelope);
		}
		return r.resolve('DummyEventSink.sink:resolve');
	}
	else{
		return r.reject(sink_error);
	}
};

/**
 * Apply all the events from a given stream ID to the object passed using the object's emit() method (as in EventEmitter).
 *
 * @param {Object} object The object to apply the events to.
 * @param {string} stream_id The stream ID from which to load the events.
 */
DummyEventSink.prototype.rehydrate = function rehydrate(object, stream_id){
	var rehydration_deferred = when.defer();
	var rehydrate_error = new Error('DummyEventSink rehydration event retrieval failure');
	rehydrate_error.type = this._failureType;
	if(this._wantRehydrateSuccess){
		if(Array.isArray(this._streams[stream_id])){
			this._streams[stream_id].forEach(function(streamed_commit){
				object.applyCommit(streamed_commit);
				rehydration_deferred.resolver.notify('DummyEventSink.rehydrate:progress');
			});
		}
		return rehydration_deferred.resolver.resolve('DummyEventSink.rehydrate:resolve');
	}
	else{
		return rehydration_deferred.resolver.reject(rehydrate_error);
	}
};

module.exports.DummyEventSink = DummyEventSink;<|endoftext|>


<commit_before>(function(){
	"use strict";

	var root = this,
		Chart = root.Chart,
		helpers = Chart.helpers;

	var defaultConfig = {
    // String - background color for graph
    backgroundColor: '#fff',

    // Boolean - whether each square in the dataset is outlined
    stroke: false,

    // Number - width of the outline stroke.
    strokePerc: 0.05,

    // String - the outline stroke color.
    strokeColor: "rgb(128,128,128)",

    // String - the outline stroke color.
    highlightStrokeColor: "rgb(192,192,192)",

    // Boolean - whether to draw the heat map boxes with rounded corners
    rounded: true,

    // Number - the radius (as a percentage of size) of the rounded corners
    roundedRadius: 0.1,

    // Number - padding between heat map boxes (as a percentage of box size)
    paddingScale: 0.05,

    // String - "gradient", "palette"
    colorInterpolation: "gradient",

    // Array[String] - the colors used for the active color scheme.
    // Any number of colors is allowed.
    colors: [ "rgba(220,220,220,0.9)", "rgba(151,187,205,0.9)"],

    // Boolean - whether boxes change color on hover.
    colorHighlight: true,

    // Number - a floating point value which specifies how much lighter or
    // darker a color becomes when hovered, where 1 is no change,
    // 0.9 is slightly darker, and 1.1 is slightly lighter.
    colorHighlightMultiplier: 0.92,

    // Boolean - Whether to draw label data
    showLabels: true,

    // Number - the font size of the label as percentage of box height
    labelScale: 0.2,

    // String - label font family
    labelFontFamily: '"HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif',

    // String - label font style
    labelFontStyle: "normal",

    // String - label font color.
    labelFontColor: "rgba(0,0,0,0.5)",

    // String - tooltipTemplate
    tooltipTemplate: "<%= xLabel %> | <%= yLabel %> : <%= value %>",

    // String - template for legend generation
    legendTemplate : ""

	};

	Chart.Type.extend({
		name: "HeatMap",
		defaults : defaultConfig,
		initialize:  function(data){

			//Expose options as a scope variable here so we can access it in the ScaleClass
			var options = this.options;

      this.colorManager = new ColorManager();
      this.colorManager.setup(data,this.options.colors,this.options);

			this.ScaleClass = Chart.Scale.extend({
				offsetGridLines : true,
				calculateBaseWidth : function(){
					return this.calculateX(1) - this.calculateX(0);
				},
				calculateBoxWidth : function(datasetCount, dataCount){
					//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
					var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
          var count = Math.max(datasetCount, dataCount);

					return this.calculateBaseWidth();
				},
        calculateBoxHeight: function(){
          return this.calculateY(0) - this.calculateY(1);
        },
        buildYLabels : function(){
          this.yLabelWidth = (this.display && this.showLabels) ? helpers.longestText(this.ctx,this.font,this.yLabels) : 0;
        },
        draw : function(){
          var ctx = this.ctx,
            yLabelGap = (this.endPoint - this.startPoint) / this.steps,
            xStart = Math.round(this.xScalePaddingLeft);
          if (this.display){
            ctx.fillStyle = this.textColor;
            ctx.font = this.font;
            helpers.each(this.yLabels,function(labelString,index){
              var yLabelCenter = this.endPoint - (yLabelGap * index) - yLabelGap*0.5,
                linePositionY = Math.round(yLabelCenter),
                drawHorizontalLine = this.showHorizontalLines;

              ctx.textAlign = "right";
              ctx.textBaseline = "middle";
              if (this.showLabels){
                ctx.fillText(labelString, xStart - 10, yLabelCenter);
              }
            },this);

            helpers.each(this.xLabels,function(label,index){
              var xPos = this.calculateX(index) + helpers.aliasPixel(this.lineWidth),
                // Check to see if line/bar here and decide where to place the line
                linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + helpers.aliasPixel(this.lineWidth),
                isRotated = (this.xLabelRotation > 0),
                drawVerticalLine = this.showVerticalLines;

              ctx.lineWidth = this.lineWidth;
              ctx.strokeStyle = this.lineColor;

              ctx.save();
              ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
              ctx.rotate(helpers.radians(this.xLabelRotation)*-1);
              ctx.font = this.font;
              ctx.textAlign = (isRotated) ? "right" : "center";
              ctx.textBaseline = (isRotated) ? "middle" : "top";
              ctx.fillText(label, 0, 0);
              ctx.restore();
            },this);
          }
        }

			});

			this.datasets = [];
      this.dataLength = 0;
      this.yLabels = [];

			//Set up tooltip events on the chart
			if (this.options.showTooltips){
				helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
					var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];

					this.eachBars(function(bar){
						bar.restore(['fillColor', 'strokeColor']);
					});
					helpers.each(activeBars, function(activeBar){
						activeBar.fillColor = activeBar.highlightFill;
						activeBar.strokeColor = activeBar.highlightStroke;
					});
					this.showTooltip(activeBars);
				});
			}

			//Declare the extension of the default point, to cater for the options passed in to the constructor
			this.BoxClass = Chart.Rectangle.extend({
				strokePerc : this.options.strokePerc,
				strokeColor : this.options.strokeColor,
				showStroke : this.options.stroke,
        fontColor : this.options.labelFontColor,
        fontFamily : this.options.labelFontFamily,
        fontScale : this.options.labelScale,
        showLabels : this.options.showLabels,
        radiusScale : this.options.rounded ? this.options.roundedRadius : 0,
        paddingScale : this.options.paddingScale,
				ctx : this.chart.ctx,
        draw : function(){
          var ctx = this.ctx,
            halfWidth = this.width/2,
            drawWidth = this.width,
            drawHeight = this.height,
            left = this.x - halfWidth,
            top = this.y,
            strokeWidth = this.strokePerc * this.width,
            halfStroke = strokeWidth / 2,
            leftPadding = this.paddingScale*drawWidth,
            topPadding = this.paddingScale*drawHeight;

          left += leftPadding*0.5;
          top += topPadding*0.5;
          drawWidth -= leftPadding;
          drawHeight -= topPadding;

          // Canvas doesn't allow us to stroke inside the width so we can
          // adjust the sizes to fit if we're setting a stroke on the line
          if (this.showStroke){
            left += halfStroke;
            drawWidth -= halfStroke;
            drawHeight -= halfStroke;
            top += halfStroke;
          }

          ctx.fillStyle = this.fillColor;
          ctx.strokeStyle = this.strokeColor;
          ctx.lineWidth = strokeWidth;

          helpers.drawRoundedRectangle(ctx, left, top, drawWidth, drawHeight, this.radiusScale*this.width);

          ctx.fill();
          if (this.showStroke){
            ctx.stroke();
          }

          if (this.showLabels && this.label !== null && this.label !== undefined){
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillStyle = this.fontColor;
            ctx.font = this.height*this.fontScale+"px "+this.fontFamily;
            ctx.fillText(this.value, left+drawWidth*0.5, top+drawHeight*0.5);
          }

        }
			});

			//Iterate through each of the datasets, and build this into a property of the chart
			helpers.each(data.datasets,function(dataset,datasetIndex){

				var datasetObject = {
					label : dataset.label || null,
					bars : []
				};

        if (dataset.data.length > this.dataLength){
          this.dataLength = dataset.data.length;
        }

				this.datasets.push(datasetObject);
        this.yLabels.push(dataset.label);

				helpers.each(dataset.data,function(dataPoint,index){
          var color = this.colorManager.getColor(dataPoint);
					//Add a new point for each piece of data, passing any required data to draw.
					datasetObject.bars.push(new this.BoxClass({
						value : dataPoint,
						label : data.labels[index],
						datasetLabel: dataset.label,
						strokeColor : this.options.strokeColor,
						fillColor : color.color,
						highlightFill : color.highlight,
						highlightStroke : this.options.highlightStrokeColor,
					}));
				},this);

			},this);

      // could not manage to invert the y scale
      this.datasets.reverse();
      this.yLabels.reverse();

			this.buildScale(data.labels, this.yLabels);

			this.BoxClass.prototype.base = this.scale.endPoint;

			this.eachBars(function(bar, index, datasetIndex){
				helpers.extend(bar, {
							x : this.scale.calculateX(index),
							y : this.scale.calculateY(datasetIndex+1),
							width : this.scale.calculateBoxWidth(),
							height : this.scale.calculateBoxHeight()
				});
				bar.save();
			}, this);

			this.render();
		},
		update : function(){
			this.scale.update();
			// Reset any highlight colours before updating.
			helpers.each(this.activeElements, function(activeElement){
				activeElement.restore(['fillColor', 'strokeColor']);
			});

			this.eachBars(function(bar){
				bar.save();
			});
			this.render();
		},
		eachBars : function(callback){
			helpers.each(this.datasets,function(dataset, datasetIndex){
				helpers.each(dataset.bars, callback, this, datasetIndex);
			},this);
		},
		getBarsAtEvent : function(e){
      var eventPosition = helpers.getRelativePosition(e),
        barIndex;

			for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
				for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
					if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
						return [this.datasets[datasetIndex].bars[barIndex]];
					}
				}
			}

			return [];
		},
		buildScale : function(labels, yLabels){
			var self = this;

			var dataTotal = function(){
				var values = [];
				self.eachBars(function(bar){
					values.push(bar.value);
				});
				return values;
			};

			var scaleOptions = {
				templateString : this.options.scaleLabel,
				height : this.chart.height,
				width : this.chart.width,
				ctx : this.chart.ctx,
				textColor : this.options.scaleFontColor,
				fontSize : this.options.scaleFontSize,
				fontStyle : this.options.scaleFontStyle,
				fontFamily : this.options.scaleFontFamily,
				valuesCount : labels.length,
				beginAtZero : this.options.scaleBeginAtZero,
				integersOnly : this.options.scaleIntegersOnly,
				calculateYRange: function(currentHeight){
          var updatedRanges = {
            min: 0,
            max: self.datasets.length,
            steps: self.datasets.length,
            stepValue: 1
          };

					helpers.extend(this, updatedRanges);
				},
				xLabels : labels,
        yLabels : yLabels,
				font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
				lineWidth : this.options.scaleLineWidth,
				lineColor : this.options.scaleLineColor,
				showHorizontalLines : this.options.scaleShowHorizontalLines,
				showVerticalLines : this.options.scaleShowVerticalLines,
				gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
				gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
				padding : (this.options.showScale) ? 0 : (this.options.stroke) ? this.options.strokeWidth : 0,
				showLabels : this.options.scaleShowLabels,
				display : this.options.showScale,
			};

			this.scale = new this.ScaleClass(scaleOptions);
		},
		addData : function(valuesArray,label){
			//Map the values array for each of the datasets
			helpers.each(valuesArray,function(value,datasetIndex){
				//Add a new point for each piece of data, passing any required data to draw.
				this.datasets[datasetIndex].bars.push(new this.BoxClass({
					value : value,
					label : label,

          x : this.scale.calculateX(index),
          y : this.scale.calculateY(datasetIndex+1),
          width : this.scale.calculateBoxWidth(),
          height : this.scale.calculateBoxHeight(),

					base : this.scale.endPoint,
					strokeColor : this.datasets[datasetIndex].strokeColor,
					fillColor : this.datasets[datasetIndex].fillColor
				}));
			},this);

			this.scale.addXLabel(label);
			//Then re-render the chart.
			this.update();
		},
		removeData : function(){
			this.scale.removeXLabel();
			//Then re-render the chart.
			helpers.each(this.datasets,function(dataset){
				dataset.bars.shift();
			},this);
			this.update();
		},
		reflow : function(){
			helpers.extend(this.BoxClass.prototype,{
				y: this.scale.endPoint,
				base : this.scale.endPoint
			});
			var newScaleProps = helpers.extend({
				height : this.chart.height,
				width : this.chart.width
			});
			this.scale.update(newScaleProps);
		},
    showTooltip : function(ChartElements){
      this.draw();
      helpers.each(ChartElements, function(Element) {
        var tooltipPosition = Element.tooltipPosition();
        var tooltipVariables = {
          xLabel: Element.datasetLabel,
          yLabel: Element.label,
          value: Element.value
        };

        new Chart.Tooltip({
          x: Math.round(tooltipPosition.x),
          y: Math.round(tooltipPosition.y+20),
          xPadding: this.options.tooltipXPadding,
          yPadding: this.options.tooltipYPadding,
          fillColor: this.options.tooltipFillColor,
          textColor: this.options.tooltipFontColor,
          fontFamily: this.options.tooltipFontFamily,
          fontStyle: this.options.tooltipFontStyle,
          fontSize: this.options.tooltipFontSize,
          caretHeight: this.options.tooltipCaretSize,
          cornerRadius: this.options.tooltipCornerRadius,
          text: helpers.template(this.options.tooltipTemplate, tooltipVariables),
          chart: this.chart,
          custom: this.options.customTooltips
        }).draw();
      }, this);
      return this;
    },
		draw : function(ease){
			var easingDecimal = ease || 1;
			this.clear();

			var ctx = this.chart.ctx;

			this.scale.draw(easingDecimal);

			//Draw all the bars for each dataset
			helpers.each(this.datasets,function(dataset,datasetIndex){
				helpers.each(dataset.bars,function(bar,index){
					if (bar.hasValue()){
						bar.base = this.scale.endPoint;
						//Transition then draw
						bar.transition({
							x : this.scale.calculateX(index),
							y : this.scale.calculateY(datasetIndex+1),
							width : this.scale.calculateBoxWidth()+1,
							height : this.scale.calculateBoxHeight()+1
						}, easingDecimal).draw();
					}
				},this);
			},this);
		}
	});

}).call(this);
<commit_msg>Some formatting<commit_after>(function(){
	"use strict";

	var root = this,
		Chart = root.Chart,
		helpers = Chart.helpers;

	var defaultConfig = {
    // String - background color for graph
    backgroundColor: '#fff',

    // Boolean - whether each square in the dataset is outlined
    stroke: false,

    // Number - width of the outline stroke.
    strokePerc: 0.05,

    // String - the outline stroke color.
    strokeColor: "rgb(128,128,128)",

    // String - the outline stroke color.
    highlightStrokeColor: "rgb(192,192,192)",

    // Boolean - whether to draw the heat map boxes with rounded corners
    rounded: true,

    // Number - the radius (as a percentage of size) of the rounded corners
    roundedRadius: 0.1,

    // Number - padding between heat map boxes (as a percentage of box size)
    paddingScale: 0.05,

    // String - "gradient", "palette"
    colorInterpolation: "gradient",

    // Array[String] - the colors used for the active color scheme.
    // Any number of colors is allowed.
    colors: [ "rgba(220,220,220,0.9)", "rgba(151,187,205,0.9)"],

    // Boolean - whether boxes change color on hover.
    colorHighlight: true,

    // Number - a floating point value which specifies how much lighter or
    // darker a color becomes when hovered, where 1 is no change,
    // 0.9 is slightly darker, and 1.1 is slightly lighter.
    colorHighlightMultiplier: 0.92,

    // Boolean - Whether to draw label data
    showLabels: true,

    // Number - the font size of the label as percentage of box height
    labelScale: 0.2,

    // String - label font family
    labelFontFamily: '"HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif',

    // String - label font style
    labelFontStyle: "normal",

    // String - label font color.
    labelFontColor: "rgba(0,0,0,0.5)",

    // String - tooltipTemplate
    tooltipTemplate: "<%= xLabel %> | <%= yLabel %> : <%= value %>",

    // String - template for legend generation
    legendTemplate : ""

	};

	Chart.Type.extend({
		name: "HeatMap",
		defaults : defaultConfig,
		initialize:  function(data){

			//Expose options as a scope variable here so we can access it in the ScaleClass
			var options = this.options;

      this.colorManager = new ColorManager();
      this.colorManager.setup(data,this.options.colors,this.options);

			this.ScaleClass = Chart.Scale.extend({
				offsetGridLines : true,
				calculateBaseWidth : function(){
					return this.calculateX(1) - this.calculateX(0);
				},
				calculateBoxWidth : function(datasetCount, dataCount){
					//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
					var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
          var count = Math.max(datasetCount, dataCount);

					return this.calculateBaseWidth();
				},
        calculateBoxHeight: function(){
          return this.calculateY(0) - this.calculateY(1);
        },
        buildYLabels : function(){
          this.yLabelWidth = (this.display && this.showLabels) ? helpers.longestText(this.ctx,this.font,this.yLabels) : 0;
        },
        draw : function(){
          var ctx = this.ctx,
            yLabelGap = (this.endPoint - this.startPoint) / this.steps,
            xStart = Math.round(this.xScalePaddingLeft);
          if (this.display){
            ctx.fillStyle = this.textColor;
            ctx.font = this.font;
            helpers.each(this.yLabels,function(labelString,index){
              var yLabelCenter = this.endPoint - (yLabelGap * index) - yLabelGap*0.5,
                linePositionY = Math.round(yLabelCenter),
                drawHorizontalLine = this.showHorizontalLines;

              ctx.textAlign = "right";
              ctx.textBaseline = "middle";
              if (this.showLabels){
                ctx.fillText(labelString, xStart - 10, yLabelCenter);
              }
            },this);

            helpers.each(this.xLabels,function(label,index){
              var xPos = this.calculateX(index) + helpers.aliasPixel(this.lineWidth),
                // Check to see if line/bar here and decide where to place the line
                linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + helpers.aliasPixel(this.lineWidth),
                isRotated = (this.xLabelRotation > 0),
                drawVerticalLine = this.showVerticalLines;

              ctx.lineWidth = this.lineWidth;
              ctx.strokeStyle = this.lineColor;

              ctx.save();
              ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
              ctx.rotate(helpers.radians(this.xLabelRotation)*-1);
              ctx.font = this.font;
              ctx.textAlign = (isRotated) ? "right" : "center";
              ctx.textBaseline = (isRotated) ? "middle" : "top";
              ctx.fillText(label, 0, 0);
              ctx.restore();
            },this);
          }
        }

			});

			this.datasets = [];
      this.dataLength = 0;
      this.yLabels = [];

			//Set up tooltip events on the chart
			if (this.options.showTooltips){
				helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
					var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];

					this.eachBars(function(bar){
						bar.restore(['fillColor', 'strokeColor']);
					});
					helpers.each(activeBars, function(activeBar){
						activeBar.fillColor = activeBar.highlightFill;
						activeBar.strokeColor = activeBar.highlightStroke;
					});
					this.showTooltip(activeBars);
				});
			}

			//Declare the extension of the default point, to cater for the options passed in to the constructor
			this.BoxClass = Chart.Rectangle.extend({
				strokePerc : this.options.strokePerc,
				strokeColor : this.options.strokeColor,
				showStroke : this.options.stroke,
        fontColor : this.options.labelFontColor,
        fontFamily : this.options.labelFontFamily,
        fontScale : this.options.labelScale,
        showLabels : this.options.showLabels,
        radiusScale : this.options.rounded ? this.options.roundedRadius : 0,
        paddingScale : this.options.paddingScale,
				ctx : this.chart.ctx,
        draw : function(){
          var ctx = this.ctx,
            halfWidth = this.width/2,
            drawWidth = this.width,
            drawHeight = this.height,
            left = this.x - halfWidth,
            top = this.y,
            strokeWidth = this.strokePerc * this.width,
            halfStroke = strokeWidth / 2,
            leftPadding = this.paddingScale*drawWidth,
            topPadding = this.paddingScale*drawHeight;

          left += leftPadding*0.5;
          top += topPadding*0.5;
          drawWidth -= leftPadding;
          drawHeight -= topPadding;

          // Canvas doesn't allow us to stroke inside the width so we can
          // adjust the sizes to fit if we're setting a stroke on the line
          if (this.showStroke){
            left += halfStroke;
            drawWidth -= halfStroke;
            drawHeight -= halfStroke;
            top += halfStroke;
          }

          ctx.fillStyle = this.fillColor;
          ctx.strokeStyle = this.strokeColor;
          ctx.lineWidth = strokeWidth;

          helpers.drawRoundedRectangle(ctx, left, top, drawWidth, drawHeight, this.radiusScale*this.width);

          ctx.fill();
          if (this.showStroke){
            ctx.stroke();
          }

          if (this.showLabels && this.label !== null && this.label !== undefined){
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillStyle = this.fontColor;
            ctx.font = this.height*this.fontScale+"px "+this.fontFamily;
            ctx.fillText(this.value, left+drawWidth*0.5, top+drawHeight*0.5);
          }

        }
			});

			//Iterate through each of the datasets, and build this into a property of the chart
			helpers.each(data.datasets,function(dataset,datasetIndex){

				var datasetObject = {
					label : dataset.label || null,
					bars : []
				};

        if (dataset.data.length > this.dataLength){
          this.dataLength = dataset.data.length;
        }

				this.datasets.push(datasetObject);
        this.yLabels.push(dataset.label);

				helpers.each(dataset.data,function(dataPoint,index){
          var color = this.colorManager.getColor(dataPoint);
					//Add a new point for each piece of data, passing any required data to draw.
					datasetObject.bars.push(new this.BoxClass({
						value : dataPoint,
						label : data.labels[index],
						datasetLabel: dataset.label,
						strokeColor : this.options.strokeColor,
						fillColor : color.color,
						highlightFill : color.highlight,
						highlightStroke : this.options.highlightStrokeColor,
					}));
				},this);

			},this);

      // could not manage to invert the y scale
      this.datasets.reverse();
      this.yLabels.reverse();

			this.buildScale(data.labels, this.yLabels);

			this.BoxClass.prototype.base = this.scale.endPoint;

			this.eachBars(function(bar, index, datasetIndex){
				helpers.extend(bar, {
							x : this.scale.calculateX(index),
							y : this.scale.calculateY(datasetIndex+1),
							width : this.scale.calculateBoxWidth(),
							height : this.scale.calculateBoxHeight()
				});
				bar.save();
			}, this);

			this.render();
		},
		update : function(){
			this.scale.update();
			// Reset any highlight colours before updating.
			helpers.each(this.activeElements, function(activeElement){
				activeElement.restore(['fillColor', 'strokeColor']);
			});

			this.eachBars(function(bar){
				bar.save();
			});
			this.render();
		},
		eachBars : function(callback){
			helpers.each(this.datasets,function(dataset, datasetIndex){
				helpers.each(dataset.bars, callback, this, datasetIndex);
			},this);
		},
		getBarsAtEvent : function(e){
      var eventPosition = helpers.getRelativePosition(e),
        barIndex;

			for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
				for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
					if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
						return [this.datasets[datasetIndex].bars[barIndex]];
					}
				}
			}

			return [];
		},
		buildScale : function(labels, yLabels){
			var self = this;

			var dataTotal = function(){
				var values = [];
				self.eachBars(function(bar){
					values.push(bar.value);
				});
				return values;
			};

			var scaleOptions = {
				templateString : this.options.scaleLabel,
				height : this.chart.height,
				width : this.chart.width,
				ctx : this.chart.ctx,
				textColor : this.options.scaleFontColor,
				fontSize : this.options.scaleFontSize,
				fontStyle : this.options.scaleFontStyle,
				fontFamily : this.options.scaleFontFamily,
				valuesCount : labels.length,
				beginAtZero : this.options.scaleBeginAtZero,
				integersOnly : this.options.scaleIntegersOnly,
				calculateYRange: function(currentHeight){
          var updatedRanges = {
            min: 0,
            max: self.datasets.length,
            steps: self.datasets.length,
            stepValue: 1
          };

					helpers.extend(this, updatedRanges);
				},
				xLabels : labels,
        yLabels : yLabels,
				font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
				lineWidth : this.options.scaleLineWidth,
				lineColor : this.options.scaleLineColor,
				showHorizontalLines : this.options.scaleShowHorizontalLines,
				showVerticalLines : this.options.scaleShowVerticalLines,
				gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
				gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
				padding : (this.options.showScale) ? 0 : (this.options.stroke) ? this.options.strokeWidth : 0,
				showLabels : this.options.scaleShowLabels,
				display : this.options.showScale,
			};

			this.scale = new this.ScaleClass(scaleOptions);
		},
		addData : function(valuesArray,label){
			//Map the values array for each of the datasets
			helpers.each(valuesArray,function(value,datasetIndex){
				//Add a new point for each piece of data, passing any required data to draw.
				this.datasets[datasetIndex].bars.push(new this.BoxClass({
					value : value,
					label : label,

          x : this.scale.calculateX(index),
          y : this.scale.calculateY(datasetIndex+1),
          width : this.scale.calculateBoxWidth(),
          height : this.scale.calculateBoxHeight(),

					base : this.scale.endPoint,
					strokeColor : this.datasets[datasetIndex].strokeColor,
					fillColor : this.datasets[datasetIndex].fillColor
				}));
			},this);

			this.scale.addXLabel(label);
			//Then re-render the chart.
			this.update();
		},
		removeData : function(){
			this.scale.removeXLabel();
			//Then re-render the chart.
			helpers.each(this.datasets,function(dataset){
				dataset.bars.shift();
			},this);
			this.update();
		},
		reflow : function(){
			helpers.extend(this.BoxClass.prototype,{
				y: this.scale.endPoint,
				base : this.scale.endPoint
			});
			var newScaleProps = helpers.extend({
				height : this.chart.height,
				width : this.chart.width
			});
			this.scale.update(newScaleProps);
		},
    showTooltip : function(ChartElements){
      this.draw();
      helpers.each(ChartElements, function(Element) {
        var tooltipPosition = Element.tooltipPosition();
        var tooltipVariables = {
          xLabel: Element.datasetLabel,
          yLabel: Element.label,
          value: Element.value
        };

        new Chart.Tooltip({
          x: Math.round(tooltipPosition.x),
          y: Math.round(tooltipPosition.y+20),
          xPadding: this.options.tooltipXPadding,
          yPadding: this.options.tooltipYPadding,
          fillColor: this.options.tooltipFillColor,
          textColor: this.options.tooltipFontColor,
          fontFamily: this.options.tooltipFontFamily,
          fontStyle: this.options.tooltipFontStyle,
          fontSize: this.options.tooltipFontSize,
          caretHeight: this.options.tooltipCaretSize,
          cornerRadius: this.options.tooltipCornerRadius,
          text: helpers.template(this.options.tooltipTemplate, tooltipVariables),
          chart: this.chart,
          custom: this.options.customTooltips
        }).draw();
      }, this);
      return this;
    },
		draw : function(ease){
			var easingDecimal = ease || 1;
			this.clear();

			var ctx = this.chart.ctx;

			this.scale.draw(easingDecimal);

			//Draw all the bars for each dataset
			helpers.each(this.datasets,function(dataset,datasetIndex){
				helpers.each(dataset.bars,function(bar,index){
          bar.transition({
            x : this.scale.calculateX(index),
            y : this.scale.calculateY(datasetIndex+1),
            width : this.scale.calculateBoxWidth()+1,
            height : this.scale.calculateBoxHeight()+1
          }, easingDecimal).draw();
				},this);
			},this);
		}
	});

}).call(this);
<|endoftext|>


<commit_before>$("select[id^=id_grade]").each(function(e) { $(this).val(10);});

$("fieldset").each(function(e){
    $this = $(this);
    var textarea = $this.find("textarea");

    $this.find("div[id^=id_dim_] p").each(function(e){
        var id = $(this).attr('id');

        // console.log("textarea="+textarea);
        var t = $(this).text();
        var ptn1 = new RegExp(/^.*?Requirements /);
        var ptn2 = new RegExp(/\s?(Did |Is |Are |Does )the /);
        var s = t.replace(ptn1, "").replace(ptn2, "This ").replace("essay at least", "essay is at least");
        var s = replace_past_tense(s, textarea);
        // console.log(s);
    });
});

var message ="This student provided a great work on this difficult subject. The essay was well-written and easy to read. The explanations deepened my understandings. Thank you for your work. Good job!";
$("#id_feedbackauthor_editoreditable").text(message);
$("#id_feedbackauthor_editor").val(message);

function replace_past_tense(s, textarea) {
    // "This student refer" の "refer" を取得
    var verb = get_word(s,3);
    verb = String(verb).replace(",", "");
    // console.log("verb="+verb);
    // referを 過去形 referred に変換
    var past = get_past_tense(verb, s, textarea);
}

// get n-th word
function get_word(s,n){
    return s.split(/\s+/).slice(n-1,n);
}

function get_past_tense(verb, s, textarea) {
    var url = "https://tensify.herokuapp.com/" + verb;

    $.ajax({
        async : false,
        type: "GET",
        url: url,
        dataType: "text"
    }).done(function(past) {
        // console.log("res="+past);
        update_textarea(s, verb, past, textarea);
    });
}

function update_textarea(s, verb, past, textarea) {

    // console.log("past="+past);

    var ptn = new RegExp("(.*?)" + verb + "(.*)");
    out = s.replace(ptn, "$1" + past + "$2").replace("?", ".");
    console.log(out);
    $(textarea).val(out);
}
<commit_msg>Update assess.js<commit_after>$("select[id^=id_grade], select[id^=id_grade__idx_]").each(function(e) {
         var point = $(this).find("option").eq(1).val();
         $(this).val(point);
});

$("fieldset").each(function(e){
    $this = $(this);
    var textarea = $this.find("textarea");

    // 説明文
    explanation = $this.find("div[id^=id_dim_] p");
    if ( ! explanation.length ) {
        explanation = $this.find("div[id^=id_dim_]");
    }
    $.each(explanation, function(e){
        var id = $(this).attr('id');

        // console.log("textarea="+textarea);
        var t = $(this).text();
        var ptn1 = new RegExp(/^.*?Requirements /);
        var ptn2 = new RegExp(/\s?(Did |Is |Are |Does )the /);
        var s = t.replace(ptn1, "").replace(ptn2, "This ").replace("essay at least", "essay is at least");
        var s = replace_past_tense(s, textarea);
        // console.log(s);
    });
});

var message ="This student provided a great work on this difficult subject. The essay was well-written and easy to read. The explanations deepened my understandings. Thank you for your work. Good job!";
$("#id_feedbackauthor_editoreditable").text(message);
$("#id_feedbackauthor_editor").val(message);

function replace_past_tense(s, textarea) {
    // "This student refer" の "refer" を取得
    var verb = get_word(s,3);
    verb = String(verb).replace(",", "");
    // console.log("verb="+verb);
    // referを 過去形 referred に変換
    var past = get_past_tense(verb, s, textarea);
}

// get n-th word
function get_word(s,n){
    return s.split(/\s+/).slice(n-1,n);
}

function get_past_tense(verb, s, textarea) {
    var url = "https://tensify.herokuapp.com/" + verb;

    $.ajax({
        async : false,
        type: "GET",
        url: url,
        dataType: "text"
    }).done(function(past) {
        // console.log("res="+past);
        update_textarea(s, verb, past, textarea);
    });
}

function update_textarea(s, verb, past, textarea) {

    // console.log("past="+past);

    var ptn = new RegExp("(.*?)" + verb + "(.*)");
    out = s.replace(ptn, "$1" + past + "$2").replace("?", ".");
    console.log(out);
    $(textarea).val(out);
}
<|endoftext|>


<commit_before>/**********************************************************************************************************************
*   Controller for views/task.view.html
*
*   Manages the displacement of all Homeworks.
*
*   Page is orderd via:
*   Homeworks -> TaskFiles(in the selected HW) -> SubTasks(in the selected TF) -> Submits(of the selected ST)
*
*   Selected Items are stored in $scope, the recieved data from the server in vm
*
*   The Controller is handled in states to fit the current Selection
**********************************************************************************************************************/

(function () {

angular
    .module('app')
    .controller('TasksController', TasksController);

    TasksController.$inject = ['$scope', '$uibModal', 'TaskService', 'FlashService', '$rootScope', '$location', '$filter', '$timeout'];
    function TasksController($scope, $uibModal, TaskService, FlashService, $rootScope, $location, $filter, $timeout) {
        var vm = this;

        $scope.orderReverse = false;
        $scope.orderTaskSetPredicate = 'taskSetName';
        $scope.orderTaskPredicate = 'taskName';
        $scope.orderTablePredicate = 'tableName';
        $scope.search = '';

        $scope.dataTypes = [];
        $scope.tabActive = {
            intensionTables : false,
            intensionForeignKeys : false,
            extension : false,
            tasks : false
        };

        $scope.animationsEnabled = true;

        vm.taskSets = [];
        vm.tasks = [];
        vm.tables = [];
        vm.foreignKeys = [];
        $scope.selectedTaskSet = {};
        $scope.selectedTask = {};
        $scope.selectedTable = {};

        function initController() {
            getAllTaskSets();
        }

        //////////////////////////////777
        //  Fetch initial Data
        //////////////////////////////777

        function getAllTaskSets() {
            if ($rootScope.Tasks.taskSets) {
                vm.taskSets = $rootScope.Tasks.taskSets;
                $scope.getCurrentPath();
            } else {
                TaskService.getAllTaskSets().then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                            console.log(result);
                                vm.taskSets = result;
                                $scope.getCurrentPath();
                            }
                        }
                );

            }

            TaskService.getColumnDefinitionDataTypes().then(
                    function (result) {
                        vm.dataTypes = result;
                    },
                    null
            );
        }

        //////////////////////////////777
        //  Saving data when leaving View
        //  Restoring saved Data and Displaying the correct screen
        //////////////////////////////777

        $scope.keepTabActive = function () {
            $rootScope.Tasks.tabActive = $scope.tabActive;
        }

        $scope.keepTaskSets = function () {
            $rootScope.Tasks.taskSets = vm.taskSets;
        }

        $scope.$on('$locationChangeStart', function(event) {
            $scope.keepTabActive();
            $scope.keepTaskSets();
        });

        $scope.getCurrentPath = function () {
            var path = $rootScope.Tasks;

            console.log(path);
            //Find out if a TaskSet is currently selected
            if (path.selectedTaskSet) {
                $scope.tabActive = path.tabActive;
                $scope.selectTaskSet(path.selectedTaskSet);
            } else {
                return;
            }

        }

        //////////////////////////////777
        //  TaskSet - Control
        //////////////////////////////777

        /* Data */
        $scope.taskSetSelectionStatus = {
            taskSetSelected : false
        }

        var DefaultTaskSet = function() {
            this.taskSetName = "";
            this.tableDefinitions = [];
            this.foreignKeyRelations = [];
            this.tasks=[];
            this.isHomeWork = false;
        };

        /* Methods */
        $scope.pushNewTaskSet = function () {
            vm.taskSets.push(new DefaultTaskSet());
        }

        $scope.selectTaskSet = function(taskSet, destination) {
            var index = findInArray(vm.taskSets, taskSet);
            selectTaskSet(index);
            $scope.tabActive.intensionTables = true;
        }

        function selectTaskSet (taskSetIndex) {
            $scope.selectedTable = undefined;
            $scope.selectedTask = undefined;
            $scope.selectedTaskSet = vm.taskSets[taskSetIndex];
            vm.tasks = $scope.selectedTaskSet.tasks;
            vm.tables = $scope.selectedTaskSet.tableDefinitions;
            vm.foreignKeyRelations = $scope.selectedTaskSet.foreignKeyRelations;
            $rootScope.Tasks.selectedTaskSet = $scope.selectedTaskSet;
        }

        $scope.viewTaskSetComments = function(taskSet) {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/comment.template.html',
                    controller: 'CommentController',
                    resolve: {
                        commentTaskObject: function() {
                            return {content: taskSet, type: 'taskSet'};
                        }
                    }
            });

            modalInstance.result.then(
            FlashService.Clear,
            null
            );
        }

        /* Server Side Methods */
        $scope.saveTaskSet = function(taskSet) {
            if (taskSet.id != undefined) {

                return TaskService.editTaskSet(taskSet, taskSet.id).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Updated TaskSet");
                            }
                        }
                );

            } else {
                return TaskService.createTaskSet(taskSet).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Created new TaskSet");
                                vm.taskSets[findInArray(vm.taskSets, taskSet)] = result;
                            }
                        }
                );

            }
        }

        $scope.exportTaskSets = function() {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/exportTaskSet.template.html',
                    controller: 'exportTaskSetController'
            });

            modalInstance.result.then(
                function (taskSetIds) {
                    return TaskService.exportTaskSets({taskSetIds: taskSetIds});
                }, null
            );
        }

        $scope.importTaskSets = function() {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/importTaskSet.template.html',
                    controller: 'importTaskSetController'
            });
        }

        $scope.saveSelectedTaskSet = function () {
             $scope.saveTaskSet($scope.selectedTaskSet);
        }

        $scope.deleteTaskSet = function (taskSet) {
            if (taskSet.id === undefined) {
                vm.taskSets.splice(findInArray(vm.taskSets, taskSet), 1);
                return;
            }

            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return " Are you sure you want to delete TaskSet: " + taskSet.taskSetName + "?
 It will be deleted forever!";
                            }
                    }
            });

            modalInstance.result
            .then(
                function () {
                    return TaskService.deleteTaskSet(taskSet.id);
                },
                null
            ).then(
                 function () {
                     vm.taskSets.splice(findInArray(vm.taskSets, taskSet), 1);
                 },
                 function (error) {
                         if (error.message) {
                             FlashService.Error(error.message);
                         }
                     }
            );
        }

        $scope.rateTaskSet = function (taskSet, decision) {
            var ratingJson = {};
            switch (decision) {
                case 'positive': {
                    ratingJson = {'positive': 1, 'needReview': 0, 'negative': 0};
                    break;
                }
                case 'needReview': {
                    ratingJson = {'positive': 0, 'needReview': 1, 'negative': 0};
                    break;
                }
                case 'negative': {
                    ratingJson = {'positive': 0, 'needReview': 0, 'negative': 1};
                    break;
                }
            }

            TaskService.rateTaskSet(taskSet.id, ratingJson).then(
                function (result) {
                    if (result.error) {
                        FlashService.Error(result.message);
                    } else {
                        vm.taskSets[findInArray(vm.taskSets, taskSet)] = result;
                    }
            });
        }

        //////////////////////////////777
        //  Intension: TableDefinition - Control
        //////////////////////////////777

        /* Data */
        $scope.tableSelectionStatus = {
            tableSelected : false,
            tableNotSelected : true
        }

        var DefaultTable = function () {
            this.tableName = "";
            this.columns = [];
            this.extension = "";
        }

        /* Methods */
        $scope.pushNewTable = function () {
            vm.tables.push(new DefaultTable());
        }

        $scope.selectTable = function (table) {
            var index = findInArray(vm.tables, table);
            selectTable(index);
            $scope.tableSelectionStatus.tableNotSelected = false;
            $scope.tableSelectionStatus.tableSelected = true;
        }

        function selectTable(tableIndex) {
            $scope.selectedTable = vm.tables[tableIndex];
            $rootScope.Tasks.selectedTable = $scope.selectedTable;
            vm.columns = $scope.selectedTable.columns;
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteTable = function (table) {
            vm.tables.splice(findInArray(vm.tables, table), 1);
        }

        //////////////////////////////777
        //  Intension: TableDefinition: Column - Control
        //////////////////////////////777

        /* Data */
        var DefaultColumn = function () {
            this.columnName = "";
            this.dataType = "bigint"
            this.notNull = true;
            this.primaryKey = false;
        }

        /* Methods */
        $scope.pushNewColumn = function () {
            vm.columns.push(new DefaultColumn());
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteColumn = function (column) {
            vm.columns.splice(findInArray(vm.columns, column), 1);
        }

        //////////////////////////////777
        //  Tasks: Control
        //////////////////////////////777

        /* Data */
        var DefaultForeignKey = function () {
            this.sourceTable = "";
            this.sourceColumn = "";
            this.destinationTable = "";
            this.destinationColumn = "";
        }

        /* Methods */
        $scope.pushNewForeignKey = function () {
            vm.foreignKeyRelations.push(new DefaultForeignKey());
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteForeignKey = function (foreignKey) {
            vm.foreignKeyRelations.splice(findInArray(vm.foreignKeyRelations, foreignKey), 1);
        }

        //////////////////////////////777
        //  Tasks: Control
        //////////////////////////////777

        /* Data */
        var DefaultTask = function () {
            this.taskSet = $scope.selectedTaskSet.id;
            this.taskName = "";
            this.refStatement = "";
            this.evaluationStrategy = 1;
            this.points = 1;
            this.requiredTerm = 0;
            this.isCollapsed = true;
            this.availableSyntaxChecks = 0;
            this.availableSemanticChecks = 0;
        }

        /* Methods */

        $scope.pushNewTask = function () {
            vm.tasks.push(new DefaultTask());
        }

        $scope.viewTaskComments = function(task) {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/comment.template.html',
                    controller: 'CommentController',
                    resolve: {
                        commentTaskObject: function() {
                            return {content: task, type: 'task'};
                        }
                    }
            });

            modalInstance.result.then(
            FlashService.Clear,
            null
            );
        }

        /* Server Side Methods */
        $scope.saveTask = function (task) {
            if (task.id != undefined) {
                TaskService.editTask(task.id, task).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Updated Task");
                            }
                        }
                );
            } else {
                TaskService.createTask(task.taskSet, task).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {

                                /* Let's put in the new values we just created in BackEnd */
                                vm.tasks[findInArray(vm.tasks, task)] = result;

                                FlashService.Success("Created new Task");
                            }
                        }
                );
            }
        }

        $scope.deleteTask = function (task) {
            /* If not in Database, we don't need to do much */
            if (task.id === undefined) {
                vm.tasks.splice(findInArray(vm.tasks, task), 1);
                return;
            }

            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return " Are you sure you want to delete Task: " + task.taskName + "?
 It will be deleted forever!";
                            }
                    }
            });

            modalInstance.result
            .then(
                function () {
                    return TaskService.deleteTask(task.id);
                },
                null
            ).then(
                 function () {
                     vm.tasks.splice(findInArray(vm.tasks, task), 1);
                 },
                 function (error) {
                         if (error.message) {
                             FlashService.Error(error.message);
                         }
                     }
            );
        }

        $scope.rateTask = function (task, decision) {
                    var ratingJson = {};
                    switch (decision) {
                        case 'positive': {
                            ratingJson = {'positive': 1, 'needReview': 0, 'negative': 0};
                            break;
                        }
                        case 'needReview': {
                            ratingJson = {'positive': 0, 'needReview': 1, 'negative': 0};
                            break;
                        }
                        case 'negative': {
                            ratingJson = {'positive': 0, 'needReview': 0, 'negative': 1};
                            break;
                        }
                    }
                    TaskService.rateTask(task.id, ratingJson).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                console.log($scope.tabActive);
                                vm.tasks[findInArray(vm.tasks, task)] = result;
                            }
                    });
                }

        //////////////////////////////777
        //  HomeWork Deletion
        //////////////////////////////777

/*
        $scope.deleteHomework = function (taskSet) {
            var taskSetIndex = findInArray(vm.taskSets, taskSet);
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return "Are you sure you want to delete Homework: " + vm.taskSets[taskSetIndex].name + "?\nRemember, that only Homeworks with no submits until now can be deleted.";
                            }
                    }
            });

            modalInstance.result.then(function (result) {
                if (result == true) {
                    TaskService.deleteHomework(vm.taskSets[taskSetIndex].id).then(
                        initController
                    );
                }
            });
        }
*/

        //////////////////////////////777
        //  Array functions
        //////////////////////////////777

        function findInArray(array, item) {
            for (var i = 0; i < array.length; i++) {
                if (array[i].$$hashKey === item.$$hashKey) {
                    return i;
                }
            }
            return -1;
        }

        $scope.findColumnsForTableName = function (tableName) {
            var columns = [];
            for (var i = 0; i < vm.tables.length; i++) {
                if (vm.tables[i].tableName === tableName) {
                    for (var j = 0; j < vm.tables[i].columns.length; j++) {
                        columns.push(vm.tables[i].columns[j].columnName);
                    }
                }
            }
            return columns;
        }

        initController();
    }
})();

<commit_msg>2 small to mention<commit_after>/**********************************************************************************************************************
*   Controller for views/task.view.html
*
*   Manages the displacement of all Homeworks.
*
*   Page is orderd via:
*   Homeworks -> TaskFiles(in the selected HW) -> SubTasks(in the selected TF) -> Submits(of the selected ST)
*
*   Selected Items are stored in $scope, the recieved data from the server in vm
*
*   The Controller is handled in states to fit the current Selection
**********************************************************************************************************************/

(function () {

angular
    .module('app')
    .controller('TasksController', TasksController);

    TasksController.$inject = ['$scope', '$uibModal', 'TaskService', 'FlashService', '$rootScope', '$location', '$filter', '$timeout'];
    function TasksController($scope, $uibModal, TaskService, FlashService, $rootScope, $location, $filter, $timeout) {
        var vm = this;

        $scope.orderReverse = false;
        $scope.orderTaskSetPredicate = 'taskSetName';
        $scope.orderTaskPredicate = 'taskName';
        $scope.orderTablePredicate = 'tableName';
        $scope.search = '';

        $scope.dataTypes = [];
        $scope.tabActive = {
            intensionTables : false,
            intensionForeignKeys : false,
            extension : false,
            tasks : false
        };

        $scope.animationsEnabled = true;

        vm.taskSets = [];
        vm.tasks = [];
        vm.tables = [];
        vm.foreignKeys = [];
        $scope.selectedTaskSet = {};
        $scope.selectedTask = {};
        $scope.selectedTable = {};

        function initController() {
            getAllTaskSets();
        }

        //////////////////////////////777
        //  Fetch initial Data
        //////////////////////////////777

        function getAllTaskSets() {
            if ($rootScope.Tasks.taskSets) {
                vm.taskSets = $rootScope.Tasks.taskSets;
                $scope.getCurrentPath();
            } else {
                TaskService.getAllTaskSets().then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                            console.log(result);
                                vm.taskSets = result;
                                $scope.getCurrentPath();
                            }
                        }
                );

            }

            TaskService.getColumnDefinitionDataTypes().then(
                    function (result) {
                        vm.dataTypes = result;
                    },
                    null
            );
        }

        //////////////////////////////777
        //  Saving data when leaving View
        //  Restoring saved Data and Displaying the correct screen
        //////////////////////////////777

        $scope.keepTabActive = function () {
            $rootScope.Tasks.tabActive = $scope.tabActive;
        }

        $scope.keepTaskSets = function () {
            $rootScope.Tasks.taskSets = vm.taskSets;
        }

        $scope.$on('$locationChangeStart', function(event) {
            $scope.keepTabActive();
            $scope.keepTaskSets();
        });

        $scope.getCurrentPath = function () {
            var path = $rootScope.Tasks;

            console.log(path);
            //Find out if a TaskSet is currently selected
            if (path.selectedTaskSet) {
                $scope.tabActive = path.tabActive;
                $scope.selectTaskSet(path.selectedTaskSet);
            } else {
                return;
            }

        }

        //////////////////////////////777
        //  TaskSet - Control
        //////////////////////////////777

        /* Data */
        $scope.taskSetSelectionStatus = {
            taskSetSelected : false
        }

        var DefaultTaskSet = function() {
            this.taskSetName = "";
            this.tableDefinitions = [];
            this.foreignKeyRelations = [];
            this.tasks=[];
            this.isHomeWork = false;
        };

        /* Methods */
        $scope.pushNewTaskSet = function () {
            vm.taskSets.push(new DefaultTaskSet());
        }

        $scope.selectTaskSet = function(taskSet, destination) {
            var index = findInArray(vm.taskSets, taskSet);
            selectTaskSet(index);
            $scope.tabActive.intensionTables = true;
        }

        function selectTaskSet (taskSetIndex) {
            $scope.selectedTable = undefined;
            $scope.selectedTask = undefined;
            $scope.selectedTaskSet = vm.taskSets[taskSetIndex];
            vm.tasks = $scope.selectedTaskSet.tasks;
            vm.tables = $scope.selectedTaskSet.tableDefinitions;
            vm.foreignKeyRelations = $scope.selectedTaskSet.foreignKeyRelations;
            $rootScope.Tasks.selectedTaskSet = $scope.selectedTaskSet;
        }

        $scope.viewTaskSetComments = function(taskSet) {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/comment.template.html',
                    controller: 'CommentController',
                    resolve: {
                        commentTaskObject: function() {
                            return {content: taskSet, type: 'taskSet'};
                        }
                    }
            });

            modalInstance.result.then(
            FlashService.Clear,
            null
            );
        }

        /* Server Side Methods */
        $scope.saveTaskSet = function(taskSet) {
            if (taskSet.id != undefined) {

                return TaskService.editTaskSet(taskSet, taskSet.id).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Updated TaskSet");
                            }
                        }
                );

            } else {
                return TaskService.createTaskSet(taskSet).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Created new TaskSet");
                                vm.taskSets[findInArray(vm.taskSets, taskSet)] = result;
                            }
                        }
                );

            }
        }

        $scope.exportTaskSets = function() {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/exportTaskSet.template.html',
                    controller: 'exportTaskSetController'
            });

            modalInstance.result.then(
                function (taskSetIds) {
                    return TaskService.exportTaskSets({taskSetIds: taskSetIds});
                }, null
            );
        }

        $scope.importTaskSets = function() {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/importTaskSet.template.html',
                    controller: 'importTaskSetController'
            });
        }

        $scope.saveSelectedTaskSet = function () {
             $scope.saveTaskSet($scope.selectedTaskSet);
        }

        $scope.deleteTaskSet = function (taskSet) {
            if (taskSet.id === undefined) {
                vm.taskSets.splice(findInArray(vm.taskSets, taskSet), 1);
                return;
            }

            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return " Are you sure you want to delete TaskSet: " + taskSet.taskSetName + "?
 It will be deleted forever!";
                            }
                    }
            });

            modalInstance.result
            .then(
                function () {
                    return TaskService.deleteTaskSet(taskSet.id);
                },
                null
            ).then(
                 function () {
                     vm.taskSets.splice(findInArray(vm.taskSets, taskSet), 1);
                 },
                 function (error) {
                         if (error.message) {
                             FlashService.Error(error.message);
                         }
                     }
            );
        }

        $scope.rateTaskSet = function (taskSet, decision) {
            var ratingJson = {};
            switch (decision) {
                case 'positive': {
                    ratingJson = {'positive': 1, 'needReview': 0, 'negative': 0};
                    break;
                }
                case 'needReview': {
                    ratingJson = {'positive': 0, 'needReview': 1, 'negative': 0};
                    break;
                }
                case 'negative': {
                    ratingJson = {'positive': 0, 'needReview': 0, 'negative': 1};
                    break;
                }
            }

            TaskService.rateTaskSet(taskSet.id, ratingJson).then(
                function (result) {
                    if (result.error) {
                        FlashService.Error(result.message);
                    } else {
                        vm.taskSets[findInArray(vm.taskSets, taskSet)] = result;
                    }
            });
        }

        //////////////////////////////777
        //  Intension: TableDefinition - Control
        //////////////////////////////777

        /* Data */
        $scope.tableSelectionStatus = {
            tableSelected : false,
            tableNotSelected : true
        }

        var DefaultTable = function () {
            this.tableName = "";
            this.columns = [];
            this.extension = "";
        }

        /* Methods */
        $scope.pushNewTable = function () {
            vm.tables.push(new DefaultTable());
        }

        $scope.selectTable = function (table) {
            var index = findInArray(vm.tables, table);
            selectTable(index);
            $scope.tableSelectionStatus.tableNotSelected = false;
            $scope.tableSelectionStatus.tableSelected = true;
        }

        function selectTable(tableIndex) {
            $scope.selectedTable = vm.tables[tableIndex];
            $rootScope.Tasks.selectedTable = $scope.selectedTable;
            vm.columns = $scope.selectedTable.columns;
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteTable = function (table) {
            vm.tables.splice(findInArray(vm.tables, table), 1);
        }

        //////////////////////////////777
        //  Intension: TableDefinition: Column - Control
        //////////////////////////////777

        /* Data */
        var DefaultColumn = function () {
            this.columnName = "";
            this.dataType = "BIGINT"
            this.notNull = true;
            this.primaryKey = false;
        }

        /* Methods */
        $scope.pushNewColumn = function () {
            vm.columns.push(new DefaultColumn());
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteColumn = function (column) {
            vm.columns.splice(findInArray(vm.columns, column), 1);
        }

        //////////////////////////////777
        //  Tasks: Control
        //////////////////////////////777

        /* Data */
        var DefaultForeignKey = function () {
            this.sourceTable = "";
            this.sourceColumn = "";
            this.destinationTable = "";
            this.destinationColumn = "";
        }

        /* Methods */
        $scope.pushNewForeignKey = function () {
            vm.foreignKeyRelations.push(new DefaultForeignKey());
        }

        /* Changes are only changed on the Server via TaskSet Actions */
        $scope.deleteForeignKey = function (foreignKey) {
            vm.foreignKeyRelations.splice(findInArray(vm.foreignKeyRelations, foreignKey), 1);
        }

        //////////////////////////////777
        //  Tasks: Control
        //////////////////////////////777

        /* Data */
        var DefaultTask = function () {
            this.taskSet = $scope.selectedTaskSet.id;
            this.taskName = "";
            this.refStatement = "";
            this.evaluationStrategy = 1;
            this.points = 1;
            this.requiredTerm = 0;
            this.isCollapsed = true;
            this.availableSyntaxChecks = 0;
            this.availableSemanticChecks = 0;
        }

        /* Methods */

        $scope.pushNewTask = function () {
            vm.tasks.push(new DefaultTask());
        }

        $scope.viewTaskComments = function(task) {
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/comment.template.html',
                    controller: 'CommentController',
                    resolve: {
                        commentTaskObject: function() {
                            return {content: task, type: 'task'};
                        }
                    }
            });

            modalInstance.result.then(
            FlashService.Clear,
            null
            );
        }

        /* Server Side Methods */
        $scope.saveTask = function (task) {
            if (task.id != undefined) {
                TaskService.editTask(task.id, task).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                FlashService.Success("Updated Task");
                            }
                        }
                );
            } else {
                TaskService.createTask(task.taskSet, task).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {

                                /* Let's put in the new values we just created in BackEnd */
                                vm.tasks[findInArray(vm.tasks, task)] = result;

                                FlashService.Success("Created new Task");
                            }
                        }
                );
            }
        }

        $scope.deleteTask = function (task) {
            /* If not in Database, we don't need to do much */
            if (task.id === undefined) {
                vm.tasks.splice(findInArray(vm.tasks, task), 1);
                return;
            }

            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return " Are you sure you want to delete Task: " + task.taskName + "?
 It will be deleted forever!";
                            }
                    }
            });

            modalInstance.result
            .then(
                function () {
                    return TaskService.deleteTask(task.id);
                },
                null
            ).then(
                 function () {
                     vm.tasks.splice(findInArray(vm.tasks, task), 1);
                 },
                 function (error) {
                         if (error.message) {
                             FlashService.Error(error.message);
                         }
                     }
            );
        }

        $scope.rateTask = function (task, decision) {
                    var ratingJson = {};
                    switch (decision) {
                        case 'positive': {
                            ratingJson = {'positive': 1, 'needReview': 0, 'negative': 0};
                            break;
                        }
                        case 'needReview': {
                            ratingJson = {'positive': 0, 'needReview': 1, 'negative': 0};
                            break;
                        }
                        case 'negative': {
                            ratingJson = {'positive': 0, 'needReview': 0, 'negative': 1};
                            break;
                        }
                    }
                    TaskService.rateTask(task.id, ratingJson).then(
                        function (result) {
                            if (result.error) {
                                FlashService.Error(result.message);
                            } else {
                                console.log($scope.tabActive);
                                vm.tasks[findInArray(vm.tasks, task)] = result;
                            }
                    });
                }

        //////////////////////////////777
        //  HomeWork Deletion
        //////////////////////////////777

/*
        $scope.deleteHomework = function (taskSet) {
            var taskSetIndex = findInArray(vm.taskSets, taskSet);
            var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'adminapp/templates/sure.template.html',
                    controller: 'sureTemplateController',
                    resolve: {
                        sureTemplateMessage: function () {
                                return "Are you sure you want to delete Homework: " + vm.taskSets[taskSetIndex].name + "?\nRemember, that only Homeworks with no submits until now can be deleted.";
                            }
                    }
            });

            modalInstance.result.then(function (result) {
                if (result == true) {
                    TaskService.deleteHomework(vm.taskSets[taskSetIndex].id).then(
                        initController
                    );
                }
            });
        }
*/

        //////////////////////////////777
        //  Array functions
        //////////////////////////////777

        function findInArray(array, item) {
            for (var i = 0; i < array.length; i++) {
                if (array[i].$$hashKey === item.$$hashKey) {
                    return i;
                }
            }
            return -1;
        }

        $scope.findColumnsForTableName = function (tableName) {
            var columns = [];
            for (var i = 0; i < vm.tables.length; i++) {
                if (vm.tables[i].tableName === tableName) {
                    for (var j = 0; j < vm.tables[i].columns.length; j++) {
                        columns.push(vm.tables[i].columns[j].columnName);
                    }
                }
            }
            return columns;
        }

        initController();
    }
})();

<|endoftext|>


<commit_before>const $ = require('jquery')
const elementsToUpdate = ['.l-menu__menu', '.l-menu__aside']

module.exports = {
  /**
   * Makes an ajax call to the current page and updates the elements menu and
   * progress.
   */
  updateDashboard () {
    $.get(window.location.pathname, { dataType: 'html' }, function (data) {
      const selector = elementsToUpdate.join(', ')
      const $newElements = $(data).find(selector)
      const $oldElements = $(selector)

      $oldElements.each(function (i, e) {
        $(e).replaceWith($newElements.eq(i))
      })
    })
  }
}
<commit_msg>assets/dashboard.js: add dashboard reload id to ensure reloads when no l- class used<commit_after>const $ = require('jquery')
const elementsToUpdate = ['.l-menu__menu', '.l-menu__aside', '#update_dashboard']

module.exports = {
  /**
   * Makes an ajax call to the current page and updates the elements menu and
   * progress.
   */
  updateDashboard () {
    $.get(window.location.pathname, { dataType: 'html' }, function (data) {
      const selector = elementsToUpdate.join(', ')
      const $newElements = $(data).find(selector)
      const $oldElements = $(selector)

      $oldElements.each(function (i, e) {
        $(e).replaceWith($newElements.eq(i))
      })
    })
  }
}
<|endoftext|>


<commit_before>var test = require('mocha').it,
  expect = require('chai').expect;

function fibonacci(n) {
      var fibs = [];
      var a = 1, b = 2, f = 1;
      if (n>0) {
        if (n===1) {
          fibs = [1];
        } else if (n===2) {
          fibs = [1, 2];
        } else {
          fibs = [1, 2];
          for(var i = 3; i <= n; i++) {
              f = a + b;
              a = b;
              b = f;
              fibs.push(f);
          }
        }
      }
      return fibs
  };
test('generating the Fibonacci sequence', function(){
  expect(fibonacci(0)).to.deep.equal([ ]);
  expect(fibonacci(1)).to.deep.equal([ 1 ]);
  expect(fibonacci(2)).to.deep.equal([ 1, 2 ]);
  expect(fibonacci(4)).to.deep.equal([1, 2, 3, 5 ]);
  // ...ad nauseum.
}); // END test(fibonacci)

// Hey, where's `fibonacci`...? Uh oh...

test('just even numbers?', function(){
  expect(evens([ ])).to.deep.equal([ ]);
  expect(evens([ 1 ])).to.deep.equal([ ]);
  expect(evens([ 1, 1, 1 ])).to.deep.equal([ ]);
  expect(evens([ 2 ])).to.deep.equal([ 2 ]);
  expect(evens([ 1, 2 ])).to.deep.equal([ 2 ]);
  // More tests, perhaps?
}); // END test(evens)

test('summing lists of Number', function(){
  assert.equal(sum([ ]), 0);
  assert.equal(sum([ 1 ]), 1);
  assert.equal(sum([ 1, 1 ]), 2);
  // ...et cetera, et cetera, et cetera.
}); // END test(sum)

// You expect me to write `sum`, too?

test('summing even Fibonacci numbers?', function(){
  expect( sum(evens(fibonacci(0))) ).to.equal(FILL_ME_IN); // nice.
  // There really should be more code in here...
}); // END test(dat CHAIN tho)
<commit_msg>beastmode for fib<commit_after>var test = require('mocha').it,
  expect = require('chai').expect;

function fibonacci(n) {
      var fibs = [];
      var a = 1, b = 2, f = 1;
      if (n>0) {
        if (n===1) {
          fibs = [1];
        } else if (n===2) {
          fibs = [1, 2];
        } else {
          fibs = [1, 2];
          for(var i = 3; i <= n; i++) {
              f = a + b;
              a = b;
              b = f;
              fibs.push(f);
          }
        }
      }
      return fibs
  };
  function evens(hulk) {
  //"Hulk smach punny odd numbers"
    var evenArr=[];
    for (var i = 0; i < hulk.length; i++) {
      if ((hulk[i] % 2) != 1) {
        evenArr.push(hulk[i]);
      }
    }
    return evenArr;
  }

  function sum(array){
    var sumresults = 0;
    for (var i = 0; i < array.length; i++) {
      // long way of saying below line - sumresults = sumresults + array[i];
      sumresults += array[i];
    }
    return sumresults;

  }
test('generating the Fibonacci sequence', function(){
  expect(fibonacci(0)).to.deep.equal([ ]);
  expect(fibonacci(1)).to.deep.equal([ 1 ]);
  expect(fibonacci(2)).to.deep.equal([ 1, 2 ]);
  expect(fibonacci(4)).to.deep.equal([1, 2, 3, 5 ]);
  // ...ad nauseum.
}); // END test(fibonacci)

// Hey, where's `fibonacci`...? Uh oh...

test('just even numbers?', function(){
  expect(evens([ ])).to.deep.equal([ ]);
  expect(evens([ 1 ])).to.deep.equal([ ]);
  expect(evens([ 1, 1, 1 ])).to.deep.equal([ ]);
  expect(evens([ 2 ])).to.deep.equal([ 2 ]);
  expect(evens([ 1, 2 ])).to.deep.equal([ 2 ]);
  expect(evens([ 1, 2, 44, 2347987, 77, 448922 ])).to.deep.equal([ 2, 44, 448922 ]);
  expect(evens([ 0 ])).to.deep.equal([0]);
  // More tests, perhaps?
}); // END test(evens)

test('summing lists of Number', function(){
  expect(sum([ ])).to.deep.equal(0);
  expect(sum([ 1 ])).to.deep.equal(1);
  expect(sum([ 1, 1 ])).to.deep.equal(2);
  //assert.equal(sum([ ]), 0);
  //assert.equal(sum([ 1 ]), 1);
  //assert.equal(sum([ 1, 1 ]), 2);
  // ...et cetera, et cetera, et cetera.
}); // END test(sum)

// You expect me to write `sum`, too?

test('summing even Fibonacci numbers?', function(){
  expect( sum(evens(fibonacci(0))) ).to.equal(0); // nice.
  expect( sum(evens(fibonacci(4))) ).to.equal(2);
  expect( sum(evens(fibonacci(10))) ).to.equal(44);
  expect( sum(evens(fibonacci(50))) ).to.equal(26658145586);
  //Beastmode answer
  expect( sum(evens(fibonacci(32))) ).to.equal(4613732);
}); // END test(dat CHAIN tho)
<|endoftext|>


<commit_before>/**
 * Created by visitante on 14/06/2017.
 */
const express = require('express')
const app = express()
const fs = require('fs');
app.use(express.static('public'));
//Ruta Informacion
app.post('/informacion', function (req, res) {
    fs.readFile('Informacion.txt', 'utf8',
        function(err, data) {
            if (err) throw err;
            console.log(data);
            res.send(data);
        });
})
//Ruta Facultad de Sistemas
app.get('/facultaddesistemas', function (req, res) {
    res.send('Facultad de Sistemas')
})

//Ruta Cabeceras
app.post('/cabeceras', function (req, res) {
    res.append('fecha',new Date()); //cabecera 1
    res.append('Metodo',req.method); //cabecera 2
    res.append('Direccion-ip',req.ip); //cabecera 3
    res.append('url-original', req.originalUrl); //cabecera 4
    res.append('protocolo',req.protocol); //cabecera 5
    res.send();
})
app.listen(8080, function () {
    console.log('Example app listening on port 8080!')
})

<commit_msg>cookies fin parte 1<commit_after>/**
 * Created by visitante on 14/06/2017.
 */
const express = require('express')
const app = express()
const fs = require('fs');
app.use(express.static('public'));
//ejemplo
app.get('/bienvenido', function (req, res) {
    res.send('Hello World!')
})

//Ruta Informacion
app.post('/informacion', function (req, res) {
    fs.readFile('Informacion.txt', 'utf8',
        function(err, data) {
            if (err) throw err;
            console.log(data);
            res.send(data);
        });
})
//Ruta Facultad de Sistemas
app.get('/facultaddesistemas', function (req, res) {
    res.send('Facultad de Sistemas')
})

//Ruta Cabeceras
app.post('/cabeceras', function (req, res) {
    res.append('fecha',new Date()); //cabecera 1
    res.append('Metodo',req.method); //cabecera 2
    res.append('Direccion-ip',req.ip); //cabecera 3
    res.append('url-original', req.originalUrl); //cabecera 4
    res.append('protocolo',req.protocol); //cabecera 5
    res.send();
})

//Ruta SetCookies

app.get('/setcookie', function (req, res) {
    res.cookie('pachacama', 24)
    res.send('Cookie seteada')
})

//Ruta ClearCookie
app.get('/clearcookie', function (req, res) {
    res.clearCookie("pachacama")
    res.send('Cookie eliminada')
})
app.listen(8080, function () {
    console.log('Example app listening on port 8080!')
})

<|endoftext|>


<commit_before>import { Command } from 'substance'

export default class AddEntityCommand extends Command {
  getCommandState () {
    return { disable: false }
  }
  execute () {
    console.info('MEH')
  }
}<commit_msg>Enable AddEntityCommand.<commit_after>import { Command } from 'substance'

export default class AddEntityCommand extends Command {
  getCommandState () {
    return { disabled: false }
  }
  execute () {
    console.info('MEH')
  }
}<|endoftext|>