<commit_before>frappe.ui.form.ControlDate = class ControlDate extends frappe.ui.form.ControlData {
	static trigger_change_on_input_event = false
	make_input() {
		super.make_input();
		this.make_picker();
	}
	make_picker() {
		this.set_date_options();
		this.set_datepicker();
		this.set_t_for_today();
	}
	set_formatted_input(value) {
		super.set_formatted_input(value);
		if (this.timepicker_only) return;
		if (!this.datepicker) return;
		if (!value) {
			this.datepicker.clear();
			return;
		} else if (value === "Today") {
			value = this.get_now_date();
		}

		let should_refresh = this.last_value && this.last_value !== value;

		if (!should_refresh) {
			if(this.datepicker.selectedDates.length > 0) {
				// if date is selected but different from value, refresh
				const selected_date =
					moment(this.datepicker.selectedDates[0])
						.format(this.date_format);

				should_refresh = selected_date !== value;
			} else {
				// if datepicker has no selected date, refresh
				should_refresh = true;
			}
		}

		if(should_refresh) {
			this.datepicker.selectDate(frappe.datetime.str_to_obj(value));
		}
	}
	set_date_options() {
		// webformTODO:
		let sysdefaults = frappe.boot.sysdefaults;

		let lang = 'en';
		frappe.boot.user && (lang = frappe.boot.user.language);
		if(!$.fn.datepicker.language[lang]) {
			lang = 'en';
		}

		let date_format = sysdefaults && sysdefaults.date_format
			? sysdefaults.date_format : 'yyyy-mm-dd';

		this.today_text = __("Today");
		this.date_format = frappe.defaultDateFormat;
		this.datepicker_options = {
			language: lang,
			autoClose: true,
			todayButton: true,
			dateFormat: date_format,
			startDate: this.get_start_date(),
			keyboardNav: false,
			firstDay: frappe.datetime.get_first_day_of_the_week_index(),
			onSelect: () => {
				this.$input.trigger('change');
			},
			onShow: () => {
				this.datepicker.$datepicker
					.find('.datepicker--button:visible')
					.text(this.today_text);

				this.update_datepicker_position();
			},
			...(this.get_df_options())
		};
	}

	get_start_date() {
		return new Date(this.get_now_date());
	}

	set_datepicker() {
		this.$input.datepicker(this.datepicker_options);
		this.datepicker = this.$input.data('datepicker');

		// today button didn't work as expected,
		// so explicitly bind the event
		this.datepicker.$datepicker
			.find('[data-action="today"]')
			.click(() => {
				this.datepicker.selectDate(this.get_now_date());
			});
	}
	update_datepicker_position() {
		if(!this.frm) return;
		// show datepicker above or below the input
		// based on scroll position
		// We have to bodge around the timepicker getting its position
		// wrong by 42px when opening upwards.
		const $header = $('.page-head');
		const header_bottom = $header.position().top + $header.outerHeight();
		const picker_height = this.datepicker.$datepicker.outerHeight() + 12;
		const picker_top = this.$input.offset().top - $(window).scrollTop() - picker_height;

		var position = 'top left';
		// 12 is the default datepicker.opts[offset]
		if (picker_top <= header_bottom) {
			position = 'bottom left';
			if (this.timepicker_only) this.datepicker.opts['offset'] = 12;
		} else {
			// To account for 42px incorrect positioning
			if (this.timepicker_only) this.datepicker.opts['offset'] = -30;
		}

		this.datepicker.update('position', position);
	}
	get_now_date() {
		return frappe.datetime.convert_to_system_tz(frappe.datetime.now_date(true));
	}
	set_t_for_today() {
		var me = this;
		this.$input.on("keydown", function(e) {
			if(e.which===84) { // 84 === t
				if(me.df.fieldtype=='Date') {
					me.set_value(frappe.datetime.nowdate());
				} if(me.df.fieldtype=='Datetime') {
					me.set_value(frappe.datetime.now_datetime());
				} if(me.df.fieldtype=='Time') {
					me.set_value(frappe.datetime.now_time());
				}
				return false;
			}
		});
	}
	parse(value) {
		if(value) {
			return frappe.datetime.user_to_str(value);
		}
	}
	format_for_input(value) {
		if(value) {
			return frappe.datetime.str_to_user(value);
		}
		return "";
	}
	validate(value) {
		if(value && !frappe.datetime.validate(value)) {
			let sysdefaults = frappe.sys_defaults;
			let date_format = sysdefaults && sysdefaults.date_format
				? sysdefaults.date_format : 'yyyy-mm-dd';
			frappe.msgprint(__("Date {0} must be in format: {1}", [value, date_format]));
			return '';
		}
		return value;
	}
	get_df_options() {
		let options = {};
		let df_options = this.df.options || '';
		if (typeof df_options === 'string') {
			try {
				options = JSON.parse(df_options);
			} catch (error) {
				console.warn(`Invalid JSON in options of "${this.df.fieldname}"`);
			}
		}
		else if (typeof df_options === 'object') {
			options = df_options;
		}
		return options;
	}
};
<commit_msg>fix: Pass date object instead of string for selectDate to work<commit_after>frappe.ui.form.ControlDate = class ControlDate extends frappe.ui.form.ControlData {
	static trigger_change_on_input_event = false
	make_input() {
		super.make_input();
		this.make_picker();
	}
	make_picker() {
		this.set_date_options();
		this.set_datepicker();
		this.set_t_for_today();
	}
	set_formatted_input(value) {
		if (value === "Today") {
			value = this.get_now_date();
		}

		super.set_formatted_input(value);
		if (this.timepicker_only) return;
		if (!this.datepicker) return;
		if (!value) {
			this.datepicker.clear();
			return;
		}

		let should_refresh = this.last_value && this.last_value !== value;

		if (!should_refresh) {
			if(this.datepicker.selectedDates.length > 0) {
				// if date is selected but different from value, refresh
				const selected_date =
					moment(this.datepicker.selectedDates[0])
						.format(this.date_format);

				should_refresh = selected_date !== value;
			} else {
				// if datepicker has no selected date, refresh
				should_refresh = true;
			}
		}

		if(should_refresh) {
			this.datepicker.selectDate(frappe.datetime.str_to_obj(value));
		}
	}
	set_date_options() {
		// webformTODO:
		let sysdefaults = frappe.boot.sysdefaults;

		let lang = 'en';
		frappe.boot.user && (lang = frappe.boot.user.language);
		if(!$.fn.datepicker.language[lang]) {
			lang = 'en';
		}

		let date_format = sysdefaults && sysdefaults.date_format
			? sysdefaults.date_format : 'yyyy-mm-dd';

		this.today_text = __("Today");
		this.date_format = frappe.defaultDateFormat;
		this.datepicker_options = {
			language: lang,
			autoClose: true,
			todayButton: true,
			dateFormat: date_format,
			startDate: this.get_start_date(),
			keyboardNav: false,
			firstDay: frappe.datetime.get_first_day_of_the_week_index(),
			onSelect: () => {
				this.$input.trigger('change');
			},
			onShow: () => {
				this.datepicker.$datepicker
					.find('.datepicker--button:visible')
					.text(this.today_text);

				this.update_datepicker_position();
			},
			...(this.get_df_options())
		};
	}

	get_start_date() {
		return this.get_now_date();
	}

	set_datepicker() {
		this.$input.datepicker(this.datepicker_options);
		this.datepicker = this.$input.data('datepicker');

		// today button didn't work as expected,
		// so explicitly bind the event
		this.datepicker.$datepicker
			.find('[data-action="today"]')
			.click(() => {
				this.datepicker.selectDate(this.get_now_date());
			});
	}
	update_datepicker_position() {
		if(!this.frm) return;
		// show datepicker above or below the input
		// based on scroll position
		// We have to bodge around the timepicker getting its position
		// wrong by 42px when opening upwards.
		const $header = $('.page-head');
		const header_bottom = $header.position().top + $header.outerHeight();
		const picker_height = this.datepicker.$datepicker.outerHeight() + 12;
		const picker_top = this.$input.offset().top - $(window).scrollTop() - picker_height;

		var position = 'top left';
		// 12 is the default datepicker.opts[offset]
		if (picker_top <= header_bottom) {
			position = 'bottom left';
			if (this.timepicker_only) this.datepicker.opts['offset'] = 12;
		} else {
			// To account for 42px incorrect positioning
			if (this.timepicker_only) this.datepicker.opts['offset'] = -30;
		}

		this.datepicker.update('position', position);
	}
	get_now_date() {
		return frappe.datetime.convert_to_system_tz(frappe.datetime.now_date(true), false).toDate();
	}
	set_t_for_today() {
		var me = this;
		this.$input.on("keydown", function(e) {
			if(e.which===84) { // 84 === t
				if(me.df.fieldtype=='Date') {
					me.set_value(frappe.datetime.nowdate());
				} if(me.df.fieldtype=='Datetime') {
					me.set_value(frappe.datetime.now_datetime());
				} if(me.df.fieldtype=='Time') {
					me.set_value(frappe.datetime.now_time());
				}
				return false;
			}
		});
	}
	parse(value) {
		if(value) {
			return frappe.datetime.user_to_str(value);
		}
	}
	format_for_input(value) {
		if(value) {
			return frappe.datetime.str_to_user(value);
		}
		return "";
	}
	validate(value) {
		if(value && !frappe.datetime.validate(value)) {
			let sysdefaults = frappe.sys_defaults;
			let date_format = sysdefaults && sysdefaults.date_format
				? sysdefaults.date_format : 'yyyy-mm-dd';
			frappe.msgprint(__("Date {0} must be in format: {1}", [value, date_format]));
			return '';
		}
		return value;
	}
	get_df_options() {
		let options = {};
		let df_options = this.df.options || '';
		if (typeof df_options === 'string') {
			try {
				options = JSON.parse(df_options);
			} catch (error) {
				console.warn(`Invalid JSON in options of "${this.df.fieldname}"`);
			}
		}
		else if (typeof df_options === 'object') {
			options = df_options;
		}
		return options;
	}
};
<|endoftext|>


<commit_before>/*
    TinyMCE filebrowser implementation.
*/

(function($, tinyMCE) {

    // Get the important values from TinyMCE.
    var win = tinyMCEPopup.getWindowArg("window");
    var inputId = tinyMCEPopup.getWindowArg("input");
    // Get the input from the opening window.
    var input = $("#" + inputId, win.document);

    // Define the filebrowser plugin.
    $.filebrowser = {}

    // Closes the filebrowser and sends the information back to the TinyMCE
    // editor.
    $.filebrowser.complete = function(permalink, title) {
        input.attr("value", permalink);
        // Set the link dialogue values.
        $("#linktitle", win.document).attr("value", title);
        // Set the image dialogue values.
        if (typeof(win.ImageDialog) != "undefined") {
            if (win.ImageDialog.getImageData) {
                win.ImageDialog.getImageData();
            }
            if (win.ImageDialog.showPreviewImage) {
                win.ImageDialog.showPreviewImage(permalink);
            }
            $("#alt", win.document).attr("value", title);
            $("#title", win.document).attr("value", title);
        }
        // Close the dialogue.
        tinyMCEPopup.close();
        return false;
    }

    // Initializes the popup file browser.
    $.filebrowser.initBrowser = function() {
        // Make the changelist links clickable.
        $("div#changelist tr.row1 a, div#changelist tr.row2 a").click(function() {
            var img = $("img", this);
            var title = img.attr("title");
            var permalink = img.attr("cms:permalink");
            $.filebrowser.complete(permalink, title)
        });
        // Make the add link clickable.
        $("a.addlink").click(function() {
            tinyMCE.activeEditor.windowManager.open({
                file: $(this).attr("href") + "&_tinymce=1",
                title: "Add file",
                width: 760,
                height: 400,
                resizable: "yes",
                inline: "yes",
                close_previous: "no",
                popup_css: false,
            }, {
                window: win,
                input: inputId
            });
            tinyMCEPopup.close();
            return false;
        });
    }

}(jQuery, tinyMCE));<commit_msg>Removed 'opener is null' error from filebrowser.<commit_after>/*
    TinyMCE filebrowser implementation.
*/

(function($, tinyMCE) {

    // Get the important values from TinyMCE.
    var win = tinyMCEPopup.getWindowArg("window");
    var inputId = tinyMCEPopup.getWindowArg("input");
    // Get the input from the opening window.
    var input = $("#" + inputId, win.document);

    // Define the filebrowser plugin.
    $.filebrowser = {}

    // Closes the filebrowser and sends the information back to the TinyMCE
    // editor.
    $.filebrowser.complete = function(permalink, title) {
        input.attr("value", permalink);
        // Set the link dialogue values.
        $("#linktitle", win.document).attr("value", title);
        // Set the image dialogue values.
        if (typeof(win.ImageDialog) != "undefined") {
            if (win.ImageDialog.getImageData) {
                win.ImageDialog.getImageData();
            }
            if (win.ImageDialog.showPreviewImage) {
                win.ImageDialog.showPreviewImage(permalink);
            }
            $("#alt", win.document).attr("value", title);
            $("#title", win.document).attr("value", title);
        }
        // Close the dialogue.
        tinyMCEPopup.close();
        return false;
    }

    // Initializes the popup file browser.
    $.filebrowser.initBrowser = function() {
        // Make the changelist links clickable and remove the original inline click listener.
        $("div#changelist tr.row1 a, div#changelist tr.row2 a").attr("onclick", null).click(function() {
            var img = $("img", this);
            var title = img.attr("title");
            var permalink = img.attr("cms:permalink");
            $.filebrowser.complete(permalink, title)
        });
        // Make the add link clickable.
        $("a.addlink").click(function() {
            tinyMCE.activeEditor.windowManager.open({
                file: $(this).attr("href") + "&_tinymce=1",
                title: "Add file",
                width: 760,
                height: 400,
                resizable: "yes",
                inline: "yes",
                close_previous: "no",
                popup_css: false,
            }, {
                window: win,
                input: inputId
            });
            tinyMCEPopup.close();
            return false;
        });
    }

}(jQuery, tinyMCE));<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {blue100} from 'material-ui/styles/colors';
import {DayProgram} from './ProgramComponents'

const fridayPlan = [
  {hour: '', 'groups': []},
  {hour: '20h', 'groups': [false,
  			   {name: 'Baila Tocamos (BE) bal', duration: 4, kind: 'bal'},
  			   false, false]},
  {hour: '20h30', 'groups': [false, true, false, false]},
  {hour: '21h', 'groups': [false, true, false, false]},
  {hour: '21h30', 'groups': [false, true, false, false]},
  {hour: '22h', 'groups': [{name: 'Duo Montanaro-Cavez (BE-FR) concert', duration: 3, kind: 'concert'},
                           false,
                           {name: 'Wouter Vandenabeele et Jeroen Knapen (BE) bal', duration: 4, kind: 'bal'},
                           false]},
  {hour: '22h30', 'groups': [true, false, true, false]},
  {hour: '23h', 'groups': [true, false, true, false]},
  {hour: '23h30', 'groups': [false, false, true, false]},
  {hour: '00h', 'groups': [false,
                           {name: 'Les Zéoles (FR) bal', duration: 4, kind: 'bal'},
                           false, false]},
  {hour: '00h30', 'groups': [false, true, false, false]},
  {hour: '01h', 'groups': [false, true, false, false]},
  {hour: '01h30', 'groups': [false, true, false, false]},
  {hour: '02h00', 'groups': [false, false, false, false]},
];

export default class FridayProgram extends React.Component {
  render() {
		return (
      <DayProgram plan={fridayPlan} lang={this.props.lang} />
    );
  }
}
<commit_msg>Update FridayProgram.js<commit_after>import React, { Component } from 'react';
import {blue100} from 'material-ui/styles/colors';
import {DayProgram} from './ProgramComponents'

const fridayPlan = [
  {hour: '', 'groups': []},
  {hour: '20h', 'groups': [false,
  			   {name: 'Baila Tocamos (BE) bal', duration: 4, kind: 'bal'},
  			   false, false]},
  {hour: '20h30', 'groups': [false, true, false, false]},
  {hour: '21h', 'groups': [false, true, false, false]},
  {hour: '21h30', 'groups': [false, true, false, false]},
  {hour: '22h', 'groups': [{name: 'Duo Montanaro-Cavez (BE-FR) concert', duration: 3, kind: 'concert'},
                           false,
                           {name: 'Wouter Vandenabeele et Jeroen Knapen (BE) bal', duration: 4, kind: 'bal'},
                           false]},
  {hour: '22h30', 'groups': [true, false, true, false]},
  {hour: '23h', 'groups': [true, false, true, false]},
  {hour: '23h30', 'groups': [false, false, true, false]},
  {hour: '00h', 'groups': [false,
                           {name: 'Les Zéoles (FR) bal', duration: 4, kind: 'bal'},
                           false, false]},
  {hour: '00h30', 'groups': [false, true, false, false]},
  {hour: '01h', 'groups': [false, true, false, false]},
  {hour: '01h30', 'groups': [false, true, false, false]},
  {hour: '02h00', 'groups': [false, false, false, false]},
];

export default class FridayProgram extends React.Component {
  render() {
    return (
      <DayProgram plan={fridayPlan} lang={this.props.lang} />
    );
  }
}
<|endoftext|>


<commit_before>(function(swiftSet) {
'use strict'

// Imports
var
  Histogram = swiftSet.Histogram
;

function key() {
  return this.id;
}

describe('Histogram', function() {
  var
    o1 = { id: 'o1', hkey: key },
    o2 = { id: 'o2', hkey: key },
    o3 = { id: 'o3', hkey: key },
    o4 = { id: 'o4', hkey: key },
    o5 = { id: 'o5', hkey: key }
  ;

  beforeEach(function() {

  });

  describe('initialization', function() {

    it('creates an accurate histogram of numbers', function() {
      var num = [1, 1, 2, 2, 3, 3];
      var hist = new Histogram(num);

      expect(hist.has(0)).toBe(false);
      expect(hist.has(1)).toBe(true);
      expect(hist.has(2)).toBe(true);
      expect(hist.has(3)).toBe(true);

      expect(hist.freq(0)).toEqual(0);
      expect(hist.freq(1)).toEqual(2);
      expect(hist.freq(2)).toEqual(2);
      expect(hist.freq(3)).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(2);
    });

    it('creates an accurate histogram of characters', function() {
      var chr = ['a', 'a', 'b', 'b', 'c', 'c'];
      var hist = new Histogram(chr);

      expect(hist.has('z')).toBe(false);
      expect(hist.has('a')).toBe(true);
      expect(hist.has('b')).toBe(true);
      expect(hist.has('c')).toBe(true);

      expect(hist.freq('z')).toEqual(0);
      expect(hist.freq('a')).toEqual(2);
      expect(hist.freq('b')).toEqual(2);
      expect(hist.freq('c')).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(2);
    });

    it('creates an accurate histogram of objects', function() {
      var obj = [o1, o1, o2, o2, o3, o3];
      var hist = new Histogram(obj);

      expect(hist.has(o4)).toBe(false);
      expect(hist.has(o1)).toBe(true);
      expect(hist.has(o2)).toBe(true);
      expect(hist.has(o3)).toBe(true);

      expect(hist.freq(o5)).toEqual(0);
      expect(hist.freq(o1)).toEqual(2);
      expect(hist.freq(o2)).toEqual(2);
      expect(hist.freq(o3)).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(2);
    });

  });

  describe('mutability', function() {

    it('accurately adds and removes one or more numbers', function() {
      var num = [1, 2, 2, 3, 3, 3];
      var hist = new Histogram(num);

      hist.add(3).add(4, 5)
        .remove(1, 2);

      expect(hist.has(1)).toBe(false);
      expect(hist.has(2)).toBe(false);
      expect(hist.has(3)).toBe(true);
      expect(hist.has(4)).toBe(true);
      expect(hist.has(5)).toBe(true);

      expect(hist.freq(1)).toEqual(0)
      expect(hist.freq(2)).toEqual(0);
      expect(hist.freq(3)).toEqual(4);
      expect(hist.freq(4)).toEqual(1);
      expect(hist.freq(5)).toEqual(1);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(4);

      hist = new Histogram(num)
        .addItems([3, 4, 4, 5, 5])
        .removeItems([1, 2]);

      expect(hist.has(1)).toBe(false);
      expect(hist.has(2)).toBe(false);
      expect(hist.has(3)).toBe(true);
      expect(hist.has(4)).toBe(true);
      expect(hist.has(5)).toBe(true);

      expect(hist.freq(1)).toEqual(0)
      expect(hist.freq(2)).toEqual(0);
      expect(hist.freq(3)).toEqual(4);
      expect(hist.freq(4)).toEqual(2);
      expect(hist.freq(5)).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(8);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(4);
    });

    it('accurately adds and removes one or more characters', function() {
      var chr = ['a', 'b', 'b', 'c', 'c', 'c'];
      var hist = new Histogram(chr);

      hist.add('c').add('d', 'e')
        .remove('a', 'b');

      expect(hist.has('a')).toBe(false);
      expect(hist.has('b')).toBe(false);
      expect(hist.has('c')).toBe(true);
      expect(hist.has('d')).toBe(true);
      expect(hist.has('e')).toBe(true);

      expect(hist.freq('a')).toEqual(0)
      expect(hist.freq('b')).toEqual(0);
      expect(hist.freq('c')).toEqual(4);
      expect(hist.freq('d')).toEqual(1);
      expect(hist.freq('e')).toEqual(1);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(4);

      hist = new Histogram(chr)
        .addItems(['c', 'd', 'd', 'e', 'e'])
        .removeItems(['a', 'b']);

      expect(hist.has('a')).toBe(false);
      expect(hist.has('b')).toBe(false);
      expect(hist.has('c')).toBe(true);
      expect(hist.has('d')).toBe(true);
      expect(hist.has('e')).toBe(true);

      expect(hist.freq('a')).toEqual(0)
      expect(hist.freq('b')).toEqual(0);
      expect(hist.freq('c')).toEqual(4);
      expect(hist.freq('d')).toEqual(2);
      expect(hist.freq('e')).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(8);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(4);
    });

    it('accurately adds and removes one or more objects', function() {
      var obj = [o1, o2, o2, o3, o3, o3];
      var hist = new Histogram(obj);

      hist.add(o3).add(o4, o5)
        .remove(o1, o2);

      expect(hist.has(o1)).toBe(false);
      expect(hist.has(o2)).toBe(false);
      expect(hist.has(o3)).toBe(true);
      expect(hist.has(o4)).toBe(true);
      expect(hist.has(o5)).toBe(true);

      expect(hist.freq(o1)).toEqual(0)
      expect(hist.freq(o2)).toEqual(0);
      expect(hist.freq(o3)).toEqual(4);
      expect(hist.freq(o4)).toEqual(1);
      expect(hist.freq(o5)).toEqual(1);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(4);

      hist = new Histogram(obj)
        .addItems([o3, o4, o4, o5, o5])
        .removeItems([o1, o2]);

      expect(hist.has(o1)).toBe(false);
      expect(hist.has(o2)).toBe(false);
      expect(hist.has(o3)).toBe(true);
      expect(hist.has(o4)).toBe(true);
      expect(hist.has(o5)).toBe(true);

      expect(hist.freq(o1)).toEqual(0)
      expect(hist.freq(o2)).toEqual(0);
      expect(hist.freq(o3)).toEqual(4);
      expect(hist.freq(o4)).toEqual(2);
      expect(hist.freq(o5)).toEqual(2);

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(8);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(4);
    });

    it('can properly normalize a histogram', function() {
      var hist = new Histogram([1, 2, 2, 3, 3, 3]);

      hist.normalize();
      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(3);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(1);

      hist.normalize(2);
      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(2);
      expect(hist.max()).toEqual(2);

    });

    it('can correctly merge one histogram with another', function() {
      var hist1 = new Histogram([1, 2, 2, 3, 3, 3]),
        hist2 = new Histogram([1, 2, 3, 4]);

      hist1.merge(hist2);
      expect(hist1.size()).toEqual(4);
      expect(hist1.total()).toEqual(10);
      expect(hist1.min()).toEqual(1);
      expect(hist1.max()).toEqual(4);
    });

    it('can clear a histogram and initialize it with new values', function() {
      var
      o1 = { id: 1 },
      o2 = { id: 2 },
      o3 = { id: 3 },
      o4 = { id: 4 },
      o5 = { id: 5 },
      a = [o1, o1, o2, o3, o3],
      b = [o2, o2, o3, o4, o5],
      h1 = new Histogram(a, 'id'), h2;

      expect(h1.size()).toEqual(3);
      expect(h1.total()).toEqual(5);
      expect(h1.min()).toEqual(1);
      expect(h1.max()).toEqual(2);
      expect(h1.freq(o1)).toEqual(2);
      expect(h1.freq(o2)).toEqual(1);
      expect(h1.freq(o3)).toEqual(2);

      h2 = h1.copy().clear(b);

      expect(h2.size()).toEqual(4);
      expect(h2.total()).toEqual(5);
      expect(h2.min()).toEqual(1);
      expect(h2.max()).toEqual(2);
      expect(h2.freq(o1)).toEqual(0);
      expect(h2.freq(o2)).toEqual(2);
      expect(h2.freq(o3)).toEqual(1);
      expect(h2.freq(o4)).toEqual(1);
      expect(h2.freq(o5)).toEqual(1);

      h2.clear();

      expect(h2.size()).toEqual(0);
      expect(h2.total()).toEqual(0);
      expect(h2.min()).toEqual(Infinity);
      expect(h2.max()).toEqual(0);
      expect(h2.freq(o1)).toEqual(0);
      expect(h2.freq(o2)).toEqual(0);
      expect(h2.freq(o3)).toEqual(0);
      expect(h2.freq(o4)).toEqual(0);
      expect(h2.freq(o5)).toEqual(0);

    });
  });

  describe('object key', function() {

    describe('uses object key values and functions', function() {

      it('uses "hkey" as an object value property', function() {
        var
        o1 = { hkey: 'o1' },
        o2 = { hkey: 'o2' },
        o3 = { hkey: 'o3' },
        o4 = { hkey: 'o4' },
        o5 = { hkey: 'o5' },
        hist = new Histogram([o1, o2, o3, o4, o5]);

        expect(hist.size()).toEqual(5);
        expect(hist.total()).toEqual(5);
        expect(hist.min()).toEqual(1);
        expect(hist.max()).toEqual(1);
      });

      it('uses "hkey" as an object function property', function() {
        var
        o1 = { id: 'o1', hkey: key },
        o2 = { id: 'o2', hkey: key },
        o3 = { id: 'o3', hkey: key },
        o4 = { id: 'o4', hkey: key },
        o5 = { id: 'o5', hkey: key },
        hist = new Histogram([o1, o2, o3, o4, o5]);

        expect(hist.size()).toEqual(5);
        expect(hist.total()).toEqual(5);
        expect(hist.min()).toEqual(1);
        expect(hist.max()).toEqual(1);
      });
    });

    describe('uses explicit key values and functions', function() {

      it('uses custom key as an object value property', function() {
        var
        o1 = { myKey: 'o1' },
        o2 = { myKey: 'o2' },
        o3 = { myKey: 'o3' },
        o4 = { myKey: 'o4' },
        o5 = { myKey: 'o5' },
        hist = new Histogram([o1, o2, o3, o4, o5], 'myKey');

        expect(hist.size()).toEqual(5);
        expect(hist.total()).toEqual(5);
        expect(hist.min()).toEqual(1);
        expect(hist.max()).toEqual(1);
      });

      it('uses a custom function as a key retriever', function() {
        var
        myKey = function() { return this.id; },
        o1 = { id: 'o1' },
        o2 = { id: 'o2' },
        o3 = { id: 'o3' },
        o4 = { id: 'o4' },
        o5 = { id: 'o5' },
        hist = new Histogram([o1, o2, o3, o4, o5], myKey);

        expect(hist.size()).toEqual(5);
        expect(hist.total()).toEqual(5);
        expect(hist.min()).toEqual(1);
        expect(hist.max()).toEqual(1);
      });
    });

    it('uses object toString method to implicity generate a key', function() {
      var
      o1 = { id: 'v', toString: function() { return this.id; } },
      o2 = { id: 'w', toString: function() { return this.id; } },
      o3 = { id: 'x', toString: function() { return this.id; } },
      o4 = { id: 'y', toString: function() { return this.id; } },
      o5 = { id: 'z', toString: function() { return this.id; } },
      hist = new Histogram([o1, o2, o3, o4, o5]);

      expect(hist.size()).toEqual(5);
      expect(hist.total()).toEqual(5);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(1);
    });
  });

  describe('global key', function() {
    var
    o1 = { id: 1 },
    o2 = { id: 2 },
    o3 = { id: 3 },
    o4 = { id: 4 },
    o5 = { id: 5 };

    it('uses an object value property', function() {
      var hist = new Histogram([o1, o2, o2, o3, o3, o3], 'id');

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(3);

      expect(hist.has(o1)).toEqual(true);
      expect(hist.has(o2)).toEqual(true);
      expect(hist.has(o3)).toEqual(true);
      expect(hist.has(o4)).toEqual(false);

      expect(hist.freq(o1)).toEqual(1);
      expect(hist.freq(o2)).toEqual(2);
      expect(hist.freq(o3)).toEqual(3);
    });

    it('uses an object function property', function() {
      var hist = new Histogram([o1, o2, o2, o3, o3, o3], function() {
        return this.id;
      });

      expect(hist.size()).toEqual(3);
      expect(hist.total()).toEqual(6);
      expect(hist.min()).toEqual(1);
      expect(hist.max()).toEqual(3);

      expect(hist.has(o1)).toEqual(true);
      expect(hist.has(o2)).toEqual(true);
      expect(hist.has(o3)).toEqual(true);
      expect(hist.has(o4)).toEqual(false);

      expect(hist.freq(o1)).toEqual(1);
      expect(hist.freq(o2)).toEqual(2);
      expect(hist.freq(o3)).toEqual(3);
    });
  });

  describe('iteration', function() {

    it('properly iterates over the histogram', function() {
      var hist = new Histogram([7, 8, 8, 9, 9, 9]),
        calls = { method: function() {}};
      spyOn(calls, 'method');

      hist.each(function(value, count, key) {
        calls.method(value);
        calls.method(count);
        calls.method(key);
      });
      // Values
      expect(calls.method).toHaveBeenCalledWith(7);
      expect(calls.method).toHaveBeenCalledWith(8);
      expect(calls.method).toHaveBeenCalledWith(9);
      // Counts
      expect(calls.method).toHaveBeenCalledWith(1);
      expect(calls.method).toHaveBeenCalledWith(2);
      expect(calls.method).toHaveBeenCalledWith(3);
      // Keys
      expect(calls.method).toHaveBeenCalledWith('7');
      expect(calls.method).toHaveBeenCalledWith('8');
      expect(calls.method).toHaveBeenCalledWith('9');
    });

    it('produces a correct list of values', function() {
      var hist = new Histogram([7, 8, 8, 9, 9, 9]),
        values = hist.items();

      expect(values).toContain(7);
      expect(values).toContain(8);
      expect(values).toContain(9);
      expect(values.length).toEqual(3);
    });

    it('produces a correct list of counts', function() {
      var hist = new Histogram([7, 8, 8, 9, 9, 9]),
        counts = hist.frequencies();

      expect(counts).toContain(1);
      expect(counts).toContain(2);
      expect(counts).toContain(3);
      expect(counts.length).toEqual(3);
    });

    it('produces a correct list of keys', function() {
      var hist = new Histogram([7, 8, 8, 9, 9, 9]),
        keys = hist.keys();

      expect(keys).toContain('7');
      expect(keys).toContain('8');
      expect(keys).toContain('9');
      expect(keys.length).toEqual(3);
    });
  });

  describe('key', function() {

    it('generates a unique histogram key for numbers', function() {
      var hist1 = new Histogram([7, 8, 8, 9, 9, 9]),
        hist2 = new Histogram([7, 8, 8, 9, 9, 9]),
        hist3 = new Histogram([7, 8, 9]);

      expect(hist1.keyify()).toEqual('{7:1,8:2,9:3}');
      expect(hist1.keyify()).toEqual(hist2.keyify());
      expect(hist1.keyify()).not.toEqual(hist3.keyify());
    });

    it('generates a unique histogram key for characters', function() {
      var hist1 = new Histogram(['7', '8', '8', '9', '9', '9']),
        hist2 = new Histogram(['7', '8', '8', '9', '9', '9']),
        hist3 = new Histogram(['7', '8', '9']);

      expect(hist1.keyify()).toEqual('{7:1,8:2,9:3}');
      expect(hist1.keyify()).toEqual(hist2.keyify());
      expect(hist1.keyify()).not.toEqual(hist3.keyify());
    });

    it('generates a unique histogram key for objects', function() {
      var hist1 = new Histogram([o1, o2, o2, o3, o3, o3]),
        hist2 = new Histogram([o1, o2, o2, o3, o3, o3]),
        hist3 = new Histogram([o1, o2, o3]);

      expect(hist1.keyify()).toEqual('{o1:1,o2:2,o3:3}');
      expect(hist1.keyify()).toEqual(hist2.keyify());
      expect(hist1.keyify()).not.toEqual(hist3.keyify());
    });

    it('can treat strings and numbers as different values', function() {
      var wrap = Histogram.wrapObj(),
      hist1 = new Histogram()
        .add(wrap(1),wrap(2),wrap(2),wrap(3),wrap(3),wrap(3)),
      hist2 = new Histogram()
        .add(wrap('1'),wrap('2'),wrap('2'),wrap('3'),wrap('3'),wrap('3'));

      expect(hist1.has(wrap(1))).toEqual(true);
      expect(hist1.has(wrap(2))).toEqual(true);
      expect(hist1.has(wrap(3))).toEqual(true);
      expect(hist1.has(wrap('3'))).toEqual(false);

      expect(hist2.has(wrap('1'))).toEqual(true);
      expect(hist2.has(wrap('2'))).toEqual(true);
      expect(hist2.has(wrap('3'))).toEqual(true);
      expect(hist2.has(wrap(3))).toEqual(false);

      expect(hist1.keyify()).not.toEqual(hist2.keyify());
      hist1.addItems(hist2.items());
      expect(hist1.size()).toEqual(6);
    });

    it('correctly determines histogram equivalence', function() {
      var hist1 = new Histogram([7, 8, 8, 9, 9, 9]),
        hist2 = new Histogram([7, 8, 8, 9, 9, 9]),
        hist3 = new Histogram([7, 8, 9]);
      expect(hist1.equals(hist2)).toEqual(true);
      expect(hist1.equals(hist3)).toEqual(false);
    });

    it('can use histograms as values in a histogram', function() {
      var h1 = new Histogram([1, 2, 3, 3, 3, 3]),
        h2 = new Histogram([4, 5, 5, 6, 6, 6]),
        h3 = new Histogram([7, 8, 8, 9, 9, 9]),
        hist1 = new Histogram([h1, h2, h2, h3, h3, h3]),
        hist2 = new Histogram([h1, h2, h2, h3, h3, h3]),
        hist3 = new Histogram([h1, h2, h3]);

      expect(hist1.size()).toEqual(3);
      expect(hist1.total()).toEqual(6);
      expect(hist1.min()).toEqual(1);
      expect(hist1.max()).toEqual(3);
      expect(hist1.freq(h1)).toEqual(1);
      expect(hist1.freq(h2)).toEqual(2);
      expect(hist1.freq(h3)).toEqual(3);
      expect(hist1.equals(hist2)).toEqual(true);
      expect(hist1.equals(hist3)).toEqual(false);
    });
  });

  describe('mixed values', function() {
      var wrap = Histogram.wrapObj(), isWrapped = Histogram.isWrapped,
      hist1 = new Histogram([wrap(1), wrap(1), '1', wrap(2), '2', o1, o2]),
      hist2 = hist1.copy();

    it('can build a mixed set of numbers, strings, and objects', function() {
      var values;

      expect(hist1.size()).toEqual(6);
      expect(hist1.total()).toEqual(7);
      expect(hist1.min()).toEqual(1);
      expect(hist1.max()).toEqual(2);

      expect(hist1.has(wrap(1))).toEqual(true);
      expect(hist1.has(wrap('1'))).toEqual(false);
      expect(hist1.has('1')).toEqual(true);
      expect(hist1.has(wrap(2))).toEqual(true);
      expect(hist1.has('2')).toEqual(true);
      expect(hist1.has(o1)).toEqual(true);
      expect(hist1.has(wrap(o1))).toEqual(false);
      expect(hist1.has(o2)).toEqual(true);
      expect(hist1.equals(hist2)).toEqual(true);

      expect(hist2.size()).toEqual(6);
      expect(hist2.total()).toEqual(7);
      expect(hist2.min()).toEqual(1);
      expect(hist2.max()).toEqual(2);

      expect(hist2.has(wrap(1))).toEqual(true);
      expect(hist2.has(wrap('1'))).toEqual(false);
      expect(hist2.has('1')).toEqual(true);
      expect(hist2.has(wrap(2))).toEqual(true);
      expect(hist2.has('2')).toEqual(true);
      expect(hist2.has(o1)).toEqual(true);
      expect(hist2.has(wrap(o1))).toEqual(false);
      expect(hist2.has(o2)).toEqual(true);
      expect(hist2.equals(hist1)).toEqual(true);

      values = hist1.items().map(function(item) {
        return isWrapped(item) ? item.item : item;
      });

      expect(values).toContain(1);
      expect(values).toContain('1');
      expect(values).toContain(2);
      expect(values).toContain('2');
      expect(values).toContain(o1);
      expect(values).toContain(o2);

      values = hist2.items().map(function(item) {
        return isWrapped(item) ? item.item : item;
      });

      expect(values).toContain(1);
      expect(values).toContain('1');
      expect(values).toContain(2);
      expect(values).toContain('2');
      expect(values).toContain(o1);
      expect(values).toContain(o2);
    });

    it('can properly unwrap values that are wrapped', function() {
      var values = hist1.unwrap();

      expect(values).toContain(1);
      expect(values).toContain('1');
      expect(values).toContain(2);
      expect(values).toContain('2');
      expect(values).toContain(o1);
      expect(values).toContain(o2);

    });
  });

  describe('copy', function() {
    it('can reliably copy a histogram', function() {
      var
      o1 = { id: 1 },
      o2 = { id: 2 },
      o3 = { id: 3 },
      o4 = { id: 4 },
      o5 = { id: 5 },
      hist1 = new Histogram([o1, o2, o2, o3, o3, o3], 'id'),
      hist2 = hist1.copy();

      hist2.add(o4, o5);
      expect(hist2.size()).toEqual(5);
      expect(hist2.total()).toEqual(8);
      expect(hist2.min()).toEqual(1);
      expect(hist2.max()).toEqual(3);

      expect(hist2.has(o1)).toEqual(true);
      expect(hist2.has(o2)).toEqual(true);
      expect(hist2.has(o3)).toEqual(true);
      expect(hist2.has(o4)).toEqual(true);
      expect(hist2.has(o5)).toEqual(true);

      expect(hist2.freq(o1)).toEqual(1);
      expect(hist2.freq(o2)).toEqual(2);
      expect(hist2.freq(o3)).toEqual(3);
      expect(hist2.freq(o4)).toEqual(1);
      expect(hist2.freq(o5)).toEqual(1);

      hist2 = hist1.copy([o3, o3, o4, o4, o5]);

      expect(hist2.size()).toEqual(3);
      expect(hist2.total()).toEqual(5);
      expect(hist2.min()).toEqual(1);
      expect(hist2.max()).toEqual(2);

      expect(hist2.has(o1)).toEqual(false);
      expect(hist2.has(o2)).toEqual(false);
      expect(hist2.has(o3)).toEqual(true);
      expect(hist2.has(o4)).toEqual(true);
      expect(hist2.has(o5)).toEqual(true);

      expect(hist2.freq(o1)).toEqual(0);
      expect(hist2.freq(o2)).toEqual(0);
      expect(hist2.freq(o3)).toEqual(2);
      expect(hist2.freq(o4)).toEqual(2);
      expect(hist2.freq(o5)).toEqual(1);
    });
  });

  describe('clear', function() {
  });
});

})(window.swiftSet, undefined);

<commit_msg>Remove hist spec<commit_after><|endoftext|>


<commit_before>/** @jsx React.DOM */
'use strict';

jest.autoMockOff();

// Fixes https://github.com/facebook/jest/issues/78
jest.dontMock('react');
jest.dontMock('underscore');

describe('Experiment Page', function() {
    var React, TestUtils, Experiment, context, _;

    beforeEach(function() {
        React = require('react');
        TestUtils = require('react/lib/ReactTestUtils');
        _ = require('underscore');

        Experiment = require('../experiment.js').Experiment;
        context = require('../testdata/experiment.js');

    });

    describe('Minimal Experiment', function() {
        var experiment, summary, defTerms, defDescs;

        beforeEach(function() {
            experiment = <Experiment context={context} />;
            TestUtils.renderIntoDocument(experiment);

            summary = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'data-display');
            defTerms = summary[0].getDOMNode().getElementsByTagName('dt');
            defDescs = summary[0].getDOMNode().getElementsByTagName('dd');
        });

        it('Has correct summary panel and key-value elements counts within it', function() {
            expect(summary.length).toEqual(1);
            expect(defTerms.length).toEqual(7);
            expect(defDescs.length).toEqual(7);
        });

        it('has proper links in dbxrefs key-value', function() {
            var dbxrefs = defDescs[6].getElementsByTagName('a');
            expect(dbxrefs.length).toEqual(2);
            expect(dbxrefs[0].getAttribute('href')).toEqual('http://genome.ucsc.edu/cgi-bin/hgTracks?tsCurTab=advancedTab&tsGroup=Any&tsType=Any&hgt_mdbVar1=dccAccession&hgt_tSearch=search&hgt_tsDelRow=&hgt_tsAddRow=&hgt_tsPage=&tsSimple=&tsName=&tsDescr=&db=hg19&hgt_mdbVal1=wgEncodeEH003317');
            expect(dbxrefs[1].getAttribute('href')).toEqual('http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM1010811');
        });

        it('has two experiment status elements in header', function() {
            var statusList = TestUtils.findRenderedDOMComponentWithClass(experiment, 'status-list').getDOMNode();
            expect(statusList.hasChildNodes()).toBeTruthy();
            expect(statusList.childNodes.length).toEqual(2);
        });
    });

    describe('Experiment with files', function() {
        var experiment, fileList, fileDl;

        beforeEach(function() {
            var context_fs = _.clone(context);
            context_fs.files = require('../testdata/file.js');
            experiment = <Experiment context={context_fs} />;
            TestUtils.renderIntoDocument(experiment);

            fileList = TestUtils.findRenderedDOMComponentWithTag(experiment, 'tbody').getDOMNode();
            fileDl = fileList.getElementsByTagName('a');
        });

        it('has two rows in the file list', function() {
            expect(fileList.hasChildNodes()).toBeTruthy();
            expect(fileList.childNodes.length).toEqual(2);
        });

        it('has two proper download links', function() {
            expect(fileDl.length).toEqual(2);
            expect(fileDl[0].getAttribute('href')).toEqual('http://encodedcc.sdsc.edu/warehouse/2013/6/14/ENCFF001REL.txt.gz');
            expect(fileDl[1].getAttribute('href')).toEqual('http://encodedcc.sdsc.edu/warehouse/2013/6/14/ENCFF001REQ.fastq.gz');
        });
    });

    describe('Document Panel', function() {
        var experiment, doc;

        beforeEach(function() {
            var context_doc = _.clone(context);
            context_doc.documents = require('../testdata/document.js');
            experiment = <Experiment context={context_doc} />;
            TestUtils.renderIntoDocument(experiment);
            doc = TestUtils.findRenderedDOMComponentWithClass(experiment, 'type-document').getDOMNode();
        });

        it('has one document panel with a PDF image anchor', function() {
            var figures = doc.getElementsByTagName('figure');
            expect(figures.length).toEqual(1);
            var anchors = figures[0].getElementsByClassName('file-pdf');
            expect(anchors.length).toEqual(1);
        });

        it('has four key-value pairs, and proper DL link', function() {
            var url = require('url');
            var docKeyValue = doc.getElementsByClassName('key-value');
            expect(docKeyValue.length).toEqual(1);
            var defTerms = docKeyValue[0].getElementsByTagName('dt');
            expect(defTerms.length).toEqual(4);
            var defDescs = docKeyValue[0].getElementsByTagName('dd');
            expect(defDescs.length).toEqual(4);
            var anchors = defDescs[3].getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(url.parse(anchors[0].getAttribute('href')).pathname).toEqual('/documents/df9dd0ec-c1cf-4391-a745-a933ab1af7a7/@@download/attachment/Myers_Lab_ChIP-seq_Protocol_v042211.pdf');
        });
    });

    describe('Replicate Panels', function() {
        var experiment, replicates;

        beforeEach(function() {
            var context_rep = _.clone(context);
            context_rep.replicates = require('../testdata/replicate.js');
            experiment = <Experiment context={context_rep} />;
            TestUtils.renderIntoDocument(experiment);
            replicates = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'panel-replicate');
        });

        it('has two replicate panels', function() {
            expect(replicates.length).toEqual(2);
        });

        it('has links to the proper biosamples in both replicate panels', function() {
            var anchors = replicates[0].getDOMNode().getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(anchors[0].textContent).toEqual('ENCBS087RNA');
            expect(anchors[0].getAttribute('href')).toEqual('/biosamples/ENCBS087RNA/');
            anchors = replicates[1].getDOMNode().getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(anchors[0].textContent).toEqual('ENCBS088RNA');
            expect(anchors[0].getAttribute('href')).toEqual('/biosamples/ENCBS088RNA/');
        });

        describe('Assay Panel', function() {
            var assay, defTerms, defDescs;

            beforeEach(function() {
                assay = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'panel-assay');
                defTerms = assay[0].getDOMNode().getElementsByTagName('dt');
                defDescs = assay[0].getDOMNode().getElementsByTagName('dd');
            });

            it('has one assay panel and seven key-value pairs', function() {
                expect(assay.length).toEqual(1);
                expect(defTerms.length).toEqual(7);
                expect(defDescs.length).toEqual(7);
            });

            it('has a proper link to a platform in the seventh key-value pair', function() {
                var anchors = defDescs[6].getElementsByTagName('a');
                expect(anchors.length).toEqual(1);
                expect(anchors[0].getAttribute('href')).toEqual('/platforms/NTR%3A0000007');
            });
        });
    });
});
<commit_msg>Added jest test for experiment release date.<commit_after>/** @jsx React.DOM */
'use strict';

jest.autoMockOff();

// Fixes https://github.com/facebook/jest/issues/78
jest.dontMock('react');
jest.dontMock('underscore');

describe('Experiment Page', function() {
    var React, TestUtils, Experiment, context, _;

    beforeEach(function() {
        React = require('react');
        TestUtils = require('react/lib/ReactTestUtils');
        _ = require('underscore');

        Experiment = require('../experiment.js').Experiment;
        context = require('../testdata/experiment.js');

    });

    describe('Minimal Experiment', function() {
        var experiment, summary, defTerms, defDescs;

        beforeEach(function() {
            experiment = <Experiment context={context} />;
            TestUtils.renderIntoDocument(experiment);

            summary = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'data-display');
            defTerms = summary[0].getDOMNode().getElementsByTagName('dt');
            defDescs = summary[0].getDOMNode().getElementsByTagName('dd');
        });

        it('Has correct summary panel and key-value elements counts within it', function() {
            expect(summary.length).toEqual(1);
            expect(defTerms.length).toEqual(8);
            expect(defDescs.length).toEqual(8);
        });

        it('has proper links in dbxrefs key-value', function() {
            var dbxrefs = defDescs[6].getElementsByTagName('a');
            expect(dbxrefs.length).toEqual(2);
            expect(dbxrefs[0].getAttribute('href')).toEqual('http://genome.ucsc.edu/cgi-bin/hgTracks?tsCurTab=advancedTab&tsGroup=Any&tsType=Any&hgt_mdbVar1=dccAccession&hgt_tSearch=search&hgt_tsDelRow=&hgt_tsAddRow=&hgt_tsPage=&tsSimple=&tsName=&tsDescr=&db=hg19&hgt_mdbVal1=wgEncodeEH003317');
            expect(dbxrefs[1].getAttribute('href')).toEqual('http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM1010811');
        });

        it('has proper proper release date', function() {
            expect(defDescs[7].textContent).toEqual('2011-10-29');
        });

        it('has two experiment status elements in header', function() {
            var statusList = TestUtils.findRenderedDOMComponentWithClass(experiment, 'status-list').getDOMNode();
            expect(statusList.hasChildNodes()).toBeTruthy();
            expect(statusList.childNodes.length).toEqual(2);
        });
    });

    describe('Experiment with files', function() {
        var experiment, fileList, fileDl;

        beforeEach(function() {
            var context_fs = _.clone(context);
            context_fs.files = require('../testdata/file.js');
            experiment = <Experiment context={context_fs} />;
            TestUtils.renderIntoDocument(experiment);

            fileList = TestUtils.findRenderedDOMComponentWithTag(experiment, 'tbody').getDOMNode();
            fileDl = fileList.getElementsByTagName('a');
        });

        it('has two rows in the file list', function() {
            expect(fileList.hasChildNodes()).toBeTruthy();
            expect(fileList.childNodes.length).toEqual(2);
        });

        it('has two proper download links', function() {
            expect(fileDl.length).toEqual(2);
            expect(fileDl[0].getAttribute('href')).toEqual('http://encodedcc.sdsc.edu/warehouse/2013/6/14/ENCFF001REL.txt.gz');
            expect(fileDl[1].getAttribute('href')).toEqual('http://encodedcc.sdsc.edu/warehouse/2013/6/14/ENCFF001REQ.fastq.gz');
        });
    });

    describe('Document Panel', function() {
        var experiment, doc;

        beforeEach(function() {
            var context_doc = _.clone(context);
            context_doc.documents = require('../testdata/document.js');
            experiment = <Experiment context={context_doc} />;
            TestUtils.renderIntoDocument(experiment);
            doc = TestUtils.findRenderedDOMComponentWithClass(experiment, 'type-document').getDOMNode();
        });

        it('has one document panel with a PDF image anchor', function() {
            var figures = doc.getElementsByTagName('figure');
            expect(figures.length).toEqual(1);
            var anchors = figures[0].getElementsByClassName('file-pdf');
            expect(anchors.length).toEqual(1);
        });

        it('has four key-value pairs, and proper DL link', function() {
            var url = require('url');
            var docKeyValue = doc.getElementsByClassName('key-value');
            expect(docKeyValue.length).toEqual(1);
            var defTerms = docKeyValue[0].getElementsByTagName('dt');
            expect(defTerms.length).toEqual(4);
            var defDescs = docKeyValue[0].getElementsByTagName('dd');
            expect(defDescs.length).toEqual(4);
            var anchors = defDescs[3].getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(url.parse(anchors[0].getAttribute('href')).pathname).toEqual('/documents/df9dd0ec-c1cf-4391-a745-a933ab1af7a7/@@download/attachment/Myers_Lab_ChIP-seq_Protocol_v042211.pdf');
        });
    });

    describe('Replicate Panels', function() {
        var experiment, replicates;

        beforeEach(function() {
            var context_rep = _.clone(context);
            context_rep.replicates = require('../testdata/replicate.js');
            experiment = <Experiment context={context_rep} />;
            TestUtils.renderIntoDocument(experiment);
            replicates = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'panel-replicate');
        });

        it('has two replicate panels', function() {
            expect(replicates.length).toEqual(2);
        });

        it('has links to the proper biosamples in both replicate panels', function() {
            var anchors = replicates[0].getDOMNode().getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(anchors[0].textContent).toEqual('ENCBS087RNA');
            expect(anchors[0].getAttribute('href')).toEqual('/biosamples/ENCBS087RNA/');
            anchors = replicates[1].getDOMNode().getElementsByTagName('a');
            expect(anchors.length).toEqual(1);
            expect(anchors[0].textContent).toEqual('ENCBS088RNA');
            expect(anchors[0].getAttribute('href')).toEqual('/biosamples/ENCBS088RNA/');
        });

        describe('Assay Panel', function() {
            var assay, defTerms, defDescs;

            beforeEach(function() {
                assay = TestUtils.scryRenderedDOMComponentsWithClass(experiment, 'panel-assay');
                defTerms = assay[0].getDOMNode().getElementsByTagName('dt');
                defDescs = assay[0].getDOMNode().getElementsByTagName('dd');
            });

            it('has one assay panel and seven key-value pairs', function() {
                expect(assay.length).toEqual(1);
                expect(defTerms.length).toEqual(7);
                expect(defDescs.length).toEqual(7);
            });

            it('has a proper link to a platform in the seventh key-value pair', function() {
                var anchors = defDescs[6].getElementsByTagName('a');
                expect(anchors.length).toEqual(1);
                expect(anchors[0].getAttribute('href')).toEqual('/platforms/NTR%3A0000007');
            });
        });
    });
});
<|endoftext|>


<commit_before>

var CacheManagerBackend = {

  CONTENT_HANDLER: 'cacheMonitor',
  STATUS_OK: 'ok',
  STATUS_ERROR: 'error',

  defaultErrorHandle: function(status, errorMsg){
    alert('Error :' + errorMsg);
  },

  handleResponse: function(response, callback){
    if(response.status == this.STATUS_OK){
      if(typeof(callback) == 'function'){
        callback(response.result);
      }
    }
    else {
      if(typeof(errorCallback) == 'function'){
        errorCallback(reponse.status, response.errorMsg);
      } else {
        this.defaultErrorHandle(response.status, response.errorMsg);
      }
    }
  },

  postJson: function(args, callback, errorCallback){
    var self = this;
    UI.loadingImg.show();
    $.post(this.CONTENT_HANDLER, args,
    function(response)
    {
      UI.loadingImg.hide();
      self.handleResponse(response, callback, errorCallback);
    }, 'json');
  },

  getJson: function(args, callback, errorCallback){
    var self = this;
    UI.loadingImg.show();
    $.getJSON(this.CONTENT_HANDLER, args,
      function(response)
      {
        UI.loadingImg.hide();
        self.handleResponse(response, callback, errorCallback);
      });

  }

};

var UI = {

  setButtonSelected: function(button, selected){
    if(!button.hasClass('selected')){
      if(selected) button.addClass('selected');
    }
    else if(!selected) button.removeClass('selected');
  },

  //define UI elements
  init: function(){
    //main panes
    this.cachedQueries = $('#cachedQueries');
    this.scheduledQueries = $('#scheduledQueries');
    //main pane switch buttons
    this.cacheButton = $('#cacheButton');
    this.scheduleButton = $('#scheduleButton');
    //cache area
    this.cachedQueries = $('#cachedQueries');
    this.cachedQueriesDetail = $('#cachedQueriesDetail');
    this.cachedQueriesOverview = $('#cachedQueriesOverview');
    this.cachedQueriesOverviewLines = $("#cachedQueriesOverviewLines");
    this.clearCacheButton = $("#clearCacheButton");
    //loading imgs
    this.loadingImg = $('#loading');
  }
};

/** SCHEDULER **/

var refreshTable = function(){

  UI.cachedQueries.hide();
  UI.scheduledQueries.show();
  UI.setButtonSelected(UI.cacheButton, false);
  UI.setButtonSelected(UI.scheduleButton, true);

  $.getJSON('cacheController?method=list', populateQueries);
};

var populateQueries = function(data){
  var ph = $("#lines").empty();

  for (row in data.queries) {

    var r = data.queries[row];

    var row = $("

");

    // Name
    var name = r.cdaFile + " (" + r.dataAccessId + ")";
    row.append("
" + name + "
");

    var paramPh = $("

");
    for (var param in r.parameters){
      paramPh.append("
"+param+"

"+r.parameters[param]+"
");
    }
    $("

").append(paramPh).appendTo(row);

    row.append("
" + formatDate(r.lastExecuted) + "
");
    row.append("
" + formatDate(r.nextExecution) + "
");
    row.append("
" + r.cronString + "
");
    row.append("
" + r.timeElapsed + "
");
    row.append("
" + (r.success?"Success":"Failed") + "
");

    var deleteButton = $("");
    var deleteFunction = function(id){
      deleteButton.click(function(){
        if(confirm("Want to delete this scheduler?")){
          $.getJSON("cacheController?method=delete&id=" + id ,function(){
            refreshTable();
          })
        }
      })
    };
    deleteFunction(r.id);

    var refreshButton = $("");
    var refreshFunction = function(id){
      refreshButton.click(function(){

        var myself = this;
        $(this).find("img").attr("src","cachemanager/processing.png");
        $.getJSON("cacheController?method=execute&id=" + id,function(){
          refreshTable();
        })

      })
    };
    refreshFunction(r.id);

    $("

").append(refreshButton).append(deleteButton).appendTo(row);

    ph.append(row);

  }
};

/** CACHE **/

//Main cache view
var refreshCachedOverviewTable = function()
{
  UI.scheduledQueries.hide();
  UI.cachedQueriesDetail.hide();

  UI.cachedQueries.show();
  UI.cachedQueriesDetail.hide();
  UI.cachedQueriesOverview.show();

  UI.setButtonSelected(UI.scheduleButton, false);
  UI.setButtonSelected(UI.cacheButton, true);

  UI.clearCacheButton.text('Clear Cache');
  UI.clearCacheButton.unbind('click');
  UI.clearCacheButton.click(function(){
    if(confirm('This will remove ALL items from cache. Are you sure?')){
      CacheManagerBackend.getJson(
        {method:'removeAll'},
        function(itemsDeleted){
          alert(itemsDeleted + ' items have been removed from cache');
          CacheManagerBackend.getJson({method : 'cacheOverview'},populateCachedQueriesOverview);
        }
      );
    }
  });

  //getGeneralInfo();

  CacheManagerBackend.getJson({method : 'cacheOverview'},populateCachedQueriesOverview, CacheManagerBackend.defaultErrorHandle);
}

var refreshCachedTable = function(cdaSettingsId, dataAccessId){

  UI.cachedQueriesOverview.hide();
  UI.cachedQueriesDetail.show();

  var clearBtnText = "Clear all items";
  if(cdaSettingsId != null){
    clearBtnText += " for " + cdaSettingsId;
    if(dataAccessId != null){
      clearBtnText += " (" + dataAccessId + ")";
    }
  }
  UI.clearCacheButton.text(clearBtnText);
  UI.clearCacheButton.unbind('click');
  UI.clearCacheButton.click(function(){
    var confText = "This will clear All items" +
      (cdaSettingsId != null?
       (" where cdaSettingsId='" + cdaSettingsId + "'" +
         (dataAccessId!=null? "and dataAccessId='"+ dataAccessId+"'" : "")):
       "");
    confText += ". Are you sure?";
    if(confirm(confText)){
      var callArgs = {method:'removeAll'};
      if(cdaSettingsId!= null){
        callArgs.cdaSettingsId = cdaSettingsId;
        if(dataAccessId!=null) callArgs.dataAccessId = dataAccessId;
      }
      CacheManagerBackend.getJson(
        callArgs,
        function(itemsDeleted){
          alert(itemsDeleted + ' items have been removed from cache');
          refreshCachedTable(cdaSettingsId, dataAccessId);
        }
      );
    }
  });

  var callArgs = {method:'cached'};
  if(cdaSettingsId!= null){
    callArgs.cdaSettingsId = cdaSettingsId;
    if(dataAccessId!=null) callArgs.dataAccessId = dataAccessId;
  }
  CacheManagerBackend.getJson(
            callArgs,
            populateCachedQueries,
            function(status, errorMsg){
              var row = $('
').text('Problem accessing cache. Check log for errors or reload to try again.');
              $("#cachedQueriesOverviewLines").empty().append(row);
            });
};

//should be improved
var getHumanReadableSize = function(byteSize) {
  var units = ['B', 'kB', 'MB', 'GB'];
  var convRate = 1024;
  var okVal = 2047;
  var size = byteSize;

  for(i=0; i<units.length; i++)
  {
    if(size < okVal || i== units.length -1){
      return Math.round(size) + ' ' + units[i];
      //return sprintf("%.0f", size) + ' ' + units[i];
    }

    size /= convRate;
  }
  return '?';
}

//NOT IMPLEMENTED:
var getGeneralInfo = function()
{
  CacheManagerBackend.getJson({method: 'clusterInfo'}, populateClusterInfo, CacheManagerBackend.defaultErrorHandle);
  CacheManagerBackend.getJson({method: 'mapInfo'}, populateMapInfo, CacheManagerBackend.defaultErrorHandle);
}

var populateClusterInfo = function(result)
{
  var LENGTH = 12;
  var members = result.otherMembers;
  members.splice(0,0,result.localMember);

  var holder = $('#membersInfo');

  for(var i=0; i<members.length; i++){
    $('
').class('span-' + LENGTH + ' row last').text(members[i].address).appendTo(holder);
  }
}

var populateMapInfo = function(result){
  var holder = $('#mapInfo');

  var str = result.entryCount + ' entries, (' + result.ownedCount + ' owned), totalling ' + getHumanReadableSize(result.mapMemSize);
  holder.text(str);
}

var populateCachedQueriesOverview = function(results)
{
  var ph = $("#cachedQueriesOverviewLines").empty();
  if(results.length > 0){
    for (var i = 0; i< results.length;i++ )
    {
      //
CDA Settings

      //
Data Access ID

      //
# Queries

      var row = $("

");
      var item = results[i];
      var settingsLink = $('').text(item.cdaSettingsId);
      row.append($('
').addClass('span-16').append(settingsLink)); //.text(item.cdaSettingsId));

      //var dataAccessLink = $('').text(item.dataAccessId).addClass('span-6');
      row.append($('
').addClass('span-6').text(item.dataAccessId));
      row.append($('
').addClass('span-2 last').text(item.count));

      var drillDownFunction = function(cdaSettingsId, dataAccessId){
        row.click(function(){
          refreshCachedTable(cdaSettingsId, dataAccessId);
        });
        row.addClass('button');
      };
      drillDownFunction(item.cdaSettingsId, item.dataAccessId);

      var drillOnSettingsFunc = function(cdaSettingsId){
        settingsLink.click(function(event){
          //alert(cdaSettingsId);
          event.stopPropagation();
          refreshCachedTable(cdaSettingsId, null);
        });
      };
      drillOnSettingsFunc(item.cdaSettingsId);
      settingsLink.addClass('link');

      //row.addClass('button');
      ph.append(row);
    }
  }
  else {
    var row = $('
').text('Cache is empty.');
    ph.append(row);
  }

};

var removeCachedQuery =  function(key, row, cdaSettingsId, dataAccessId)
{
  row.addClass('toDelete');
  if(confirm('Are you sure you want to remove this query from cache?'))
  {
    CacheManagerBackend.postJson({method: 'removeCache', key: key},
      function(result){
        refreshCachedTable(cdaSettingsId, dataAccessId);
      }, CacheManagerBackend.defaultErrorHandle);
  }
  else
  {
    row.removeClass('toDelete');
  }
};

var populateCachedQueries = function(resp){

  var ph = $("#cachedQueriesLines").empty();

  if(resp.items.length > 0)
  {
    for (var i = 0; i< resp.items.length;i++ ) {
      //
Query

      //
Parameters

      //
# Rows

      //
Insertion

      //
Last Update

      //
# Hits

      //
Operations

      var row = $("

");
      var item = resp.items[i];

      //query
      var queryCol = $('
').addClass('span-9').addClass('queryCol').text(item.query);
      queryCol.click(
        function(){
          alert($(this).text());
        }
      );
      row.append(queryCol);

      //parameters
      var paramPh = $("

");
      for (var param in item.parameters){
        paramPh.append("
"+param+"

"+item.parameters[param]+"
");
      }
      row.append($('
').addClass('span-5').append(paramPh));
      //rows
      row.append($('
').addClass('span-1').text(item.rows));
      //size
      row.append($('
').addClass('span-2').text(item.size != null ? getHumanReadableSize(item.size) : '?'));
      //insert date
      var insertDate = new Date(item.inserted);
      row.append($('
').addClass('span-2').text(insertDate.toLocaleDateString() + ' ' + insertDate.toLocaleTimeString()));
      //access date
      var accessDate = new Date(item.accessed);
      row.append($('
').addClass('span-2').text(accessDate.toLocaleDateString() + ' ' + accessDate.toLocaleTimeString()));
      //#hits
      row.append($('
').addClass('span-1').text(item.hits));

      //remove from cache
      var removeButton = $("");
      var setRemoveAction = function(key, row, cdaSettingsId, dataAccessId){
        removeButton.click(function(){
          removeCachedQuery(key,row, cdaSettingsId, dataAccessId);
        })
      }
      setRemoveAction(item.key, row, resp.cdaSettingsId, resp.dataAccessId);

      //view results
      var tableButton = $("");
      var setQueryDetailsAction = function(tableContents, key){
        tableButton.click(function(){
            tableContents.toggle();
            if(tableContents.hasClass('empty')){
              tableContents.removeClass('empty');
              if(key)
              {
                tableContents.append( $('' ));
                CacheManagerBackend.postJson(
                  {
                    method: 'getDetails',
                    key: key
                  },
                  function(result) {
                     renderCachedTable(result, tableContents);
                  },
                  function(status, errorMsg){
                    tableContents.text('Item could not be retrieved from cache: ' + errorMsg);
                  }
                )
              }
              else{
                alert('this cache element is invalid');//TODO: better msg
              }
            }
        });
      };

      $("

").append(tableButton).append(removeButton).appendTo(row);

      row.append($('').css('display','none').addClass('keyHolder').text( escape(item.key)));

      ph.append(row);

        //table
      var tableContentsId = "tableContents" + i;
      ph.append($('
').addClass('span-22 prepend-1 append-1 empty last queryTable').css('display','none'));

      setQueryDetailsAction($('#' + tableContentsId), item.key);
    }
  }
  else //no items
  {
    var row = $('
').text('No queries in cache for ' + resp.cdaSettingsId +
                                                    (resp.dataAccessId!=null?' (' + resp.dataAccessId + ')' : ''));
    ph.append(row);
  }
};

var renderCachedTable = function(data, container)
{
  var tableContents = data.resultset;
  var columnNames = [];
  for (column in data.metadata) {
    columnNames.push({"sTitle": data.metadata[column].colName});
  }
  var table = $('

');

  container.empty();
  container.append(table);

  var dTable = table.dataTable({"aaData": tableContents, "aoColumns": columnNames, "bFilter" : false});

};

var formatDate = function(date)
{
  var d = new Date(date);
  return d.getFullYear() + "-" + pad(d.getMonth()+1) + "-"+ pad(d.getDate()) + "
" +
  pad(d.getHours())+":" + pad(d.getMinutes())+":" + pad(d.getSeconds()) ;
}

var pad = function(n){

  return ("0"+n).substr(n.toFixed().length-1);

};
<commit_msg>Bug #2088 Error deleting schedule in new trunk<commit_after>

var CacheManagerBackend = {

  CONTENT_HANDLER: 'cacheMonitor',
  STATUS_OK: 'ok',
  STATUS_ERROR: 'error',

  defaultErrorHandle: function(status, errorMsg){
    alert('Error :' + errorMsg);
  },

  handleResponse: function(response, callback){
    if(response.status == this.STATUS_OK){
      if(typeof(callback) == 'function'){
        callback(response.result);
      }
    }
    else {
      if(typeof(errorCallback) == 'function'){
        errorCallback(reponse.status, response.errorMsg);
      } else {
        this.defaultErrorHandle(response.status, response.errorMsg);
      }
    }
  },

  postJson: function(args, callback, errorCallback){
    var self = this;
    UI.loadingImg.show();
    $.post(this.CONTENT_HANDLER, args,
    function(response)
    {
      UI.loadingImg.hide();
      self.handleResponse(response, callback, errorCallback);
    }, 'json');
  },

  getJson: function(args, callback, errorCallback){
    var self = this;
    UI.loadingImg.show();
    $.getJSON(this.CONTENT_HANDLER, args,
      function(response)
      {
        UI.loadingImg.hide();
        self.handleResponse(response, callback, errorCallback);
      });

  }

};

var UI = {

  setButtonSelected: function(button, selected){
    if(!button.hasClass('selected')){
      if(selected) button.addClass('selected');
    }
    else if(!selected) button.removeClass('selected');
  },

  //define UI elements
  init: function(){
    //main panes
    this.cachedQueries = $('#cachedQueries');
    this.scheduledQueries = $('#scheduledQueries');
    //main pane switch buttons
    this.cacheButton = $('#cacheButton');
    this.scheduleButton = $('#scheduleButton');
    //cache area
    this.cachedQueries = $('#cachedQueries');
    this.cachedQueriesDetail = $('#cachedQueriesDetail');
    this.cachedQueriesOverview = $('#cachedQueriesOverview');
    this.cachedQueriesOverviewLines = $("#cachedQueriesOverviewLines");
    this.clearCacheButton = $("#clearCacheButton");
    //loading imgs
    this.loadingImg = $('#loading');
  }
};

/** SCHEDULER **/

var refreshTable = function(){

  UI.cachedQueries.hide();
  UI.scheduledQueries.show();
  UI.setButtonSelected(UI.cacheButton, false);
  UI.setButtonSelected(UI.scheduleButton, true);

  $.getJSON('cacheController?method=list', populateQueries);
};

var populateQueries = function(data){
  var ph = $("#lines").empty();

  for (row in data.queries) {

    var r = data.queries[row];

    var row = $("

");

    // Name
    var name = r.cdaFile + " (" + r.dataAccessId + ")";
    row.append("
" + name + "
");

    var paramPh = $("

");
    for (var param in r.parameters){
      paramPh.append("
"+param+"

"+r.parameters[param]+"
");
    }
    $("

").append(paramPh).appendTo(row);

    row.append("
" + formatDate(r.lastExecuted) + "
");
    row.append("
" + formatDate(r.nextExecution) + "
");
    row.append("
" + r.cronString + "
");
    row.append("
" + r.timeElapsed + "
");
    row.append("
" + (r.success?"Success":"Failed") + "
");

    var deleteButton = $("");
    var deleteFunction = function(id){
      deleteButton.click(function(){
        if(confirm("Want to delete this scheduler?")){
          $.getJSON("cacheController?method=delete&object=" + id ,function(){
            refreshTable();
          })
        }
      })
    };
    deleteFunction(r.id);

    var refreshButton = $("");
    var refreshFunction = function(id){
      refreshButton.click(function(){

        var myself = this;
        $(this).find("img").attr("src","cachemanager/processing.png");
        $.getJSON("cacheController?method=execute&object=" + id,function(){
          refreshTable();
        })

      })
    };
    refreshFunction(r.id);

    $("

").append(refreshButton).append(deleteButton).appendTo(row);

    ph.append(row);

  }
};

/** CACHE **/

//Main cache view
var refreshCachedOverviewTable = function()
{
  UI.scheduledQueries.hide();
  UI.cachedQueriesDetail.hide();

  UI.cachedQueries.show();
  UI.cachedQueriesDetail.hide();
  UI.cachedQueriesOverview.show();

  UI.setButtonSelected(UI.scheduleButton, false);
  UI.setButtonSelected(UI.cacheButton, true);

  UI.clearCacheButton.text('Clear Cache');
  UI.clearCacheButton.unbind('click');
  UI.clearCacheButton.click(function(){
    if(confirm('This will remove ALL items from cache. Are you sure?')){
      CacheManagerBackend.getJson(
        {method:'removeAll'},
        function(itemsDeleted){
          alert(itemsDeleted + ' items have been removed from cache');
          CacheManagerBackend.getJson({method : 'cacheOverview'},populateCachedQueriesOverview);
        }
      );
    }
  });

  //getGeneralInfo();

  CacheManagerBackend.getJson({method : 'cacheOverview'},populateCachedQueriesOverview, CacheManagerBackend.defaultErrorHandle);
}

var refreshCachedTable = function(cdaSettingsId, dataAccessId){

  UI.cachedQueriesOverview.hide();
  UI.cachedQueriesDetail.show();

  var clearBtnText = "Clear all items";
  if(cdaSettingsId != null){
    clearBtnText += " for " + cdaSettingsId;
    if(dataAccessId != null){
      clearBtnText += " (" + dataAccessId + ")";
    }
  }
  UI.clearCacheButton.text(clearBtnText);
  UI.clearCacheButton.unbind('click');
  UI.clearCacheButton.click(function(){
    var confText = "This will clear All items" +
      (cdaSettingsId != null?
       (" where cdaSettingsId='" + cdaSettingsId + "'" +
         (dataAccessId!=null? "and dataAccessId='"+ dataAccessId+"'" : "")):
       "");
    confText += ". Are you sure?";
    if(confirm(confText)){
      var callArgs = {method:'removeAll'};
      if(cdaSettingsId!= null){
        callArgs.cdaSettingsId = cdaSettingsId;
        if(dataAccessId!=null) callArgs.dataAccessId = dataAccessId;
      }
      CacheManagerBackend.getJson(
        callArgs,
        function(itemsDeleted){
          alert(itemsDeleted + ' items have been removed from cache');
          refreshCachedTable(cdaSettingsId, dataAccessId);
        }
      );
    }
  });

  var callArgs = {method:'cached'};
  if(cdaSettingsId!= null){
    callArgs.cdaSettingsId = cdaSettingsId;
    if(dataAccessId!=null) callArgs.dataAccessId = dataAccessId;
  }
  CacheManagerBackend.getJson(
            callArgs,
            populateCachedQueries,
            function(status, errorMsg){
              var row = $('
').text('Problem accessing cache. Check log for errors or reload to try again.');
              $("#cachedQueriesOverviewLines").empty().append(row);
            });
};

//should be improved
var getHumanReadableSize = function(byteSize) {
  var units = ['B', 'kB', 'MB', 'GB'];
  var convRate = 1024;
  var okVal = 2047;
  var size = byteSize;

  for(i=0; i<units.length; i++)
  {
    if(size < okVal || i== units.length -1){
      return Math.round(size) + ' ' + units[i];
      //return sprintf("%.0f", size) + ' ' + units[i];
    }

    size /= convRate;
  }
  return '?';
}

//NOT IMPLEMENTED:
var getGeneralInfo = function()
{
  CacheManagerBackend.getJson({method: 'clusterInfo'}, populateClusterInfo, CacheManagerBackend.defaultErrorHandle);
  CacheManagerBackend.getJson({method: 'mapInfo'}, populateMapInfo, CacheManagerBackend.defaultErrorHandle);
}

var populateClusterInfo = function(result)
{
  var LENGTH = 12;
  var members = result.otherMembers;
  members.splice(0,0,result.localMember);

  var holder = $('#membersInfo');

  for(var i=0; i<members.length; i++){
    $('
').class('span-' + LENGTH + ' row last').text(members[i].address).appendTo(holder);
  }
}

var populateMapInfo = function(result){
  var holder = $('#mapInfo');

  var str = result.entryCount + ' entries, (' + result.ownedCount + ' owned), totalling ' + getHumanReadableSize(result.mapMemSize);
  holder.text(str);
}

var populateCachedQueriesOverview = function(results)
{
  var ph = $("#cachedQueriesOverviewLines").empty();
  if(results.length > 0){
    for (var i = 0; i< results.length;i++ )
    {
      //
CDA Settings

      //
Data Access ID

      //
# Queries

      var row = $("

");
      var item = results[i];
      var settingsLink = $('').text(item.cdaSettingsId);
      row.append($('
').addClass('span-16').append(settingsLink)); //.text(item.cdaSettingsId));

      //var dataAccessLink = $('').text(item.dataAccessId).addClass('span-6');
      row.append($('
').addClass('span-6').text(item.dataAccessId));
      row.append($('
').addClass('span-2 last').text(item.count));

      var drillDownFunction = function(cdaSettingsId, dataAccessId){
        row.click(function(){
          refreshCachedTable(cdaSettingsId, dataAccessId);
        });
        row.addClass('button');
      };
      drillDownFunction(item.cdaSettingsId, item.dataAccessId);

      var drillOnSettingsFunc = function(cdaSettingsId){
        settingsLink.click(function(event){
          //alert(cdaSettingsId);
          event.stopPropagation();
          refreshCachedTable(cdaSettingsId, null);
        });
      };
      drillOnSettingsFunc(item.cdaSettingsId);
      settingsLink.addClass('link');

      //row.addClass('button');
      ph.append(row);
    }
  }
  else {
    var row = $('
').text('Cache is empty.');
    ph.append(row);
  }

};

var removeCachedQuery =  function(key, row, cdaSettingsId, dataAccessId)
{
  row.addClass('toDelete');
  if(confirm('Are you sure you want to remove this query from cache?'))
  {
    CacheManagerBackend.postJson({method: 'removeCache', key: key},
      function(result){
        refreshCachedTable(cdaSettingsId, dataAccessId);
      }, CacheManagerBackend.defaultErrorHandle);
  }
  else
  {
    row.removeClass('toDelete');
  }
};

var populateCachedQueries = function(resp){

  var ph = $("#cachedQueriesLines").empty();

  if(resp.items.length > 0)
  {
    for (var i = 0; i< resp.items.length;i++ ) {
      //
Query

      //
Parameters

      //
# Rows

      //
Insertion

      //
Last Update

      //
# Hits

      //
Operations

      var row = $("

");
      var item = resp.items[i];

      //query
      var queryCol = $('
').addClass('span-9').addClass('queryCol').text(item.query);
      queryCol.click(
        function(){
          alert($(this).text());
        }
      );
      row.append(queryCol);

      //parameters
      var paramPh = $("

");
      for (var param in item.parameters){
        paramPh.append("
"+param+"

"+item.parameters[param]+"
");
      }
      row.append($('
').addClass('span-5').append(paramPh));
      //rows
      row.append($('
').addClass('span-1').text(item.rows));
      //size
      row.append($('
').addClass('span-2').text(item.size != null ? getHumanReadableSize(item.size) : '?'));
      //insert date
      var insertDate = new Date(item.inserted);
      row.append($('
').addClass('span-2').text(insertDate.toLocaleDateString() + ' ' + insertDate.toLocaleTimeString()));
      //access date
      var accessDate = new Date(item.accessed);
      row.append($('
').addClass('span-2').text(accessDate.toLocaleDateString() + ' ' + accessDate.toLocaleTimeString()));
      //#hits
      row.append($('
').addClass('span-1').text(item.hits));

      //remove from cache
      var removeButton = $("");
      var setRemoveAction = function(key, row, cdaSettingsId, dataAccessId){
        removeButton.click(function(){
          removeCachedQuery(key,row, cdaSettingsId, dataAccessId);
        })
      }
      setRemoveAction(item.key, row, resp.cdaSettingsId, resp.dataAccessId);

      //view results
      var tableButton = $("");
      var setQueryDetailsAction = function(tableContents, key){
        tableButton.click(function(){
            tableContents.toggle();
            if(tableContents.hasClass('empty')){
              tableContents.removeClass('empty');
              if(key)
              {
                tableContents.append( $('' ));
                CacheManagerBackend.postJson(
                  {
                    method: 'getDetails',
                    key: key
                  },
                  function(result) {
                     renderCachedTable(result, tableContents);
                  },
                  function(status, errorMsg){
                    tableContents.text('Item could not be retrieved from cache: ' + errorMsg);
                  }
                )
              }
              else{
                alert('this cache element is invalid');//TODO: better msg
              }
            }
        });
      };

      $("

").append(tableButton).append(removeButton).appendTo(row);

      row.append($('').css('display','none').addClass('keyHolder').text( escape(item.key)));

      ph.append(row);

        //table
      var tableContentsId = "tableContents" + i;
      ph.append($('
').addClass('span-22 prepend-1 append-1 empty last queryTable').css('display','none'));

      setQueryDetailsAction($('#' + tableContentsId), item.key);
    }
  }
  else //no items
  {
    var row = $('
').text('No queries in cache for ' + resp.cdaSettingsId +
                                                    (resp.dataAccessId!=null?' (' + resp.dataAccessId + ')' : ''));
    ph.append(row);
  }
};

var renderCachedTable = function(data, container)
{
  var tableContents = data.resultset;
  var columnNames = [];
  for (column in data.metadata) {
    columnNames.push({"sTitle": data.metadata[column].colName});
  }
  var table = $('

');

  container.empty();
  container.append(table);

  var dTable = table.dataTable({"aaData": tableContents, "aoColumns": columnNames, "bFilter" : false});

};

var formatDate = function(date)
{
  var d = new Date(date);
  return d.getFullYear() + "-" + pad(d.getMonth()+1) + "-"+ pad(d.getDate()) + "
" +
  pad(d.getHours())+":" + pad(d.getMinutes())+":" + pad(d.getSeconds()) ;
}

var pad = function(n){

  return ("0"+n).substr(n.toFixed().length-1);

};
<|endoftext|>


<commit_before>const should = require('should')
const check = require('../assets/check.js')
const sinon = require('sinon')

describe('check', () => {
  describe('with no message available', ()=>{
    it('returns an empty list', async () =>{
      const res = check({
        getUpdates: () => ({result: []})
      })()

      return should(await res).be.eql([])
    })
  })

  describe('with messages available', ()=>{
    const mockApi = {
      getUpdates: () => ({
        result: [{message: {text: 'hi'}, update_id: 42}]
      })
    }
    it('returns an update for each message available', async ()=>{
      const res = check(mockApi)()

      should(await res).be.eql([{update_id: '42'}])
    })

    describe('with a filter defined', ()=>{
      const filter = /not_hi/

      it('filters out messages not matching the regex',  async ()=>{
        const res = await check({
          getUpdates: () => ({
            result: [
              {message: {text: 'hi'}, update_id: 42},
              {message: {text: 'not_hi'}, update_id: 43},
            ]
          })
        }, {}, filter)()

        should(await res).be.eql([{update_id: '43'}])
      })

      it('filters out messages not matching the regex, even all of them',  async ()=>{
        const res = check(mockApi, {}, filter)()

        should(await res).be.eql([])
      })
    })
  })

})
<commit_msg>testing readConfig<commit_after>const should = require('should')
const check = require('../assets/check.js')
const sinon = require('sinon')

describe('check', () => {
  describe('with no message available', ()=>{
    it('returns an empty list', async () =>{
      const res = check({
        getUpdates: () => ({result: []})
      })()

      return should(await res).be.eql([])
    })
  })

  describe('with messages available', ()=>{
      const mockApi = {
          getUpdates: () => ({
              result: [
                  {message: {text: 'hi'}, update_id: 42},
                  {message: {text: 'not_hi'}, update_id: 43},
              ]
          })
      }
    it('returns an update for each message available', async ()=>{
      const res = check(mockApi)()

        should(await res).be.eql([{update_id: '42'},{update_id: '43'}])
    })

    describe('with a filter defined', ()=>{
      const filter = /not_hi/

      it('filters out messages not matching the regex',  async ()=>{
        const res = await check(mockApi, {}, filter)()

        should(await res).be.eql([{update_id: '43'}])
      })

      it('filters out messages not matching the regex, even all of them',  async ()=>{
        const res = check(mockApi, {}, /asd/)()

        should(await res).be.eql([])
      })
    })
  })

})
<|endoftext|>


<commit_before>'use strict';
/*jshint asi: true */

var test = require('tape')
  , rmrf = require('rimraf')
  , spawn = require('child_process').spawn
  , path = require('path')
  , initRepo = require('../lib/init-repo')

function hackFunctionBind () {
  // HACK: cannot push to remote during tests, so we'll have to hack Function.bind a bit
  var function_bind = Function.prototype.bind;
  Function.prototype.bind = function (this_, arg) {
    if (arg && arg[0] === 'push' && arg[1] === 'origin')
      return function (cb) { setTimeout(cb, 5) }

    return function_bind.apply(this, arguments);
  }
}

function gitcmd (cmds, cb) {
  var cmd = spawn('git', cmds)
  var msg = '';

  cmd.stdout.on('data', function (d) {
    msg += d
  });

  cmd.stderr.on('data', console.error)
  cmd.on('close', function (code) {
    cb(msg);
  });
}

test('\ninit repo create repository, adds all files, adds remote and commits', function (t) {

  var repodir = path.join(__dirname, 'fixtures', 'init-repo')

  rmrf(path.join(repodir, '.git'), function (err) {
    if (err) return t.fail(err)

    var cwd = process.cwd()
    process.chdir(repodir)

    hackFunctionBind()

    initRepo('joe', 'joerepo', function (err) {
      gitcmd([ 'log', '--oneline' ], function (res) {
        var msg = res.split(' ').splice(1).join(' ')
        t.equal('"initial repository"\n', msg, 'includes first commit')

        gitcmd([ 'remote', '-v' ], function (res) {
          t.deepEqual(
              res.split('\n')
            , [ 'origin	git@github.com:joe/joerepo.git (fetch)'
              , 'origin	git@github.com:joe/joerepo.git (push)'
              , ''
              ]
            , 'adds origin remotes'
          )
          rmrf(path.join(repodir, '.git'), function () {
            process.chdir(cwd)
            t.end()
          })
        })
      })
    })
  })
})
<commit_msg>fixing test issue<commit_after>'use strict';
/*jshint asi: true */

var test = require('tape')
  , rmrf = require('rimraf')
  , spawn = require('child_process').spawn
  , path = require('path')
  , initRepo = require('../lib/init-repo')

function hackFunctionBind () {
  // HACK: cannot push to remote during tests, so we'll have to hack Function.bind a bit
  var function_bind = Function.prototype.bind;
  Function.prototype.bind = function (this_, arg) {
    if (arg && arg[0] === 'push' && arg[1] === 'origin')
      return function (cb) { setTimeout(cb, 5) }

    return function_bind.apply(this, arguments);
  }
}

function gitcmd (cmds, cb) {
  var cmd = spawn('git', cmds)
  var msg = '';

  cmd.stdout.on('data', function (d) {
    msg += d
  });

  cmd.stderr.on('data', console.error)
  cmd.on('close', function (code) {
    cb(msg);
  });
}

test('\ninit repo create repository, adds all files, adds remote and commits', function (t) {

  var repodir = path.join(__dirname, 'fixtures', 'init-repo')

  rmrf(path.join(repodir, '.git'), function (err) {
    if (err) return t.fail(err)

    var cwd = process.cwd()
    process.chdir(repodir)

    hackFunctionBind()

    initRepo('joe', 'joerepo', function (err) {
      gitcmd([ 'log', '--oneline' ], function (res) {
        var msg = res.split(' ').splice(1).join(' ')
        t.equal(msg, '"initial repository"\n', 'includes first commit')

        gitcmd([ 'remote', '-v' ], function (res) {
          t.deepEqual(
              res.split('\n')
            , [ 'origin	git@github.com:joe/joerepo.git (fetch)'
              , 'origin	git@github.com:joe/joerepo.git (push)'
              , ''
              ]
            , 'adds origin remotes'
          )
          rmrf(path.join(repodir, '.git'), function () {
            process.chdir(cwd)
            t.end()
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>
var sl = require('..');

var list = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 3, name: 'Abel', age: 500, gender: 'man' },
    { id: 4, name: 'Caine', age: 400, gender: 'man' }
];

var list2 = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 5, name: 'Set', age: 300, gender: 'man' },
    { id: 6, name: 'Sarah', age: 200, gender: 'woman' }
];

exports['intersect list with list'] = function (test) {
    var result = sl.intersect(list, list, 'id');

    test.ok(result);
    test.ok(Array.isArray(result));
    test.equal(result.length, list.length);

    for (var k = 0; k < result.length; k++)
        test.equal(result[k].id, list[k].id);
}

exports['intersect list with second list'] = function (test) {
    var result = sl.intersect(list, list2, 'id');

    test.ok(result);
    test.ok(Array.isArray(result));
    test.equal(result.length, 2);

    for (var k = 0; k < result.length; k++) {
        test.ok(sl.exist(list, { id: result[k].id }));
        test.ok(sl.exist(list2, { id: result[k].id }));
    }

    test.ok(sl.exist(result, { name: 'Adam', id: 1 }));
    test.ok(sl.exist(result, { name: 'Eve', id: 2 }));
}

<commit_msg>Refactor intersect tests<commit_after>
const sl = require('..');

const list = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 3, name: 'Abel', age: 500, gender: 'man' },
    { id: 4, name: 'Caine', age: 400, gender: 'man' }
];

const list2 = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 5, name: 'Set', age: 300, gender: 'man' },
    { id: 6, name: 'Sarah', age: 200, gender: 'woman' }
];

exports['intersect list with list'] = function (test) {
    const result = sl.intersect(list, list, 'id');

    test.ok(result);
    test.ok(Array.isArray(result));
    test.equal(result.length, list.length);

    for (let k = 0; k < result.length; k++)
        test.equal(result[k].id, list[k].id);
}

exports['intersect list with second list'] = function (test) {
    const result = sl.intersect(list, list2, 'id');

    test.ok(result);
    test.ok(Array.isArray(result));
    test.equal(result.length, 2);

    for (let k = 0; k < result.length; k++) {
        test.ok(sl.exist(list, { id: result[k].id }));
        test.ok(sl.exist(list2, { id: result[k].id }));
    }

    test.ok(sl.exist(result, { name: 'Adam', id: 1 }));
    test.ok(sl.exist(result, { name: 'Eve', id: 2 }));
}

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file or at
 * https://developers.google.com/open-source/licenses/bsd
 */
({
async update(inputs, state) {
  if (!state.publicPipelines) {
    try {
      state.publicPipelines = await this.fetchPublicPipelines(inputs);
    } catch (e) {
      log(`Failed fetching public pipelines from ${inputs.publicPipelinesUrl} (${e.toString()})`);
    }
  }
},
async fetchPublicPipelines({publicPipelinesUrl, pipelines}) {
  if (publicPipelinesUrl) {
    const res = await fetch(publicPipelinesUrl);
    if (res.status === 200) {
      const text = await res.text();
      if (text) {
        const publicPipelines = values(JSON.parse(text.replace(/"\*/g, '"$')) ?? Object);
        return this.filterPublicPipelines(publicPipelines, pipelines);
      }
    }
  }
},
filterPublicPipelines(publicPipelines, pipelines) {
  if (Array.isArray(publicPipelines)) {
    return publicPipelines.filter(({$meta: {name, id}}) => {
      // Prior to 0.4.0 pipelines were created with `name` only.
      // Filtering by `name` (in addition to filtering by `id`) is done for backward compabitility.
      return !this.findPipelineById(id, pipelines) && !this.findPipelineByName(name, pipelines);
    });
  }
},
render({pipeline, pipelines}, {publicPipelines}) {
  const separator = {name: '_________________', selected: false, isDisabled: true};
  return {
    pipelines: [
      ...(this.renderPipelines(pipelines, pipeline?.$meta?.name) || []),
      ...(publicPipelines?.length > 0 ? [separator] : []),
      ...(this.renderPipelines(publicPipelines, pipeline?.$meta?.name) || [])
    ]
  };
},
renderPipelines(pipelines, selectedName) {
  return !pipelines ? [] : pipelines?.map?.(({$meta}) => ({
    name: $meta?.name,
    id: $meta?.id || $meta.name,
    isDisabled: false,
    isSelected: $meta?.name === selectedName
  }));
},
onSelect({eventlet: {value}, pipelines}, {publicPipelines}) {
  const pipeline = this.findPipelineById(value, pipelines)
    || this.findPipelineById(value, publicPipelines)
    // Backward compatibility: prior to 0.4.0 pipelines were created with `name` only.
    || this.findPipelineByName(value, publicPipelines);
  log(`selected "${value}" (${pipeline?.$meta.name})`);
  return {pipeline};
},
findPipelineById(id, pipelines) {
  return pipelines?.find?.(({$meta}) => $meta?.id === id);
},
findPipelineByName(name, pipelines) {
  return pipelines?.find?.(({$meta}) => $meta?.name === name);
},
onRefresh(inputs, state) {
  state.publicPipelines = null;
},
template: html`

  <select title="Current Pipeline" repeat="pipeline_t" on-change="onSelect">{{pipelines}}</select>
  <mwc-icon-button title="Refresh Pipeline List" icon="refresh" on-click="onRefresh"></mwc-icon-button>

<template pipeline_t>
  <option selected="{{isSelected}}" value="{{id}}" disabled="{{isDisabled}}">{{name}}</option>
</template>
  `
});
<commit_msg>fix selected pipeline in Chooser (#65)<commit_after>/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file or at
 * https://developers.google.com/open-source/licenses/bsd
 */
({
async update(inputs, state) {
  if (!state.publicPipelines) {
    try {
      state.publicPipelines = await this.fetchPublicPipelines(inputs);
    } catch (e) {
      log(`Failed fetching public pipelines from ${inputs.publicPipelinesUrl} (${e.toString()})`);
    }
  }
},
async fetchPublicPipelines({publicPipelinesUrl, pipelines}) {
  if (publicPipelinesUrl) {
    const res = await fetch(publicPipelinesUrl);
    if (res.status === 200) {
      const text = await res.text();
      if (text) {
        const publicPipelines = values(JSON.parse(text.replace(/"\*/g, '"$')) ?? Object);
        return this.filterPublicPipelines(publicPipelines, pipelines);
      }
    }
  }
},
filterPublicPipelines(publicPipelines, pipelines) {
  if (Array.isArray(publicPipelines)) {
    return publicPipelines.filter(({$meta: {name, id}}) => {
      // Prior to 0.4.0 pipelines were created with `name` only.
      // Filtering by `name` (in addition to filtering by `id`) is done for backward compabitility.
      return !this.findPipelineById(id, pipelines) && !this.findPipelineByName(name, pipelines);
    });
  }
},
render({pipeline, pipelines}, {publicPipelines}) {
  const separator = {name: '_________________', selected: false, isDisabled: true};
  return {
    pipelines: [
      ...(this.renderPipelines(pipelines, pipeline) || []),
      ...(publicPipelines?.length > 0 ? [separator] : []),
      ...(this.renderPipelines(publicPipelines, pipeline) || [])
    ]
  };
},
renderPipelines(pipelines, selectedPipeline) {
  return pipelines ? pipelines?.map?.(pipeline => {
    const id = this.pipelineId(pipeline);
    return {
      name: pipeline.$meta?.name,
      id,
      isDisabled: false,
      isSelected: id === this.pipelineId(selectedPipeline)
    };
  }) : [];
},
pipelineId(pipeline) {
  // Backward compatibility: prior to 0.4.0 pipelines were created with `name` only, without a unique id.
  return pipeline?.$meta.id || pipeline?.$meta?.name || null;
},
onSelect({eventlet: {value}, pipelines}, {publicPipelines}) {
  const pipeline = this.findPipelineById(value, pipelines)
    || this.findPipelineById(value, publicPipelines)
    // Backward compatibility: prior to 0.4.0 pipelines were created with `name` only.
    || this.findPipelineByName(value, publicPipelines);
  log(`selected "${value}" (${pipeline?.$meta.name})`);
  return {pipeline};
},
findPipelineById(id, pipelines) {
  return pipelines?.find?.(({$meta}) => $meta?.id === id);
},
findPipelineByName(name, pipelines) {
  return pipelines?.find?.(({$meta}) => $meta?.name === name);
},
onRefresh(inputs, state) {
  state.publicPipelines = null;
},
template: html`

  <select title="Current Pipeline" repeat="pipeline_t" on-change="onSelect">{{pipelines}}</select>
  <mwc-icon-button title="Refresh Pipeline List" icon="refresh" on-click="onRefresh"></mwc-icon-button>

<template pipeline_t>
  <option selected="{{isSelected}}" value="{{id}}" disabled="{{isDisabled}}">{{name}}</option>
</template>
  `
});
<|endoftext|>


<commit_before>angular
module('Cadastrar').
  component('registrarDepartamento', {
    templateUrl: '/app/Cadastrar/cadastrar.template.html',
    controller: ['ApiDepartamento','$http','$location', 'MatWebGlobals',function registrarDepartamento(ApiDepartamento,$http,$location,MatWebGlobals) {
        var ctrl = this;
this.formulario = {'depName':'','idNumber':''};
        ctrl.cadastrar = cadastrar;

        function cadastrar() {
            ctrl.mensagem = true;
            UserService.Create(ctrl.formulario)
                .then(function (data) {
                    if (data.success) {
                        FlashService.Success('Registration successful', true);
                        $location.path('/Cadastrar');
                    } else {
                        FlashService.Error(data.message);
                        ctrl.mensagem = false;
                    }
                });
        }
    }<commit_msg>lol 2017-05-17<commit_after>angular
module('Cadastrar').
  component('registrarDepartamento', {
    templateUrl: '/app/Cadastrar/cadastrar.template.html',
    controller: ['ApiDepartamento','$http','$location', 'MatWebGlobals',function registrarDepartamento(ApiDepartamento,$http,$location,MatWebGlobals) {
        var ctrl = this;
       this.formulario = {'depName':'','idNumber':''};
        ctrl.cadastrar = cadastrar;

        function cadastrar() {
            ctrl.mensagem = true;
            ApiDepartamento.Create(ctrl.formulario)
                .then(function (data) {
                    if (data.success) {
                        MatWebGlobals.Success('Registration successful', true);
                        $location.path('/Cadastrar');
                    } else {
                        MatWebGlobals.Error(data.mensagem);
                        ctrl.mensagem = false;
                    }
                });
        }
    }
}();<|endoftext|>