<commit_before>import * as d3 from 'd3'
import { Card } from './card.js'
import { Sparkline } from './sparkline.js'
import { accounting } from 'lib/shared'

export class SimpleCard extends Card {
  constructor(divClass, json, value, cardName, valueType) {
    super(divClass)

    this.dataType = this.div.attr('data-type');

    var trend = this.div.attr('data-trend');
    var freq = this.div.attr('data-freq');

    var parseDate = freq === 'daily' ? d3.timeParse('%Y-%m-%d') : freq === 'monthly' ? d3.timeParse('%Y-%m') : d3.timeParse('%Y');
    var parsedDate = parseDate(json.data[0].date);
    var formatDate = d3.timeFormat("%b %Y");

    var divCard = $('div[class*="' + divClass.replace('.','') + '"]');

    divCard.find("div.indicator_widget.padded").find("div.widget_body").find("div.sparkline").empty();

    // If no data exists for the selected year.
    if(parsedDate.getFullYear() != window.populateDataYear.currentYear) {
      divCard.remove();
      return;
    }

    this.div.selectAll('.tw-sharer')
      .attr('target', '_blank')
      .attr('href', 'https://twitter.com/intent/tweet?text=' + I18n.t('gobierto_common.visualizations.where') + encodeURI(window.populateData.municipalityName) + ': ' +  encodeURI(I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title')).toLowerCase() + I18n.t('gobierto_common.visualizations.time') + encodeURI(formatDate(parsedDate).toLowerCase()) + ', ' + encodeURI(this._printData(value))  + '&url=' + window.location.href + '&via=gobierto&source=webclient');

    this.div.selectAll('.fb-sharer')
      .attr('target', '_blank')
      .attr('href', 'https://www.facebook.com/sharer/sharer.php?u=' + window.location.href);

    this.div.select('.widget_figure')
      .text(this._printData(value));

    // If the data is 0
    if (divCard.find("div.indicator_widget.padded").find("div.widget_body").find("span.widget_figure").text() == 0)
      divCard.remove()

    // Append source
    this.div.selectAll('.widget_src')
      .attr('title', json.metadata.indicator['source name'])
      .text(json.metadata.indicator['source name']);

    // Append date of last data point
    this.div.selectAll('.widget_updated')
      .text(formatDate(parsedDate));

    // Append update frequency
    this.div.selectAll('.widget_freq')
      .text(this._printFreq(json.metadata.frequency_type));

    // Append metadata
    this.div.selectAll('.widget_title')
      .attr('title', I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title'))
      .text(I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title'));

    // Append backface info
    this.div.selectAll('.js-data-desc')
      .text(json.metadata.indicator.description);
    this.div.selectAll('.js-data-freq')
      .text(formatDate(parsedDate));

    if (typeof json.data[1] !== 'undefined') {
      var spark = new Sparkline(divClass + ' .sparkline', json.data, { trend, freq });
      spark.render();

      var pctChange = valueType ? (value / json.data[1][valueType] * 100) - 100 : (value / json.data[1].value * 100) - 100
      var pctFormat = accounting.formatNumber(pctChange, 2) + '%';
      var isPositive = pctChange > 0;

      // If is a positive change, attach a plus sign to the number
      this.div.select('.widget_pct')
        .text(function() { return isPositive ? '+' + pctFormat : pctFormat; });

      // Return the correct icon
      this.div.select('.widget_pct')
        .append('i')
        .attr('aria-hidden', 'true')
        .attr('class', function() {
          return isPositive ? 'fa fa-caret-up' : 'fa fa-caret-down';
        });
    }
  }
}
<commit_msg>Don't remove card if the data is missing<commit_after>import * as d3 from 'd3'
import { Card } from './card.js'
import { Sparkline } from './sparkline.js'
import { accounting } from 'lib/shared'

export class SimpleCard extends Card {
  constructor(divClass, json, value, cardName, valueType) {
    super(divClass)

    this.dataType = this.div.attr('data-type');

    var trend = this.div.attr('data-trend');
    var freq = this.div.attr('data-freq');

    var parseDate = freq === 'daily' ? d3.timeParse('%Y-%m-%d') : freq === 'monthly' ? d3.timeParse('%Y-%m') : d3.timeParse('%Y');
    var parsedDate = parseDate(json.data[0].date);
    var formatDate = d3.timeFormat("%b %Y");

    var divCard = $('div[class*="' + divClass.replace('.','') + '"]');

    divCard.find("div.indicator_widget.padded").find("div.widget_body").find("div.sparkline").empty();

    this.div.selectAll('.tw-sharer')
      .attr('target', '_blank')
      .attr('href', 'https://twitter.com/intent/tweet?text=' + I18n.t('gobierto_common.visualizations.where') + encodeURI(window.populateData.municipalityName) + ': ' +  encodeURI(I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title')).toLowerCase() + I18n.t('gobierto_common.visualizations.time') + encodeURI(formatDate(parsedDate).toLowerCase()) + ', ' + encodeURI(this._printData(value))  + '&url=' + window.location.href + '&via=gobierto&source=webclient');

    this.div.selectAll('.fb-sharer')
      .attr('target', '_blank')
      .attr('href', 'https://www.facebook.com/sharer/sharer.php?u=' + window.location.href);

    this.div.select('.widget_figure')
      .text(this._printData(value));

    // If the data is 0
    if (divCard.find("div.indicator_widget.padded").find("div.widget_body").find("span.widget_figure").text() == 0)
      divCard.remove()

    // Append source
    this.div.selectAll('.widget_src')
      .attr('title', json.metadata.indicator['source name'])
      .text(json.metadata.indicator['source name']);

    // Append date of last data point
    this.div.selectAll('.widget_updated')
      .text(formatDate(parsedDate));

    // Append update frequency
    this.div.selectAll('.widget_freq')
      .text(this._printFreq(json.metadata.frequency_type));

    // Append metadata
    this.div.selectAll('.widget_title')
      .attr('title', I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title'))
      .text(I18n.t('gobierto_common.visualizations.cards.' + cardName + '.title'));

    // Append backface info
    this.div.selectAll('.js-data-desc')
      .text(json.metadata.indicator.description);
    this.div.selectAll('.js-data-freq')
      .text(formatDate(parsedDate));

    if (typeof json.data[1] !== 'undefined') {
      var spark = new Sparkline(divClass + ' .sparkline', json.data, { trend, freq });
      spark.render();

      var pctChange = valueType ? (value / json.data[1][valueType] * 100) - 100 : (value / json.data[1].value * 100) - 100
      var pctFormat = accounting.formatNumber(pctChange, 2) + '%';
      var isPositive = pctChange > 0;

      // If is a positive change, attach a plus sign to the number
      this.div.select('.widget_pct')
        .text(function() { return isPositive ? '+' + pctFormat : pctFormat; });

      // Return the correct icon
      this.div.select('.widget_pct')
        .append('i')
        .attr('aria-hidden', 'true')
        .attr('class', function() {
          return isPositive ? 'fa fa-caret-up' : 'fa fa-caret-down';
        });
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import ColumnHeader from './column_header';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';

const easingOutQuint = (x, t, b, c, d) => c*((t=t/d-1)*t*t*t*t + 1) + b;

const scrollTop = (node) => {
  const startTime = Date.now();
  const offset    = node.scrollTop;
  const targetY   = -offset;
  const duration  = 1000;
  let interrupt   = false;

  const step = () => {
    const elapsed    = Date.now() - startTime;
    const percentage = elapsed / duration;

    if (percentage > 1 || interrupt) {
      return;
    }

    node.scrollTop = easingOutQuint(0, elapsed, offset, targetY, duration);
    requestAnimationFrame(step);
  };

  step();

  return () => {
    interrupt = true;
  };
};

class Column extends React.PureComponent {

  static propTypes = {
    heading: PropTypes.string,
    icon: PropTypes.string,
    children: PropTypes.node,
    active: PropTypes.bool,
    hideHeadingOnMobile: PropTypes.bool,
  };

  handleHeaderClick = () => {
    const scrollable = this.node.querySelector('.scrollable');
    if (!scrollable) {
      return;
    }
    this._interruptScrollAnimation = scrollTop(scrollable);
  }

  handleScroll = debounce(() => {
    if (typeof this._interruptScrollAnimation !== 'undefined') {
      this._interruptScrollAnimation();
    }
  }, 200)

  setRef = (c) => {
    this.node = c;
  }

  render () {
    const { heading, icon, children, active, hideHeadingOnMobile } = this.props;

    let columnHeaderId = null;
    let header = '';

<<<<<<< HEAD:app/assets/javascripts/components/features/ui/components/column.jsx
    if (typeof heading === 'string') {
      columnHeaderId = heading.replace(/ /g, '-')
=======
    if (heading) {
      columnHeaderId = heading.replace(/ /g, '-');
>>>>>>> 8963f8c3c2630bfcc377a5ca0513eef5a6b2a4bc:app/javascript/mastodon/features/ui/components/column.js
      header = <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} hideOnMobile={hideHeadingOnMobile} columnHeaderId={columnHeaderId}/>;
    } else if (heading) {
      header = <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} />;
    }
    return (
      <div
        ref={this.setRef}
        role='region'
        aria-labelledby={columnHeaderId}
        className='column'
        onScroll={this.handleScroll}>
        {header}
        {children}
      </div>
    );
  }

}

<<<<<<< HEAD:app/assets/javascripts/components/features/ui/components/column.jsx
Column.propTypes = {
  heading: PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.node]),
  icon: PropTypes.string,
  children: PropTypes.node,
  active: PropTypes.bool,
  hideHeadingOnMobile: PropTypes.bool
};

=======
>>>>>>> 8963f8c3c2630bfcc377a5ca0513eef5a6b2a4bc:app/javascript/mastodon/features/ui/components/column.js
export default Column;
<commit_msg>Resolve a merged conflict - app/javascript/mastodon/features/ui/components/column.js<commit_after>import React from 'react';
import ColumnHeader from './column_header';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';

const easingOutQuint = (x, t, b, c, d) => c*((t=t/d-1)*t*t*t*t + 1) + b;

const scrollTop = (node) => {
  const startTime = Date.now();
  const offset    = node.scrollTop;
  const targetY   = -offset;
  const duration  = 1000;
  let interrupt   = false;

  const step = () => {
    const elapsed    = Date.now() - startTime;
    const percentage = elapsed / duration;

    if (percentage > 1 || interrupt) {
      return;
    }

    node.scrollTop = easingOutQuint(0, elapsed, offset, targetY, duration);
    requestAnimationFrame(step);
  };

  step();

  return () => {
    interrupt = true;
  };
};

class Column extends React.PureComponent {

  static propTypes = {
    heading: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
    icon: PropTypes.string,
    children: PropTypes.node,
    active: PropTypes.bool,
    hideHeadingOnMobile: PropTypes.bool,
  };

  handleHeaderClick = () => {
    const scrollable = this.node.querySelector('.scrollable');
    if (!scrollable) {
      return;
    }
    this._interruptScrollAnimation = scrollTop(scrollable);
  }

  handleScroll = debounce(() => {
    if (typeof this._interruptScrollAnimation !== 'undefined') {
      this._interruptScrollAnimation();
    }
  }, 200)

  setRef = (c) => {
    this.node = c;
  }

  render () {
    const { heading, icon, children, active, hideHeadingOnMobile } = this.props;

    let columnHeaderId = null;
    let header = '';

    if (typeof heading === 'string') {
      columnHeaderId = heading.replace(/ /g, '-')
      header = <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} hideOnMobile={hideHeadingOnMobile} columnHeaderId={columnHeaderId}/>;
    } else if (heading) {
      header = <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} />;
    }
    return (
      <div
        ref={this.setRef}
        role='region'
        aria-labelledby={columnHeaderId}
        className='column'
        onScroll={this.handleScroll}>
        {header}
        {children}
      </div>
    );
  }

}

export default Column;
<|endoftext|>


<commit_before>function DataNavigationBuilder () {
    _.superClass(DataNavigationBuilder, this);
}

_.inherit(DataNavigationBuilder, ElementBuilder);

_.extend(DataNavigationBuilder.prototype, {

    createElement: function (params) {
        return new DataNavigation(params.parent);
    },

    applyMetadata: function (params) {
        ElementBuilder.prototype.applyMetadata.call(this, params);

        var element = params.element;
        var metadata = params.metadata;

        if (Array.isArray(metadata.AvailablePageSizes)) {
            element.getAvailablePageSizes().reset(metadata.AvailablePageSizes);
        }

        var ds = this.findDataSource(params);
        if (ds) {
            element.setDataSource(ds);
            element.setPageNumber(ds.getPageNumber());
            element.setPageSize(ds.getPageSize());

            element.onPageNumberChanged(function (context, message) {
                ds.setPageNumber(message.value);
            });

            element.onPageSizeChanged(function (context, message) {
                ds.setPageSize(message.value);
            });
        } else {
            console.error('DataSource not found');
        }

    },

    findDataSource: function (params) {
        var
            name = params.metadata.DataSource,
            parent = params.parent,
            view,
            context,
            dataSource;

        if (parent) {
            view = parent.getView()
        }
        if (name && view) {
            context = view.getContext();
            dataSource = context.dataSources[name];
        }

        return dataSource;
    }

});<commit_msg>UI-1646: DataNavigation не может найти DataSource#resolve<commit_after>function DataNavigationBuilder () {
    _.superClass(DataNavigationBuilder, this);
}

_.inherit(DataNavigationBuilder, ElementBuilder);

_.extend(DataNavigationBuilder.prototype, {

    createElement: function (params) {
        return new DataNavigation(params.parent);
    },

    applyMetadata: function (params) {
        ElementBuilder.prototype.applyMetadata.call(this, params);

        var element = params.element;
        var metadata = params.metadata;

        if (Array.isArray(metadata.AvailablePageSizes)) {
            element.getAvailablePageSizes().reset(metadata.AvailablePageSizes);
        }

        var ds = this.findDataSource(params);
        if (ds) {
            element.setDataSource(ds);
            element.setPageNumber(ds.getPageNumber());
            element.setPageSize(ds.getPageSize());

            element.onPageNumberChanged(function (context, message) {
                ds.setPageNumber(message.value);
            });

            element.onPageSizeChanged(function (context, message) {
                ds.setPageSize(message.value);
            });
        } else {
            console.error('DataSource not found');
        }

    },

    findDataSource: function (params) {
        var
            name = params.metadata.DataSource,
            view = params.parentView,
            context,
            dataSource;

        if (name && view) {
            context = view.getContext();
            dataSource = context.dataSources[name];
        }

        return dataSource;
    }

});<|endoftext|>


<commit_before>/* eslint-disable */
console.log('%cMade with Kittn ','color: #02C3EF; font-size: 30px; font-weight: bold;');
console.log('%cGet your 🐱 here: http://kittn.de', 'font-weight: bold; color: #000; font-size: 12px;');
console.log('--------------------');
console.log('%cAUTHOR: Sascha Fuchs (@gisugosu) & Lars Eichler (@cinkon)', 'font-weight: bold');
console.log('--------------------');
/* eslint-enable */
<commit_msg>More Advertising :p<commit_after>/* eslint-disable */
console.log(`%c
kkkkkkkk             iiii          tttt               tttt
k::::::k            i::::i      ttt:::t            ttt:::t
k::::::k             iiii       t:::::t            t:::::t
k::::::k                        t:::::t            t:::::t
 k:::::k    kkkkkkkiiiiiiittttttt:::::tttttttttttttt:::::ttttttt  nnnn  nnnnnnnn
 k:::::k   k:::::k i:::::it:::::::::::::::::tt:::::::::::::::::t  n:::nn::::::::nn
 k:::::k  k:::::k   i::::it:::::::::::::::::tt:::::::::::::::::t  n::::::::::::::nn
 k:::::k k:::::k    i::::itttttt:::::::tttttttttttt:::::::tttttt  nn:::::::::::::::n
 k::::::k:::::k     i::::i      t:::::t            t:::::t          n:::::nnnn:::::n
 k:::::::::::k      i::::i      t:::::t            t:::::t          n::::n    n::::n
 k:::::::::::k      i::::i      t:::::t            t:::::t          n::::n    n::::n
 k::::::k:::::k     i::::i      t:::::t    tttttt  t:::::t    ttttttn::::n    n::::n
k::::::k k:::::k   i::::::i     t::::::tttt:::::t  t::::::tttt:::::tn::::n    n::::n
k::::::k  k:::::k  i::::::i     tt::::::::::::::t  tt::::::::::::::tn::::n    n::::n
k::::::k   k:::::k i::::::i       tt:::::::::::tt    tt:::::::::::ttn::::n    n::::n
kkkkkkkk    kkkkkkkiiiiiiii         ttttttttttt        ttttttttttt  nnnnnn    nnnnnn`, 'color: #02C3EF;')
console.log('%cGet your 🐱 here: https://www.npmjs.com/package/generator-kittn - 📘 here: http://kittn.de', 'font-weight: bold; font-size: 12px;');
console.log('--------------------');
console.log('%cAUTHOR: Sascha Fuchs (@gisugosu) and Lars Eichler (@cinkon)', 'font-weight: bold');
console.log('--------------------');
/* eslint-enable */
<|endoftext|>


<commit_before>/*
 * mobile select unit tests
 */

(function($){
	var mouseUpTouchEnd = $.support.touch ? "touchend" : "mouseup",
			libName = "jquery.mobile.forms.select.js";

	module(libName);

	test( "a large select menu should come up in a dialog many times", function(){
		var menu, select = $("#select-choice-many-container a");

		// bring up the dialog
		select.trigger(mouseUpTouchEnd);
		menu = $("#select-choice-many-menu");
		same(menu.parents('.ui-dialog').length, 1);

		// select and close the dialog
		menu.parents('ui-dialog').find("span.ui-icon-delete").click();

		//bring up the dialog again
		select.trigger(mouseUpTouchEnd);
		same(menu.parents('.ui-dialog').length, 1);
	});

	test( "firing a click at least 400 ms later on the select screen overlay does close it", function(){
		$.Event.prototype.originalEvent = {
			touches: [ 'foo' ]
		};

		$("#select-choice-few-button").trigger(mouseUpTouchEnd);

		// click the first menu item
		setTimeout(function(){
			$("#select-choice-few-menu a:first").click();
		}, 400);

		// verify the menu is hidden
		setTimeout(function(){
			same($("#select-choice-few-menu").parent(".ui-selectmenu-hidden").length, 1);
			start();
		}, 500);

		stop();
	});

	test( "selects marked with data-native-menu=true should use a div as their button", function(){
		same($("#select-choice-native-container div.ui-btn").length, 1);
	});

	test( "selects marked with data-native-menu=true should not have a custom menu", function(){
		same($("#select-choice-native-container ul").length, 0);
	});
})(jQuery);<commit_msg>added a test to make sure the select element is inside the div-based button when native option is true<commit_after>/*
 * mobile select unit tests
 */

(function($){
	var mouseUpTouchEnd = $.support.touch ? "touchend" : "mouseup",
			libName = "jquery.mobile.forms.select.js";

	module(libName);

	test( "a large select menu should come up in a dialog many times", function(){
		var menu, select = $("#select-choice-many-container a");

		// bring up the dialog
		select.trigger(mouseUpTouchEnd);
		menu = $("#select-choice-many-menu");
		same(menu.parents('.ui-dialog').length, 1);

		// select and close the dialog
		menu.parents('ui-dialog').find("span.ui-icon-delete").click();

		//bring up the dialog again
		select.trigger(mouseUpTouchEnd);
		same(menu.parents('.ui-dialog').length, 1);
	});

	test( "firing a click at least 400 ms later on the select screen overlay does close it", function(){
		$.Event.prototype.originalEvent = {
			touches: [ 'foo' ]
		};

		$("#select-choice-few-button").trigger(mouseUpTouchEnd);

		// click the first menu item
		setTimeout(function(){
			$("#select-choice-few-menu a:first").click();
		}, 400);

		// verify the menu is hidden
		setTimeout(function(){
			same($("#select-choice-few-menu").parent(".ui-selectmenu-hidden").length, 1);
			start();
		}, 500);

		stop();
	});

	test( "selects marked with data-native-menu=true should use a div as their button", function(){
		same($("#select-choice-native-container div.ui-btn").length, 1);
	});

	test( "selects marked with data-native-menu=true should not have a custom menu", function(){
		same($("#select-choice-native-container ul").length, 0);
	});

	test( "selects marked with data-native-menu=true should sit inside the button", function(){
		same($("#select-choice-native-container div.ui-btn select").length, 1);
	});
})(jQuery);<|endoftext|>


<commit_before>"use strict";

describe("Schemas", function() {
    var Schemas, mockSchemasResource, $httpBackend;

    beforeEach(module("bibframeEditor"));
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get("$httpBackend");
        mockSchemasResource = $injector.get("Schemas");
        $httpBackend.expectGET("./schema/bibframe.n3").respond("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .");
    }));

    afterEach(function() {
        $httpBackend.flush();
    });

    describe("get", function() {
        it("should call get", function() {
            var result = mockSchemasResource.get("bibframe.n3");

            result.success(function(r) {
                expect(r).toMatch(/^@prefix rdf/);
            });
        });
    });
});
<commit_msg>remove unused var<commit_after>"use strict";

describe("Schemas", function() {
    var mockSchemasResource, $httpBackend;

    beforeEach(module("bibframeEditor"));
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get("$httpBackend");
        mockSchemasResource = $injector.get("Schemas");
        $httpBackend.expectGET("./schema/bibframe.n3").respond("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .");
    }));

    afterEach(function() {
        $httpBackend.flush();
    });

    describe("get", function() {
        it("should call get", function() {
            var result = mockSchemasResource.get("bibframe.n3");

            result.success(function(r) {
                expect(r).toMatch(/^@prefix rdf/);
            });
        });
    });
});
<|endoftext|>


<commit_before>var primoViewHasLoaded = setInterval(function() {
    //wait for primo's angular to load itself (eg replaces primo-explore contents with angular contents, then insert header)
    if (document.querySelector('noscript') === null || typeof(document.querySelector('noscript')) === 'undefined' ) {
        clearInterval(primoViewHasLoaded);
        loadReusableComponents();
    }
}, 50);

function loadReusableComponents() {
    // insert elements, even before Polymer is loaded
    // first element of the original document
    // var firstElement = document.querySelector('primo-explore');
    var firstElement = document.body; //.children[0];

    // insert header inside primo's view
    var header = document.createElement('uq-minimal-header');
    header.setAttribute("show-login-button", "false");
    // firstElement.insertBefore(header, firstElement.firstChild);

    // insert alerts inside primo's view
    var alerts = document.createElement('uqlibrary-alerts');
    // firstElement.insertBefore(alerts, firstElement.firstChild);

    // while new PrimoUI has infinite scrolling, do not include footer

    // // insert sub footer before body-tag
    // var subFooter = document.createElement('uql-connect-footer');
    // document.body.appendChild(subFooter);
    //
    // // insert footer before body-tag
    // var footer = document.createElement('uq-minimal-footer');
    // document.body.appendChild(footer);

    window.addEventListener('WebComponentsReady', function() {
        // when polymer is ready - configure elements
        // header.showLoginButton = false;
    });
}

//enable GTM
// (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
//     new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
//     j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
//     'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
// })(window,document,'script','dataLayer','GTM-W4KK37');

<commit_msg>troubleshooting download issue<commit_after>var primoViewHasLoaded = setInterval(function() {
    //wait for primo's angular to load itself (eg replaces primo-explore contents with angular contents, then insert header)
    if (document.querySelector('noscript') === null || typeof(document.querySelector('noscript')) === 'undefined' ) {
        clearInterval(primoViewHasLoaded);
        loadReusableComponents();
    }
}, 50);

function loadReusableComponents() {
    // insert elements, even before Polymer is loaded
    // first element of the original document
    var firstElement = document.querySelector('primo-explore');
    // var firstElement = document.body; //.children[0];

    // insert header inside primo's view
    var header = document.createElement('uq-minimal-header');
    header.setAttribute("show-login-button", "false");
    firstElement.insertBefore(header, firstElement.firstChild);

    // insert alerts inside primo's view
    var alerts = document.createElement('uqlibrary-alerts');
    firstElement.insertBefore(alerts, firstElement.firstChild);

    // while new PrimoUI has infinite scrolling, do not include footer

    // // insert sub footer before body-tag
    // var subFooter = document.createElement('uql-connect-footer');
    // document.body.appendChild(subFooter);
    //
    // // insert footer before body-tag
    // var footer = document.createElement('uq-minimal-footer');
    // document.body.appendChild(footer);

    window.addEventListener('WebComponentsReady', function() {
        // when polymer is ready - configure elements
        // header.showLoginButton = false;
    });
}

//enable GTM
// (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
//     new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
//     j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
//     'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
// })(window,document,'script','dataLayer','GTM-W4KK37');

<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose');
var serviceToSchools = mongoose.model('serviceToSchools');

var modelClass = require('../modelClass');
var renderModel = new modelClass.RenderModel(serviceToSchools, 'serviceToSchools/serviceToSchools.tex', 'serviceToSchools/na.tex');

var is = require('is-js');

/*
will explicitly populate the report with
the data you provide
*/
renderModel.setDebugPopulate( false, {
	service: 'Service to schools goes here...'
});

/*
will explicitly print the N/A latex
to the screen for debugging purposes
*/
renderModel.isDebugNull = false;

/*
render function that finds the obj in the database
and converts it into latex.
*/
module.exports.render = function(req, callback) {
	renderModel.render(req, callback);
};

/*
Gets the data from the frontend and
saves it in the database.
*/
module.exports.submit = function(req, callback) {
	console.log(require('util').inspect(req.body));

	if (is.empty(req.body.serviceToSchools)) return callback(null, null);

	var service = new cserviceToSchools({
		service: req.body.serviceToSchools.service,
		user: req.user
	});

	service.save(function(err) {
		callback(err, service);
	});
};

<commit_msg>fixed typo<commit_after>'use strict';

var mongoose = require('mongoose');
var serviceToSchools = mongoose.model('serviceToSchools');

var modelClass = require('../modelClass');
var renderModel = new modelClass.RenderModel(serviceToSchools, 'serviceToSchools/serviceToSchools.tex', 'serviceToSchools/na.tex');

var is = require('is-js');

/*
will explicitly populate the report with
the data you provide
*/
renderModel.setDebugPopulate( false, {
	service: 'Service to schools goes here...'
});

/*
will explicitly print the N/A latex
to the screen for debugging purposes
*/
renderModel.isDebugNull = false;

/*
render function that finds the obj in the database
and converts it into latex.
*/
module.exports.render = function(req, callback) {
	renderModel.render(req, callback);
};

/*
Gets the data from the frontend and
saves it in the database.
*/
module.exports.submit = function(req, callback) {
	console.log(require('util').inspect(req.body));

	if (is.empty(req.body.serviceToSchools)) return callback(null, null);

	var service = new serviceToSchools({
		service: req.body.serviceToSchools.service,
		user: req.user
	});

	service.save(function(err) {
		callback(err, service);
	});
};

<|endoftext|>


<commit_before>
(function ($) {
    $.fn.dnnModuleActions = function (options) {
        var opts = $.extend({}, $.fn.dnnModuleActions.defaultOptions, options);
        var $self = this;
        var actionButton = opts.actionButton;
        var moduleId = opts.moduleId;
        var tabId = opts.tabId;
        var adminActions = opts.adminActions;
        var adminCount = adminActions.length;
        var customActions = opts.customActions;
        var customCount = customActions.length;
        var panes = opts.panes;
        var supportsMove = opts.supportsMove;
        var count = adminCount + customCount;
        var isShared = opts.IsShared;

        if (count > 0 || supportsMove) {
            var $form = $("body form");
            if ($form.find("div#moduleActions-" + moduleId).length === 0) {
                $form.append("

");
                var menu = $form.find("div:last");
                var menuRoot = menu.find("ul");
                if (customCount > 0) {
                    buildMenu(menuRoot, "Edit", "actionMenuEdit", customActions, customCount);
                }
                if (adminCount > 0) {
                    buildMenu(menuRoot, "Admin", "actionMenuAdmin", adminActions, adminCount);
                }
                if (supportsMove) {
                    buildMoveMenu(menuRoot, "Move", "actionMenuMove");
                }

                if (isShared) {
                    buildSharedMenu(menuRoot, "Shared Module", "dnn_shared");
                }
                watchResize(moduleId);
            }
        }

        function buildMoveMenu(root, rootText, rootClass) {
            var parent = buildMenuRoot(root, rootText, rootClass);
            var modulePane = $(".DnnModule-" + moduleId).parent();
            var paneName = modulePane.attr("id").replace("dnn_", "");

            var htmlString;
            var moduleIndex = -1;
            var id = paneName + moduleId;
            var modules = modulePane.children();
            var moduleCount = modules.length;
            var i;

            for (i = 0; i < moduleCount; i++) {
                var module = modules[i];
                var mid = getModuleId(module);

                if (moduleId == parseInt(mid)) {
                    moduleIndex = i;
                    break;
                }
            }

            //Add Top/Up actions
            if (moduleIndex > 0) {
                //htmlString = "
" + opts.topText + "";
                htmlString = "
" + opts.topText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-top").click(function () {
                    moveTop(paneName);
                });

                //htmlString = "
" + opts.upText + "";
                htmlString = "
" + opts.upText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-up").click(function () {
                    moveUp(paneName, moduleIndex);
                });
            }

            //Add Bottom/Down actions
            if (moduleIndex < moduleCount - 1) {
                //htmlString = "
" + opts.downText + "";
                htmlString = "
" + opts.downText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-down").click(function () {
                    moveDown(paneName, moduleIndex);
                });

                //htmlString = "
" + opts.bottomText + "";
                htmlString = "
" + opts.bottomText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-bottom").click(function () {
                    moveBottom(paneName);
                });
            }

            var htmlStringContainer = "";

            //Add move to pane entries
            for (i = 0; i < panes.length; i++) {
                var pane = panes[i];
                if (paneName !== pane) {
                    id = pane + moduleId;
                    //htmlString = "
" + opts.movePaneText.replace("{0}", pane) + "";
                    htmlStringContainer += "
" + opts.movePaneText.replace("{0}", pane);
                }
            }

            if (htmlStringContainer) {
                // loop is done, append the HTML and add moveToPane function on click event
                parent.append(htmlStringContainer);
                parent.find("li").not('.common').click(function () {
                    moveToPane($(this).attr("id").replace(moduleId, ""));
                });
            }
        }

        function buildMenu(root, rootText, rootClass, actions, actionCount) {
            var $parent = buildMenuRoot(root, rootText, rootClass);

            for (var i = 0; i < actionCount; i++) {
                var action = actions[i];

                if (action.Title !== "~") {
                    if (!action.Url) {
	                    action.Url = "javascript: __doPostBack('" + actionButton + "', '" + action.ID + "')";
                    } else {
	                    action.Url = decodeURIComponent(action.Url);
                    }

                    var htmlString = "
";

                    switch(action.CommandName) {
                        case "DeleteModule.Action":
                            htmlString = "
";
                            break;
                        case "ModuleSettings.Action":
                            htmlString = "
";
                            break;
                        case "ImportModule.Action":
                            htmlString = "
";
                            break;
                        case "ExportModule.Action":
                            htmlString = "
";
                            break;
                        case "ModuleHelp.Action":
                            htmlString = "
";
                            break;
                    }

                    if (isEnabled(action)) {
                        htmlString += "" + action.Title + "";
                    } else {
                        htmlString += "" + action.Title + "";
                    }

                    $parent.append(htmlString);
                }
            }

            $parent.find("#moduleActions-" + moduleId + "-Delete a").dnnConfirm({
                text: opts.deleteText,
                yesText: opts.yesText,
                noText: opts.noText,
                title: opts.confirmTitle
            });
        }

        function buildSharedMenu(root, rootText, rootClass, actions, actionCount) {
            root.append("

" + rootText + "
");
        }

        function buildMenuRoot(root, rootText, rootClass) {
            root.append("

");
            var parent = root.find("li." + rootClass + " > ul");

            return parent;
        }

        function getModuleId(module) {
            var $anchor = $(module).children("a");
            if ($anchor.length === 0) {
                $anchor = $(module).children("div.dnnDraggableContent").children("a");
            }
            return $anchor.attr("name");
        }

        function isEnabled(action) {
            return action.ClientScript || action.Url || action.CommandArgument;
        }

        function moveBottom(targetPane) {
            moveToPane(targetPane);
        }

        function moveDown(targetPane, moduleIndex) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .insertAfter($("#dnn_" + targetPane).children()[moduleIndex])
                    .fadeIn("slow", function () {

                        //update server
                        completeMove(targetPane, ( 2 * moduleIndex + 4));
                    });
            });
        }

        function moveTop(targetPane) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .prependTo($("#dnn_" + targetPane))
                    .fadeIn("slow", function () {
                        //update server
                        completeMove(targetPane, 0);
                    });
            });
        }

        function moveToPane(targetPane) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .appendTo("#dnn_" + targetPane)
                    .fadeIn("slow", function () {

                        //update server
                        completeMove(targetPane, -1);
                    });
            });
        }

        function moveUp(targetPane, moduleIndex) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .insertBefore($("#dnn_" + targetPane).children()[moduleIndex - 1])
                    .fadeIn("slow", function () {
                        //update server
                        completeMove(targetPane, (2 * moduleIndex - 2));
                    });
            });
        }

        function position(mId) {
            var container = $(".DnnModule-" + mId);
            var root = $("#moduleActions-" + mId + " > ul");
            var containerPosition = container.offset();
            var containerWidth = container.width();

            root.css({
                position: "absolute",
                marginLeft: 0,
                marginTop: 0,
                top: containerPosition.top,
                left: containerPosition.left + containerWidth - 65
            });
        }

        function watchResize(mId) {
            var container = $(".DnnModule-" + mId);
            container.data("o-size", { w: container.width(), h: container.height() });
            var loopyFunc = function () {
                var data = container.data("o-size");
                if (data.w != container.width() || data.h != container.height()) {
                    container.data("o-size", { w: container.width(), h: container.height() });
                    container.trigger("resize");
                }

                setTimeout(loopyFunc, 250);
            };

            container.trigger("resize", function () {
                position(mId);
            });

            loopyFunc();
        };

        function completeMove(targetPane, moduleOrder) {
            //remove empty pane class
            $("#dnn_" + targetPane).removeClass("DNNEmptyPane");

            var dataVar = {
                TabId: tabId,
                ModuleId: moduleId,
                Pane: targetPane,
                ModuleOrder: moduleOrder
            };

            var service = $.dnnSF();
            var serviceUrl = $.dnnSF().getServiceRoot("InternalServices") + "ModuleService/";
            $.ajax({
                url: serviceUrl + 'MoveModule',
                type: 'POST',
                data: dataVar,
                beforeSend: service.setModuleHeaders,
                success: function () {
                	window.location.reload();
                },
                error: function () {
                }
            });

            //fire window resize to reposition action menus
            $(window).resize();
        }

        return $self;
    };

    $.fn.dnnModuleActions.defaultOptions = {
        customText: "CustomText",
        adminText: "AdminText",
        moveText: "MoveText",
        topText: "Top",
        upText: "Up",
        downText: "Down",
        bottomText: "Bottom",
        movePaneText: "To {0}"
    };

    // register window resize on ajaxComplete to reposition action menus - only in edit mode
    // after page fully load
    var resizeThrottle;
    $(window).resize(function () {
        if (resizeThrottle) {
            clearTimeout(resizeThrottle);
            resizeThrottle = null;
        }
        resizeThrottle = setTimeout(
            function () {
                var menu = $('.actionMenu');
                menu.each(function () {
                    var $this = $(this);
                    var id = $this.attr('id');
                    if (id) {
                        var mId = id.split('-')[1];
                        var container = $(".DnnModule-" + mId);
                        var root = $('ul.dnn_mact', $this);
                        var containerPosition = container.offset();
                        var containerWidth = container.width();

                        root.css({
                            position: "absolute",
                            marginLeft: 0,
                            marginTop: 0,
                            top: containerPosition.top,
                            left: containerPosition.left + containerWidth - 65
                        });
                    }
                });
                resizeThrottle = null;
            },
            100
        );
    });
    $(window).load(function () {
        $(document).ajaxComplete(function () {
            $(window).resize();
        });
        $(window).resize();
    });

})(jQuery);<commit_msg>DNN-7400 - Ensured that Module Action menu are only added into the main DNN form element<commit_after>
(function ($) {
    $.fn.dnnModuleActions = function (options) {
        var opts = $.extend({}, $.fn.dnnModuleActions.defaultOptions, options);
        var $self = this;
        var actionButton = opts.actionButton;
        var moduleId = opts.moduleId;
        var tabId = opts.tabId;
        var adminActions = opts.adminActions;
        var adminCount = adminActions.length;
        var customActions = opts.customActions;
        var customCount = customActions.length;
        var panes = opts.panes;
        var supportsMove = opts.supportsMove;
        var count = adminCount + customCount;
        var isShared = opts.IsShared;

        if (count > 0 || supportsMove) {
            var $form = $("body#Body form#Form");
            if ($form.find("div#moduleActions-" + moduleId).length === 0) {
                $form.append("

");
                var menu = $form.find("div:last");
                var menuRoot = menu.find("ul");
                if (customCount > 0) {
                    buildMenu(menuRoot, "Edit", "actionMenuEdit", customActions, customCount);
                }
                if (adminCount > 0) {
                    buildMenu(menuRoot, "Admin", "actionMenuAdmin", adminActions, adminCount);
                }
                if (supportsMove) {
                    buildMoveMenu(menuRoot, "Move", "actionMenuMove");
                }

                if (isShared) {
                    buildSharedMenu(menuRoot, "Shared Module", "dnn_shared");
                }
                watchResize(moduleId);
            }
        }

        function buildMoveMenu(root, rootText, rootClass) {
            var parent = buildMenuRoot(root, rootText, rootClass);
            var modulePane = $(".DnnModule-" + moduleId).parent();
            var paneName = modulePane.attr("id").replace("dnn_", "");

            var htmlString;
            var moduleIndex = -1;
            var id = paneName + moduleId;
            var modules = modulePane.children();
            var moduleCount = modules.length;
            var i;

            for (i = 0; i < moduleCount; i++) {
                var module = modules[i];
                var mid = getModuleId(module);

                if (moduleId == parseInt(mid)) {
                    moduleIndex = i;
                    break;
                }
            }

            //Add Top/Up actions
            if (moduleIndex > 0) {
                //htmlString = "
" + opts.topText + "";
                htmlString = "
" + opts.topText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-top").click(function () {
                    moveTop(paneName);
                });

                //htmlString = "
" + opts.upText + "";
                htmlString = "
" + opts.upText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-up").click(function () {
                    moveUp(paneName, moduleIndex);
                });
            }

            //Add Bottom/Down actions
            if (moduleIndex < moduleCount - 1) {
                //htmlString = "
" + opts.downText + "";
                htmlString = "
" + opts.downText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-down").click(function () {
                    moveDown(paneName, moduleIndex);
                });

                //htmlString = "
" + opts.bottomText + "";
                htmlString = "
" + opts.bottomText;
                parent.append(htmlString);

                //Add click event handler to just added element
                parent.find("li#" + id + "-bottom").click(function () {
                    moveBottom(paneName);
                });
            }

            var htmlStringContainer = "";

            //Add move to pane entries
            for (i = 0; i < panes.length; i++) {
                var pane = panes[i];
                if (paneName !== pane) {
                    id = pane + moduleId;
                    //htmlString = "
" + opts.movePaneText.replace("{0}", pane) + "";
                    htmlStringContainer += "
" + opts.movePaneText.replace("{0}", pane);
                }
            }

            if (htmlStringContainer) {
                // loop is done, append the HTML and add moveToPane function on click event
                parent.append(htmlStringContainer);
                parent.find("li").not('.common').click(function () {
                    moveToPane($(this).attr("id").replace(moduleId, ""));
                });
            }
        }

        function buildMenu(root, rootText, rootClass, actions, actionCount) {
            var $parent = buildMenuRoot(root, rootText, rootClass);

            for (var i = 0; i < actionCount; i++) {
                var action = actions[i];

                if (action.Title !== "~") {
                    if (!action.Url) {
	                    action.Url = "javascript: __doPostBack('" + actionButton + "', '" + action.ID + "')";
                    } else {
	                    action.Url = decodeURIComponent(action.Url);
                    }

                    var htmlString = "
";

                    switch(action.CommandName) {
                        case "DeleteModule.Action":
                            htmlString = "
";
                            break;
                        case "ModuleSettings.Action":
                            htmlString = "
";
                            break;
                        case "ImportModule.Action":
                            htmlString = "
";
                            break;
                        case "ExportModule.Action":
                            htmlString = "
";
                            break;
                        case "ModuleHelp.Action":
                            htmlString = "
";
                            break;
                    }

                    if (isEnabled(action)) {
                        htmlString += "" + action.Title + "";
                    } else {
                        htmlString += "" + action.Title + "";
                    }

                    $parent.append(htmlString);
                }
            }

            $parent.find("#moduleActions-" + moduleId + "-Delete a").dnnConfirm({
                text: opts.deleteText,
                yesText: opts.yesText,
                noText: opts.noText,
                title: opts.confirmTitle
            });
        }

        function buildSharedMenu(root, rootText, rootClass, actions, actionCount) {
            root.append("

" + rootText + "
");
        }

        function buildMenuRoot(root, rootText, rootClass) {
            root.append("

");
            var parent = root.find("li." + rootClass + " > ul");

            return parent;
        }

        function getModuleId(module) {
            var $anchor = $(module).children("a");
            if ($anchor.length === 0) {
                $anchor = $(module).children("div.dnnDraggableContent").children("a");
            }
            return $anchor.attr("name");
        }

        function isEnabled(action) {
            return action.ClientScript || action.Url || action.CommandArgument;
        }

        function moveBottom(targetPane) {
            moveToPane(targetPane);
        }

        function moveDown(targetPane, moduleIndex) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .insertAfter($("#dnn_" + targetPane).children()[moduleIndex])
                    .fadeIn("slow", function () {

                        //update server
                        completeMove(targetPane, ( 2 * moduleIndex + 4));
                    });
            });
        }

        function moveTop(targetPane) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .prependTo($("#dnn_" + targetPane))
                    .fadeIn("slow", function () {
                        //update server
                        completeMove(targetPane, 0);
                    });
            });
        }

        function moveToPane(targetPane) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .appendTo("#dnn_" + targetPane)
                    .fadeIn("slow", function () {

                        //update server
                        completeMove(targetPane, -1);
                    });
            });
        }

        function moveUp(targetPane, moduleIndex) {
            var container = $(".DnnModule-" + moduleId);

            //move module to target pane
            container.fadeOut("slow", function () {
                $(this).detach()
                    .insertBefore($("#dnn_" + targetPane).children()[moduleIndex - 1])
                    .fadeIn("slow", function () {
                        //update server
                        completeMove(targetPane, (2 * moduleIndex - 2));
                    });
            });
        }

        function position(mId) {
            var container = $(".DnnModule-" + mId);
            var root = $("#moduleActions-" + mId + " > ul");
            var containerPosition = container.offset();
            var containerWidth = container.width();

            root.css({
                position: "absolute",
                marginLeft: 0,
                marginTop: 0,
                top: containerPosition.top,
                left: containerPosition.left + containerWidth - 65
            });
        }

        function watchResize(mId) {
            var container = $(".DnnModule-" + mId);
            container.data("o-size", { w: container.width(), h: container.height() });
            var loopyFunc = function () {
                var data = container.data("o-size");
                if (data.w != container.width() || data.h != container.height()) {
                    container.data("o-size", { w: container.width(), h: container.height() });
                    container.trigger("resize");
                }

                setTimeout(loopyFunc, 250);
            };

            container.trigger("resize", function () {
                position(mId);
            });

            loopyFunc();
        };

        function completeMove(targetPane, moduleOrder) {
            //remove empty pane class
            $("#dnn_" + targetPane).removeClass("DNNEmptyPane");

            var dataVar = {
                TabId: tabId,
                ModuleId: moduleId,
                Pane: targetPane,
                ModuleOrder: moduleOrder
            };

            var service = $.dnnSF();
            var serviceUrl = $.dnnSF().getServiceRoot("InternalServices") + "ModuleService/";
            $.ajax({
                url: serviceUrl + 'MoveModule',
                type: 'POST',
                data: dataVar,
                beforeSend: service.setModuleHeaders,
                success: function () {
                	window.location.reload();
                },
                error: function () {
                }
            });

            //fire window resize to reposition action menus
            $(window).resize();
        }

        return $self;
    };

    $.fn.dnnModuleActions.defaultOptions = {
        customText: "CustomText",
        adminText: "AdminText",
        moveText: "MoveText",
        topText: "Top",
        upText: "Up",
        downText: "Down",
        bottomText: "Bottom",
        movePaneText: "To {0}"
    };

    // register window resize on ajaxComplete to reposition action menus - only in edit mode
    // after page fully load
    var resizeThrottle;
    $(window).resize(function () {
        if (resizeThrottle) {
            clearTimeout(resizeThrottle);
            resizeThrottle = null;
        }
        resizeThrottle = setTimeout(
            function () {
                var menu = $('.actionMenu');
                menu.each(function () {
                    var $this = $(this);
                    var id = $this.attr('id');
                    if (id) {
                        var mId = id.split('-')[1];
                        var container = $(".DnnModule-" + mId);
                        var root = $('ul.dnn_mact', $this);
                        var containerPosition = container.offset();
                        var containerWidth = container.width();

                        root.css({
                            position: "absolute",
                            marginLeft: 0,
                            marginTop: 0,
                            top: containerPosition.top,
                            left: containerPosition.left + containerWidth - 65
                        });
                    }
                });
                resizeThrottle = null;
            },
            100
        );
    });
    $(window).load(function () {
        $(document).ajaxComplete(function () {
            $(window).resize();
        });
        $(window).resize();
    });

})(jQuery);<|endoftext|>


<commit_before>import { Controller } from "stimulus";

export default class extends Controller {
  static targets = ["source", "select"];
  static values = { options: Array };

  connect() {
    this.populateSelect(parseInt(this.sourceTarget.value));
  }

  handleSelectChange() {
    this.populateSelect(parseInt(this.sourceTarget.value));
  }

  populateSelect(sourceId) {
    const allOptions = this.optionsValue;
    const options = allOptions.find((option) => option[0] === sourceId)[1];
    const selectBox = this.selectTarget;
    selectBox.innerHTML = "";
    options.forEach((item) => {
      const opt = document.createElement("option");
      opt.value = item[1];
      opt.innerHTML = item[0];
      selectBox.appendChild(opt);
    });
  }
}
<commit_msg>Tidy up dependent-select controller<commit_after>import { Controller } from "stimulus";

export default class extends Controller {
  static targets = ["source", "select"];
  static values = { options: Array };

  connect() {
    this.populateSelect(parseInt(this.sourceTarget.value));
  }

  handleSelectChange() {
    this.populateSelect(parseInt(this.sourceTarget.value));
  }

  populateSelect(sourceId) {
    this.removeCurrentOptions()

    this.dependantOptionsFor(sourceId).forEach((item) => {
      this.addOption(item[0], item[1])
    });
  }

  removeCurrentOptions() {
    this.selectTarget.innerHTML = ""
  }

  addOption(label, value) {
    const newOption = document.createElement("option")
    newOption.innerHTML = label
    newOption.value = value
    this.selectTarget.appendChild(newOption)
  }

  dependantOptionsFor(sourceId) {
    return this.optionsValue.find((option) => option[0] === sourceId)[1]
  }
}
<|endoftext|>


<commit_before>var hbs = require('hbs'),
	fs = require('fs'),
	path = require('path'),
	cfg = require('../core/config.js');

/**
 * Excluded Directories and Files
 * @type {{directories: *[], files: *[]}}
 */
var excludes = {
	directories: [
		'_data',
		path.basename(cfg.nitro.view_partials_directory)
	],
	files: [
		'404.' + cfg.nitro.view_file_extension
	]
};

/**
 *
 * @param dir string To-be-traversed Directory
 * @returns {Array} All allowed views
 */
function walk(dir) {
	var results = [],
		files = fs.readdirSync(dir);

	files.forEach(function(file) {
		var filePath = dir + '/' + file,
			stat = fs.statSync(filePath);

		if (stat && stat.isDirectory() && excludes.directories.indexOf(file) === -1) {
			results = results.concat(walk(filePath));
		}
		else if (stat && stat.isFile() && excludes.files.indexOf(file) === -1) {
			var relativePath = path.relative(cfg.nitro.view_directory, filePath),
				ext = path.extname(filePath),
				extReg = new RegExp(ext + '$'),
				name = relativePath.replace(extReg, '').replace(/\//g, ' ').replace(/\\/g, ' ').replace(/\b\w/g, function (w) {
					return w.toUpperCase();
				}),
				url = relativePath.replace(extReg, '').replace(/\//g, '-').replace(/\\/g, '-');

			results.push({
				view_name: name,
				view_url: url
			});
		}
	});

	return results;
}

module.exports = function() {
	var views = walk(cfg.nitro.view_directory),
		markup = ['
'];

	views.forEach(function(view) {
		markup.push('
' + view.view_name + '
');
	});

	markup.push('
');

	return new hbs.handlebars.SafeString(markup.join(''));
};
<commit_msg>Exclude some more files & folders from view list<commit_after>var hbs = require('hbs'),
	fs = require('fs'),
	path = require('path'),
	cfg = require('../core/config.js');

/**
 * Excluded Directories and Files
 * @type {{directories: *[], files: *[]}}
 */
var excludes = {
	directories: [
		'_data',
		path.basename(cfg.nitro.view_partials_directory),
		'.svn'
	],
	files: [
		'404.' + cfg.nitro.view_file_extension,
		'.DS_Store',
		'Thumbs.db',
		'Desktop.ini'
	]
};

/**
 *
 * @param dir string To-be-traversed Directory
 * @returns {Array} All allowed views
 */
function walk(dir) {
	var results = [],
		files = fs.readdirSync(dir);

	files.forEach(function(file) {
		var filePath = dir + '/' + file,
			stat = fs.statSync(filePath);

		if (stat && stat.isDirectory() && excludes.directories.indexOf(file) === -1) {
			results = results.concat(walk(filePath));
		}
		else if (stat && stat.isFile() && excludes.files.indexOf(file) === -1) {
			var relativePath = path.relative(cfg.nitro.view_directory, filePath),
				ext = path.extname(filePath),
				extReg = new RegExp(ext + '$'),
				name = relativePath.replace(extReg, '').replace(/\//g, ' ').replace(/\\/g, ' ').replace(/\b\w/g, function (w) {
					return w.toUpperCase();
				}),
				url = relativePath.replace(extReg, '').replace(/\//g, '-').replace(/\\/g, '-');

			results.push({
				view_name: name,
				view_url: url
			});
		}
	});

	return results;
}

module.exports = function() {
	var views = walk(cfg.nitro.view_directory),
		markup = ['
'];

	views.forEach(function(view) {
		markup.push('
' + view.view_name + '
');
	});

	markup.push('
');

	return new hbs.handlebars.SafeString(markup.join(''));
};
<|endoftext|>


<commit_before>'use strict';
/**
 * @ngdoc function
 * @name com.module.core.controller:HomeCtrl
 * @description Dashboard
 * @requires $scope
 * @requires $rootScope
 **/
angular.module('com.module.core')
  .controller('HomeCtrl', function($scope, $rootScope,Vis,$timeout) {

    $scope.count = {};

    $scope.boxes = $rootScope.dashboardBox;

    $scope.user=$rootScope.currentUser;

    // Visualizations
    $scope.draw=function() {
            // create some nodes
            var nodes=Vis.nodes();
            var edges=Vis.edges();
            console.log('draw invoked!');
            // create a network
            var container = document.getElementById('mynetwork');
            var data = {
                nodes: nodes,
                edges: edges
            };
            var options = {
                nodes: {
                    shape: 'dot',
                    size: 16
                },
                physics: {
                    forceAtlas2Based: {
                        gravitationalConstant: -26,
                        centralGravity: 0.005,
                        springLength: 230,
                        springConstant: 0.18
                    },
                    maxVelocity: 146,
                    solver: 'forceAtlas2Based',
                    timestep: 0.35,
                    stabilization: {iterations: 150}
                }
            };
            var network = new vis.Network(container, data, options);

    };
    $scope.start=function(){
      $timeout($scope.draw,500);
    };

});
<commit_msg>reduce groups in graph<commit_after>'use strict';
/**
 * @ngdoc function
 * @name com.module.core.controller:HomeCtrl
 * @description Dashboard
 * @requires $scope
 * @requires $rootScope
 **/
angular.module('com.module.core')
  .controller('HomeCtrl', function($scope, $rootScope,Vis,$timeout) {

    $scope.count = {};

    $scope.boxes = $rootScope.dashboardBox;

    $scope.user=$rootScope.currentUser;

    // Visualizations
    $scope.draw=function() {
            // create some nodes
            var nodes=Vis.nodes();
            var edges=Vis.edges();
            console.log('draw invoked!');
            // create a network
            var container = document.getElementById('mynetwork');
            var data = {
                nodes: nodes,
                edges: edges
            };
            var options = {
                nodes: {
                    shape: 'dot',
                    size: 16
                },
                physics: {
                    forceAtlas2Based: {
                        gravitationalConstant: -26,
                        centralGravity: 0.005,
                        springLength: 230,
                        springConstant: 0.18
                    },
                    maxVelocity: 146,
                    solver: 'forceAtlas2Based',
                    timestep: 0.35,
                    stabilization: {iterations: 150}
                }
            };
            var network = new vis.Network(container, data, options);

    };
    $scope.start=function(){
      $timeout($scope.draw,10);
    };

});
<|endoftext|>


<commit_before>'use strict';

angular.module('WordRiverApp')
  .controller('WordManagerCtrl', function ($scope, $http, socket, Auth) {
    $scope.currentUser = Auth.getCurrentUser();
    $scope.categoryField = "";
    $scope.addField = "";
    $scope.addType = "";
    $scope.editField = "";
    $scope.editType = "";
    $scope.searchField = "";
    $scope.categoryArray = [];
    $scope.currentUser = Auth.getCurrentUser();
    $scope.selectedCategories = [];
    $scope.allTiles = [];
    $scope.allCatTiles = [];
    $scope.userTiles = [];
    $scope.matchTiles = [];
    $scope.toSort = "tile";
    $scope.order = true;
    $scope.currentCategory = null;
    $scope.currentTile = null;
    $scope.tileId = "";
    $scope.contextTagsTemp = [];
    $scope.showValue = true;
    $scope.wordToEdit = null;
   // $scope.wordToRemove = null;
    //$scope.selectedCategories = [];

    $scope.confirmDelete = function(index) {
      this.index = index;
      if (confirm("Are you sure you want to delete " + $scope.categoryArray[index] + "?") == true) {
        $scope.removeCategory(index);
      }
    };

    $scope.getCategories = function() {
      $http.get('/api/categories').success(function (allCategories) {
        console.log(allCategories);
        for (var i = 0; i < $scope.currentUser.contextPacks.length; i++) {
          for(var j = 0; j < allCategories.length; j++){
            if(allCategories[j]._id == $scope.currentUser.contextPacks[i]){
              $scope.categoryArray.push(allCategories[i]);
            }
          }
        }
      });
    }

    $scope.checkCheckbox = function(category){
      var counter;
        for (var i = 0; i < $scope.selectedCategories.length; i++) {
          if ($scope.selectedCategories[i].tagName == category) {
            $scope.selectedCategories.splice(i, 1);
            counter = 1;
          }
        }
      if (counter != 1){
        $scope.selectedCategories.push({
          tagName:category
        });
      }
    };

    $scope.getCategories();

    $scope.$on('$destroy', function () {
      socket.unsyncUpdates('pack');
    });

    $scope.addCategory = function () {
      if ($scope.categoryField.length >= 1) {
        $scope.categoryArray.push($scope.categoryField);
        $http.patch('/api/users/' + $scope.currentUser._id + '/category',
          {contextPacks: $scope.categoryArray}
        ).success(function(){
          });
      }
      $scope.categoryField="";
      $scope.getCategories();
    };

    $scope.getWords = function(){
      $scope.userTiles = [];
      $http.get('/api/tile').success(function(allTiles) {
        $scope.allTiles = allTiles;
        for(var i= 0; i < $scope.allTiles.length; i++){
          if($scope.currentUser._id == $scope.allTiles[i].creatorID){
            $scope.userTiles.push($scope.allTiles[i]);
          }
        }
      });
    };
    $scope.getWords();

    $scope.addWord = function() {
      if ($scope.addField.length >= 1 && $scope.addType.length >= 1) {
        $http.post('/api/tile', {
          name: $scope.addField,
          contextTags: $scope.selectedCategories,
          creatorID: $scope.currentUser._id,
          wordType: $scope.addType
        });
        $scope.addField = "";
        $scope.getWords();
      }
    };

    $scope.getAllTiles = function(){
      $http.get('/api/tile').success(function (allTiles) {
        $scope.allCatTiles = allTiles;
        for (var i = 0; i < $scope.allCatTiles.length; i++) {
          if ($scope.currentUser._id == $scope.allCatTiles[i].creatorID) {
            $scope.userTiles.push($scope.allCatTiles[i]);
          }
        }
      });
    };

    $scope.getAllTiles();
    //cat is short for category
    $scope.displayCatInfo = function (category) {
      //$scope.userTiles = [];
      $scope.matchTiles = [];
      $scope.currentCategory = category;
      //$http.get('/api/tile').success(function (allTiles) {
        //  $scope.allCatTiles = allTiles;
        //  for (var i = 0; i < $scope.allCatTiles.length; i++) {
        //    if ($scope.currentUser._id == $scope.allCatTiles[i].creatorID) {
        //      $scope.userTiles.push($scope.allCatTiles[i]);
        //    }
        //  }
        for (var j = 0; j < $scope.userTiles.length; j++) {
          for (var z = 0; z < $scope.userTiles[j].contextTags.length; z++) {
            console.log($scope.userTiles[j].contextTags[z].tagName)
            if ($scope.userTiles[j].contextTags[z].tagName == category._id) {
              $scope.matchTiles.push($scope.userTiles[j]);
              //console.log($scope.userTiles[j].name);
            }
          }
        }
        if ($scope.matchTiles.length > 0) {

        } else {
          alert("There are no tiles in this category");
        }

    };

    $scope.getCategoryFromTagName = function(tile, index) {
      for(var i = 0; i < $scope.categoryArray.length; i++){
        //console.log(tile.contextTags[index]);
        if(tile.contextTags[index].tagName == $scope.categoryArray[i]._id){
          $scope.contextTagsTemp.push($scope.categoryArray[i]);
          console.log($scope.categoryArray[i]);
        }
      }
    };

      $scope.displayWordInfo = function (word) {
        $scope.contextTagsTemp = [];
        $scope.currentTile = word;
        //for(var i =0; i < $scope.allTiles.length; i++){
        // //console.log(word.name)
        //  if($scope.allTiles[i]._id == word._id){
        //    if($scope.allTiles[i].contextTags.length > 0) {
        //      for (var j = 0; j < $scope.allTiles[i].contextTags.length; j++){
        //       $scope.getCategoryFromTagName($scope.allTiles[i]);
        //      }
        //      //alert("This tile has the categories:\n" + $scope.contextTagsTemp.join('\n'));
        //    }
        //    else{
        //      //alert("This tile has no categories.");
        //    }
        //  }
        //}

        for (var j = 0; j < word.contextTags.length; j++) {
          console.log(word.contextTags.length);
          $scope.getCategoryFromTagName(word, j);
        }

      };

    //Deletes a category
    $scope.removeCategory = function(index) {
      $scope.categoryArray.splice(index, 1);
      $http.patch('/api/users/'+$scope.currentUser._id+'/category',{
        contextPacks : $scope.categoryArray
      });
    };

      //Removes a word from a category
    $scope.removeFromCategory = function(tile, index) {
      //console.log("test");
      $scope.tileId = tile._id;
      $http.put('/api/tile/' + $scope.tileId + "/removeFromCategory", {category: $scope.currentCategory, tileId: tile._id});
      //console.log("test");
      console.log(tile._id);
      $scope.matchTiles.splice(index, 1);
      //$http.post('/api/packs', {packName: pack.packName, tiles: pack.tiles});
      //$http.delete('/api/packs/' + pack._id);
    };

    //Removes a category from a word, on the server side this does the same thing as removeFromCategory
    $scope.removeCategoryFromWord = function(index) {
      $scope.tileId = $scope.currentTile._id;
      $http.put('/api/tile/' + $scope.tileId + "/removeFromCategory", {category: $scope.contextTagsTemp[index], tileId: $scope.currentTile._id});
      //console.log("test");
      //console.log(tile._id);
      $scope.contextTagsTemp.splice(index, 1);
    };

    //deletes a word
    $scope.removeWord = function(index) {
      $scope.wordToRemove = $scope.userTiles[index];
      $http.delete('/api/tile/'+ $scope.wordToRemove._id);
      $scope.getWords();
      var wordToRemove = $scope.userTiles(index);
      $scope.userTiles.splice(index,1);
      for(var i = 0; i < $scope.allTiles.length; i++){
        if(wordToRemove.id == $scope.allTiles[i].id) {
            $scope.allTiles.splice(i,1);
          }
      }
    };

    $scope.editWord = function(index){
        $scope.editWordIndex = index;
        $scope.showValue = false;
        $scope.wordToEdit = $scope.userTiles[index];
    };

    $scope.updateTile = function(tile) {
      if($scope.editField.length >= 1 && $scope.editType.length < 1){
        //Only editing the word text
        //$http.patch('/api/tiles/',
        //  {contextPacks: $scope.categoryArray}
        //).success(function(){
        //  });
        $scope.editField = "";
      }
      else if($scope.editField.length == 0 && $scope.editType.length >= 1){
        //Only editing the word type
       ;
        $scope.editType = "";
      }
      else if($scope.editField.length >= 1 && $scope.editType.length >= 1){
        //Editing both the word type and the word text

        $scope.editField = "";
        $scope.editType = "";
      }

        $scope.showValue = true;
    }

  });

//Usefull database functions from previous iteration

//exports.removeTileFromCategory = function(req, res, next) {
//  var userId = req.user._id;
//
//  var word = req.body.word;
//  var packId = req.body.packId;
//  User.findById(userId, function (err, user) {
//    for(var i = 0; i < user.tileBucket.length; i++){
//      console.log(word == user.tileBucket[i].wordName);
//      if(word == user.tileBucket[i].wordName){
//        console.log(word);
//        for(var j = 0; j < user.tileBucket[i].tileTags.length; j++){
//          if(user.tileBucket[i].tileTags[j] == packId){
//            console.log(j);
//            user.tileBucket[i].tileTags.splice(j, 1);
//          }
//        }
//      }
//    }
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};

//exports.updatePack = function(req, res, next) {
//  var userId = req.user._id;
//
//  var tagName = req.body.tagName;
//  var packType = req.body.packType;
//
//  User.findById(userId, function (err, user) {
//    user.tileTags.push({"tagName": tagName, "tagType": packType});
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};

//exports.updateTile = function(req, res, next) {
//  var userId = req.user._id;
//
//  var word = req.body.word;
//  var packId = req.body.packId;
//
//  User.findById(userId, function (err, user) {
//    var found = false;
//    for(var i = 0; i < user.tileBucket.length; i++){
//      if(user.tileBucket[i].wordName == word){
//        found = true;
//        user.tileBucket[i].tileTags.push(packId);
//      }
//    }
//    if(!found){
//      user.tileBucket.push({wordName: word, tileTags: [packId]});
//    }
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};
<commit_msg>Worked on the delete category functionality. It's still not quite working.<commit_after>'use strict';

angular.module('WordRiverApp')
  .controller('WordManagerCtrl', function ($scope, $http, socket, Auth) {
    $scope.currentUser = Auth.getCurrentUser();
    $scope.categoryField = "";
    $scope.addField = "";
    $scope.addType = "";
    $scope.editField = "";
    $scope.editType = "";
    $scope.searchField = "";
    $scope.categoryArray = [];
    $scope.currentUser = Auth.getCurrentUser();
    $scope.selectedCategories = [];
    $scope.allTiles = [];
    $scope.allCatTiles = [];
    $scope.userTiles = [];
    $scope.matchTiles = [];
    $scope.toSort = "tile";
    $scope.order = true;
    $scope.currentCategory = null;
    $scope.currentTile = null;
    $scope.tileId = "";
    $scope.contextTagsTemp = [];
    $scope.showValue = true;
    $scope.wordToEdit = null;
   // $scope.wordToRemove = null;
    //$scope.selectedCategories = [];

    $scope.confirmDelete = function(index) {
      this.index = index;
      if (confirm("Are you sure you want to delete " + $scope.categoryArray[index] + "?") == true) {
        $scope.removeCategory(index);
      }
    };

    $scope.getCategories = function() {
      $http.get('/api/categories').success(function (allCategories) {
        console.log(allCategories);
        for (var i = 0; i < $scope.currentUser.contextPacks.length; i++) {
          for(var j = 0; j < allCategories.length; j++){
            if(allCategories[j]._id == $scope.currentUser.contextPacks[i]){
              $scope.categoryArray.push(allCategories[i]);
            }
          }
        }
      });
    }

    $scope.checkCheckbox = function(category){
      var counter;
        for (var i = 0; i < $scope.selectedCategories.length; i++) {
          if ($scope.selectedCategories[i].tagName == category) {
            $scope.selectedCategories.splice(i, 1);
            counter = 1;
          }
        }
      if (counter != 1){
        $scope.selectedCategories.push({
          tagName:category
        });
      }
    };

    $scope.getCategories();

    $scope.$on('$destroy', function () {
      socket.unsyncUpdates('pack');
    });

    $scope.addCategory = function () {
      if ($scope.categoryField.length >= 1) {
        $scope.categoryArray.push($scope.categoryField);
        $http.patch('/api/users/' + $scope.currentUser._id + '/category',
          {contextPacks: $scope.categoryArray}
        ).success(function(){
          });
      }
      $scope.categoryField="";
      $scope.getCategories();
    };

    $scope.getWords = function(){
      $scope.userTiles = [];
      $http.get('/api/tile').success(function(allTiles) {
        $scope.allTiles = allTiles;
        for(var i= 0; i < $scope.allTiles.length; i++){
          if($scope.currentUser._id == $scope.allTiles[i].creatorID){
            $scope.userTiles.push($scope.allTiles[i]);
          }
        }
      });
    };
    $scope.getWords();

    $scope.addWord = function() {
      if ($scope.addField.length >= 1 && $scope.addType.length >= 1) {
        $http.post('/api/tile', {
          name: $scope.addField,
          contextTags: $scope.selectedCategories,
          creatorID: $scope.currentUser._id,
          wordType: $scope.addType
        });
        $scope.addField = "";
        $scope.getWords();
      }
    };

    $scope.getAllTiles = function(){
      $http.get('/api/tile').success(function (allTiles) {
        $scope.allCatTiles = allTiles;
        for (var i = 0; i < $scope.allCatTiles.length; i++) {
          if ($scope.currentUser._id == $scope.allCatTiles[i].creatorID) {
            $scope.userTiles.push($scope.allCatTiles[i]);
          }
        }
      });
    };

    $scope.getAllTiles();
    //cat is short for category
    $scope.displayCatInfo = function (category) {
      //$scope.userTiles = [];
      $scope.matchTiles = [];
      $scope.currentCategory = category;
      //$http.get('/api/tile').success(function (allTiles) {
        //  $scope.allCatTiles = allTiles;
        //  for (var i = 0; i < $scope.allCatTiles.length; i++) {
        //    if ($scope.currentUser._id == $scope.allCatTiles[i].creatorID) {
        //      $scope.userTiles.push($scope.allCatTiles[i]);
        //    }
        //  }
        for (var j = 0; j < $scope.userTiles.length; j++) {
          for (var z = 0; z < $scope.userTiles[j].contextTags.length; z++) {
            console.log($scope.userTiles[j].contextTags[z].tagName)
            if ($scope.userTiles[j].contextTags[z].tagName == category._id) {
              $scope.matchTiles.push($scope.userTiles[j]);
              //console.log($scope.userTiles[j].name);
            }
          }
        }
        if ($scope.matchTiles.length > 0) {

        } else {
          alert("There are no tiles in this category");
        }

    };

    $scope.getCategoryFromTagName = function(tile, index) {
      for(var i = 0; i < $scope.categoryArray.length; i++){
        //console.log(tile.contextTags[index]);
        if(tile.contextTags[index].tagName == $scope.categoryArray[i]._id){
          $scope.contextTagsTemp.push($scope.categoryArray[i]);
          console.log($scope.categoryArray[i]);
        }
      }
    };

      $scope.displayWordInfo = function (word) {
        $scope.contextTagsTemp = [];
        $scope.currentTile = word;
        //for(var i =0; i < $scope.allTiles.length; i++){
        // //console.log(word.name)
        //  if($scope.allTiles[i]._id == word._id){
        //    if($scope.allTiles[i].contextTags.length > 0) {
        //      for (var j = 0; j < $scope.allTiles[i].contextTags.length; j++){
        //       $scope.getCategoryFromTagName($scope.allTiles[i]);
        //      }
        //      //alert("This tile has the categories:\n" + $scope.contextTagsTemp.join('\n'));
        //    }
        //    else{
        //      //alert("This tile has no categories.");
        //    }
        //  }
        //}

        for (var j = 0; j < word.contextTags.length; j++) {
          console.log(word.contextTags.length);
          $scope.getCategoryFromTagName(word, j);
        }

      };

    //Deletes a category
    $scope.removeCategory = function(index) {
      $scope.categoryArray.splice(index, 1);
      var categoryArrayIDS = [];
      for(var i = 0; i < $scope.categoryArray.length; i ++){
        categoryArrayIDS.push($scope.categoryArray[i]._id);
      }
      $http.patch('/api/users/' + $scope.currentUser._id, "/category",{
        contextPacks : categoryArrayIDS
      });
    };

      //Removes a word from a category
    $scope.removeFromCategory = function(tile, index) {
      //console.log("test");
      $scope.tileId = tile._id;
      $http.put('/api/tile/' + $scope.tileId + "/removeFromCategory", {category: $scope.currentCategory, tileId: tile._id});
      //console.log("test");
      console.log(tile._id);
      $scope.matchTiles.splice(index, 1);
      //$http.post('/api/packs', {packName: pack.packName, tiles: pack.tiles});
      //$http.delete('/api/packs/' + pack._id);
    };

    //Removes a category from a word, on the server side this does the same thing as removeFromCategory
    $scope.removeCategoryFromWord = function(index) {
      $scope.tileId = $scope.currentTile._id;
      $http.put('/api/tile/' + $scope.tileId + "/removeFromCategory", {category: $scope.contextTagsTemp[index], tileId: $scope.currentTile._id});
      //console.log("test");
      //console.log(tile._id);
      $scope.contextTagsTemp.splice(index, 1);
    };

    //deletes a word
    $scope.removeWord = function(index) {
      $scope.wordToRemove = $scope.userTiles[index];
      $http.delete('/api/tile/'+ $scope.wordToRemove._id);
      $scope.getWords();
      var wordToRemove = $scope.userTiles(index);
      $scope.userTiles.splice(index,1);
      for(var i = 0; i < $scope.allTiles.length; i++){
        if(wordToRemove.id == $scope.allTiles[i].id) {
            $scope.allTiles.splice(i,1);
          }
      }
    };

    $scope.editWord = function(index){
        $scope.editWordIndex = index;
        $scope.showValue = false;
        $scope.wordToEdit = $scope.userTiles[index];
    };

    $scope.updateTile = function(tile) {
      if($scope.editField.length >= 1 && $scope.editType.length < 1){
        //Only editing the word text
        $scope.tileId = tile._id;

        $http.put('/api/tile/' + $scope.tileId + "/update", {category: $scope.currentCategory, tileId: tile._id});

        $scope.editField = "";
      }
      else if($scope.editField.length == 0 && $scope.editType.length >= 1){
        //Only editing the word type
       ;
        $scope.editType = "";
      }
      else if($scope.editField.length >= 1 && $scope.editType.length >= 1){
        //Editing both the word type and the word text

        $scope.editField = "";
        $scope.editType = "";
      }

        $scope.showValue = true;
    }

  });

//Usefull database functions from previous iteration

//exports.removeTileFromCategory = function(req, res, next) {
//  var userId = req.user._id;
//
//  var word = req.body.word;
//  var packId = req.body.packId;
//  User.findById(userId, function (err, user) {
//    for(var i = 0; i < user.tileBucket.length; i++){
//      console.log(word == user.tileBucket[i].wordName);
//      if(word == user.tileBucket[i].wordName){
//        console.log(word);
//        for(var j = 0; j < user.tileBucket[i].tileTags.length; j++){
//          if(user.tileBucket[i].tileTags[j] == packId){
//            console.log(j);
//            user.tileBucket[i].tileTags.splice(j, 1);
//          }
//        }
//      }
//    }
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};

//exports.updatePack = function(req, res, next) {
//  var userId = req.user._id;
//
//  var tagName = req.body.tagName;
//  var packType = req.body.packType;
//
//  User.findById(userId, function (err, user) {
//    user.tileTags.push({"tagName": tagName, "tagType": packType});
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};

//exports.updateTile = function(req, res, next) {
//  var userId = req.user._id;
//
//  var word = req.body.word;
//  var packId = req.body.packId;
//
//  User.findById(userId, function (err, user) {
//    var found = false;
//    for(var i = 0; i < user.tileBucket.length; i++){
//      if(user.tileBucket[i].wordName == word){
//        found = true;
//        user.tileBucket[i].tileTags.push(packId);
//      }
//    }
//    if(!found){
//      user.tileBucket.push({wordName: word, tileTags: [packId]});
//    }
//    user.save(function(err) {
//      if (err) return validationError(res, err);
//      res.send(200);
//    });
//  });
//};
<|endoftext|>


<commit_before>// wwBenchmark.js
// ==============

/* eslint no-eval: 0 */
/* eslint arrow-body-style: 0 */

'use strict';

const benchmark = require('benchmark');

function getResultMessage (data) {
  const re = /^.*x (\d.*) ops\/sec ±(.*)% \(.*$/;
  let statisticalConfidence = true;
  let resultMessage;

  if (data.testData[0].match(re) && data.testData[1].match(re)) {
    const stats = data.testData.map(datum => {
      return {
        mean: parseInt((datum.match(re)[1]).replace(',', ''), 10),
        pMarginOfError: Number(datum.match(re)[2]) / 100
      };
    }).map(stat => {
      return {
        mean: stat.mean,
        pMarginOfError: stat.pMarginOfError,
        aMarginOfError: stat.mean * stat.pMarginOfError
      };
    });

    const stockRange = [
      stats[0].mean - stats[0].aMarginOfError, stats[0].mean + stats[0].aMarginOfError
    ];

    const userRange = [
      stats[1].mean - stats[1].aMarginOfError, stats[1].mean + stats[1].aMarginOfError
    ];

    if (stockRange[0] <= userRange[1] && stockRange[1] >= userRange[0]) {
      statisticalConfidence = false;
    }

    // there are instances when benchmark.js returns a victor
    // despite unfounded confidence.
    if (statisticalConfidence) {
      if (data.fastest[0] === 'stock test') {
        // stock code faster than user code:
        // return 'stock';
        resultMessage = 'Your code can be made more efficient.';
      }
      // user code faster than stock code:
      // return 'user';
      resultMessage = 'Your code performed better than the stock solution. It\'s blazing fast!';
    }
    // tied between user and stock code:
    // return 'tie';
    resultMessage = 'Tie. Your code is fast!';

    return resultMessage;
  }
}

function startBenchmark (baselineCode, testCode, fnc) {
  // TODO:
  // firm time cutoff regardless of whether test finishes.

  // default options:
  benchmark.options.maxTime = 0.05; // seems to be the minimum for test cycles - 5.
  // benchmark.options.maxTime = Number.NEGATIVE_INFINITY;
  benchmark.options.minSamples = 4;
  // benchmark.options.initCount = 10;

  self.baselineCode = baselineCode.replace(/use strict/g, '');
  self.testCode = testCode.replace(/use strict/g, '');
  self.fnc = fnc;

  const stockTest = {
    name: 'stock test',
    setup () { try { eval(self.baselineCode); } catch (err) { console.error(err); } },
    fn () { eval(fnc); }
  };
  const userTest = {
    name: 'user test',
    setup () { try { eval(testCode); } catch (err) { console.error(err); } },
    fn () { eval(fnc); }
  };

  const suite = benchmark.Suite();

  const results = {
    fastest: null,
    testData: []
  };

  return new Promise(resolve => {
    suite
    .add(stockTest)
    .add(userTest)
    .on('cycle', e => results.testData.push(String(e.target)))
    .on('complete', function () { results.fastest = this.filter('fastest').map('name');
      resolve({
        resultMessage: getResultMessage(results),
        stockPerf: results.testData[0],
        userPerf: results.testData[1]
      });
    })
    .run({ async: true });
  });
}

self.onmessage = e => {
  const stockCode = e.data[0][0];
  const userCode = e.data[0][1];
  const benchmarkFnCall = e.data[1];

  startBenchmark(stockCode, userCode, benchmarkFnCall)
    .then(result => {
      self.postMessage(result);
    });
  /*
  let timeUsed = Number.POSITIVE_INFINITY;
  try {
    eval(code);
    const start = performance.now();
    eval(benchmarkFnCall);
    const finish = performance.now();
    timeUsed = finish - start;
  }
  catch (err) {
    console.error(err);
  }
 */

 // self.postMessage(result);
};
<commit_msg>update benchmark msgs and # of runs sampled<commit_after>// wwBenchmark.js
// ==============

/* eslint no-eval: 0 */
/* eslint arrow-body-style: 0 */

'use strict';

const benchmark = require('benchmark');

function getResultMessage (data) {
  const re = /^.*x (\d.*) ops\/sec ±(.*)% \(.*$/;
  let statisticalConfidence = true;
  let resultMessage;

  if (data.testData[0].match(re) && data.testData[1].match(re)) {
    const stats = data.testData.map(datum => {
      return {
        mean: parseInt((datum.match(re)[1]).replace(',', ''), 10),
        pMarginOfError: Number(datum.match(re)[2]) / 100
      };
    }).map(stat => {
      return {
        mean: stat.mean,
        pMarginOfError: stat.pMarginOfError,
        aMarginOfError: stat.mean * stat.pMarginOfError
      };
    });

    const stockRange = [
      stats[0].mean - stats[0].aMarginOfError, stats[0].mean + stats[0].aMarginOfError
    ];

    const userRange = [
      stats[1].mean - stats[1].aMarginOfError, stats[1].mean + stats[1].aMarginOfError
    ];

    if (stockRange[0] <= userRange[1] && stockRange[1] >= userRange[0]) {
      statisticalConfidence = false;
    }

    // there are instances when benchmark.js returns a victor
    // despite unfounded confidence.
    if (statisticalConfidence) {
      if (data.fastest[0] === 'stock test') {
        // stock code faster than user code:
        // return 'stock';
        resultMessage = 'Your code is slower than par.';
      }
      // user code faster than stock code:
      // return 'user';
      resultMessage = 'Your code is faster than par! It\'s blazing fast!';
    }
    // tied between user and stock code:
    // return 'tie';
    resultMessage = 'Par! Your code is fast!';

    return resultMessage;
  }
}

function startBenchmark (baselineCode, testCode, fnc) {
  // TODO:
  // firm time cutoff regardless of whether test finishes.

  // default options:
  benchmark.options.maxTime = 0.05; // seems to be the minimum for test cycles - 5.
  // benchmark.options.maxTime = Number.NEGATIVE_INFINITY;
  benchmark.options.minSamples = 10;
  // benchmark.options.initCount = 10;

  self.baselineCode = baselineCode.replace(/use strict/g, '');
  self.testCode = testCode.replace(/use strict/g, '');
  self.fnc = fnc;

  const stockTest = {
    name: 'stock test',
    setup () { try { eval(self.baselineCode); } catch (err) { console.error(err); } },
    fn () { eval(fnc); }
  };
  const userTest = {
    name: 'user test',
    setup () { try { eval(testCode); } catch (err) { console.error(err); } },
    fn () { eval(fnc); }
  };

  const suite = benchmark.Suite();

  const results = {
    fastest: null,
    testData: []
  };

  return new Promise(resolve => {
    suite
    .add(stockTest)
    .add(userTest)
    .on('cycle', e => results.testData.push(String(e.target)))
    .on('complete', function () { results.fastest = this.filter('fastest').map('name');
      resolve({
        resultMessage: getResultMessage(results),
        stockPerf: results.testData[0],
        userPerf: results.testData[1]
      });
    })
    .run({ async: true });
  });
}

self.onmessage = e => {
  const stockCode = e.data[0][0];
  const userCode = e.data[0][1];
  const benchmarkFnCall = e.data[1];

  startBenchmark(stockCode, userCode, benchmarkFnCall)
    .then(result => {
      self.postMessage(result);
    });
  /*
  let timeUsed = Number.POSITIVE_INFINITY;
  try {
    eval(code);
    const start = performance.now();
    eval(benchmarkFnCall);
    const finish = performance.now();
    timeUsed = finish - start;
  }
  catch (err) {
    console.error(err);
  }
 */

 // self.postMessage(result);
};
<|endoftext|>