<commit_before>import { Viewerbase } from '../namespace';

/**
 * Imports file with side effects only (files that do not export anything...)
 */

import './collections';
import './lib/debugReactivity';

/**
 * Exported Functions
 */

// getElementIfNotEmpty
import { getElementIfNotEmpty } from './lib/getElementIfNotEmpty';
Viewerbase.getElementIfNotEmpty = getElementIfNotEmpty;

// getStackDataIfNotEmpty
import { getStackDataIfNotEmpty } from './lib/getStackDataIfNotEmpty';
Viewerbase.getStackDataIfNotEmpty = getStackDataIfNotEmpty;

// switchToImageRelative
import { switchToImageRelative } from './lib/switchToImageRelative';
Viewerbase.switchToImageRelative = switchToImageRelative;

// switchToImageByIndex
import { switchToImageByIndex } from './lib/switchToImageByIndex';
Viewerbase.switchToImageByIndex = switchToImageByIndex;

// getFrameOfReferenceUID
import { getFrameOfReferenceUID } from './lib/getFrameOfReferenceUID';
Viewerbase.getFrameOfReferenceUID = getFrameOfReferenceUID;

// updateCrosshairsSynchronizer
import { updateCrosshairsSynchronizer } from './lib/updateCrosshairsSynchronizer';
Viewerbase.updateCrosshairsSynchronizer = updateCrosshairsSynchronizer;

// getImageId
import { getImageId } from './lib/getImageId';
Viewerbase.getImageId = getImageId;

// setActiveViewport
import { setActiveViewport } from './lib/setActiveViewport';
Viewerbase.setActiveViewport = setActiveViewport;

// setFocusToActiveViewport
import { setFocusToActiveViewport } from './lib/setFocusToActiveViewport';
Viewerbase.setFocusToActiveViewport = setFocusToActiveViewport;

// getWADORSImageId
import { getWADORSImageId } from './lib/getWADORSImageId';
Viewerbase.getWADORSImageId = getWADORSImageId;

// updateAllViewports
import { updateAllViewports } from './lib/updateAllViewports';
Viewerbase.updateAllViewports = updateAllViewports;

// sortStudy
import { sortStudy } from './lib/sortStudy';
Viewerbase.sortStudy = sortStudy;

// updateOrientationMarkers
import { updateOrientationMarkers } from './lib/updateOrientationMarkers';
Viewerbase.updateOrientationMarkers = updateOrientationMarkers;

// isImage
import { isImage } from './lib/isImage';
Viewerbase.isImage = isImage;

// getInstanceClassDefaultViewport, setInstanceClassDefaultViewportFunction
import { getInstanceClassDefaultViewport, setInstanceClassDefaultViewportFunction } from './lib/instanceClassSpecificViewport';
Viewerbase.getInstanceClassDefaultViewport = getInstanceClassDefaultViewport;
Viewerbase.setInstanceClassDefaultViewportFunction = setInstanceClassDefaultViewportFunction;

// displayReferenceLines
import { displayReferenceLines } from './lib/displayReferenceLines';
Viewerbase.displayReferenceLines = displayReferenceLines;

/**
 * Exported Namespaces (sub-namespaces)
 */

// imageViewerViewportData.*
import { imageViewerViewportData } from './lib/imageViewerViewportData';
Viewerbase.imageViewerViewportData = imageViewerViewportData;

// panelNavigation.*
import { panelNavigation } from './lib/panelNavigation';
Viewerbase.panelNavigation = panelNavigation;

// WLPresets.*
import { WLPresets } from './lib/WLPresets';
Viewerbase.wlPresets = WLPresets;

// hotkeyUtils.*
import { hotkeyUtils } from './lib/hotkeyUtils';
Viewerbase.hotkeyUtils = hotkeyUtils;

// viewportOverlayUtils.*
import { viewportOverlayUtils } from './lib/viewportOverlayUtils';
Viewerbase.viewportOverlayUtils = viewportOverlayUtils;

// viewportUtils.*
import { viewportUtils } from './lib/viewportUtils';
Viewerbase.viewportUtils = viewportUtils;

// thumbnailDragHandlers.*
import { thumbnailDragHandlers } from './lib/thumbnailDragHandlers';
Viewerbase.thumbnailDragHandlers = thumbnailDragHandlers;

// dialogUtils.*
import { dialogUtils } from './lib/dialogUtils';
Viewerbase.dialogUtils = dialogUtils;

// unloadHandlers.*
import { unloadHandlers } from './lib/unloadHandlers';
Viewerbase.unloadHandlers = unloadHandlers;

// sortingManager.*
import { sortingManager } from './lib/sortingManager';
Viewerbase.sortingManager = sortingManager;

// crosshairsSynchronizers.*
import { crosshairsSynchronizers } from './lib/crosshairsSynchronizers';
Viewerbase.crosshairsSynchronizers = crosshairsSynchronizers;

// annotateTextUtils.*
import { annotateTextUtils } from './lib/annotateTextUtils';
Viewerbase.annotateTextUtils = annotateTextUtils;

// textMarkerUtils.*
import { textMarkerUtils } from './lib/textMarkerUtils';
Viewerbase.textMarkerUtils = textMarkerUtils;

// createStacks.*
import { createStacks } from './lib/createStacks';
Viewerbase.createStacks = createStacks;

/**
 * Exported Singletons
 */

// StackManager as "stackManager" (since it's a plain object instance, the exported name starts with a lowercase letter)
import { StackManager } from './lib/StackManager';
Viewerbase.stackManager = StackManager;

// toolManager
import { toolManager } from './lib/toolManager';
Viewerbase.toolManager = toolManager;

/**
 * Exported Helpers
 */

import { helpers } from './lib/helpers/';
Viewerbase.helpers = helpers;

/**
 * Exported Collections
 */

// sopClassDictionary
import { sopClassDictionary } from './lib/sopClassDictionary';
Viewerbase.sopClassDictionary = sopClassDictionary;

// dicomTagDescriptions
import { dicomTagDescriptions } from './lib/dicomTagDescriptions';
Viewerbase.dicomTagDescriptions = dicomTagDescriptions;

/**
 * Exported Classes
 */

// ImageSet
import { ImageSet } from './lib/classes/ImageSet';
Viewerbase.ImageSet = ImageSet;

// ResizeViewportManager
import { ResizeViewportManager } from './lib/classes/ResizeViewportManager';
Viewerbase.ResizeViewportManager = ResizeViewportManager;

// StudyMetadata, SeriesMetadata, InstanceMetadata
import { StudyMetadata } from './lib/classes/metadata/StudyMetadata';
import { SeriesMetadata } from './lib/classes/metadata/SeriesMetadata';
import { InstanceMetadata } from './lib/classes/metadata/InstanceMetadata';
Viewerbase.metadata = { StudyMetadata, SeriesMetadata, InstanceMetadata };

// TypeSafeCollection
import { TypeSafeCollection } from './lib/classes/TypeSafeCollection';
Viewerbase.TypeSafeCollection = TypeSafeCollection;

// OHIFError
import { OHIFError } from './lib/classes/OHIFError';
Viewerbase.OHIFError = OHIFError;

// StackImagePositionOffsetSynchronizer
import { StackImagePositionOffsetSynchronizer } from './lib/classes/StackImagePositionOffsetSynchronizer';
Viewerbase.StackImagePositionOffsetSynchronizer = StackImagePositionOffsetSynchronizer;

// StudyMetadataSource
import { StudyMetadataSource } from './lib/classes/StudyMetadataSource';
Viewerbase.StudyMetadataSource = StudyMetadataSource;
<commit_msg>Adding LayoutManager class to viewerbase namespace...<commit_after>import { Viewerbase } from '../namespace';

/**
 * Imports file with side effects only (files that do not export anything...)
 */

import './collections';
import './lib/debugReactivity';

/**
 * Exported Functions
 */

// getElementIfNotEmpty
import { getElementIfNotEmpty } from './lib/getElementIfNotEmpty';
Viewerbase.getElementIfNotEmpty = getElementIfNotEmpty;

// getStackDataIfNotEmpty
import { getStackDataIfNotEmpty } from './lib/getStackDataIfNotEmpty';
Viewerbase.getStackDataIfNotEmpty = getStackDataIfNotEmpty;

// switchToImageRelative
import { switchToImageRelative } from './lib/switchToImageRelative';
Viewerbase.switchToImageRelative = switchToImageRelative;

// switchToImageByIndex
import { switchToImageByIndex } from './lib/switchToImageByIndex';
Viewerbase.switchToImageByIndex = switchToImageByIndex;

// getFrameOfReferenceUID
import { getFrameOfReferenceUID } from './lib/getFrameOfReferenceUID';
Viewerbase.getFrameOfReferenceUID = getFrameOfReferenceUID;

// updateCrosshairsSynchronizer
import { updateCrosshairsSynchronizer } from './lib/updateCrosshairsSynchronizer';
Viewerbase.updateCrosshairsSynchronizer = updateCrosshairsSynchronizer;

// getImageId
import { getImageId } from './lib/getImageId';
Viewerbase.getImageId = getImageId;

// setActiveViewport
import { setActiveViewport } from './lib/setActiveViewport';
Viewerbase.setActiveViewport = setActiveViewport;

// setFocusToActiveViewport
import { setFocusToActiveViewport } from './lib/setFocusToActiveViewport';
Viewerbase.setFocusToActiveViewport = setFocusToActiveViewport;

// getWADORSImageId
import { getWADORSImageId } from './lib/getWADORSImageId';
Viewerbase.getWADORSImageId = getWADORSImageId;

// updateAllViewports
import { updateAllViewports } from './lib/updateAllViewports';
Viewerbase.updateAllViewports = updateAllViewports;

// sortStudy
import { sortStudy } from './lib/sortStudy';
Viewerbase.sortStudy = sortStudy;

// updateOrientationMarkers
import { updateOrientationMarkers } from './lib/updateOrientationMarkers';
Viewerbase.updateOrientationMarkers = updateOrientationMarkers;

// isImage
import { isImage } from './lib/isImage';
Viewerbase.isImage = isImage;

// getInstanceClassDefaultViewport, setInstanceClassDefaultViewportFunction
import { getInstanceClassDefaultViewport, setInstanceClassDefaultViewportFunction } from './lib/instanceClassSpecificViewport';
Viewerbase.getInstanceClassDefaultViewport = getInstanceClassDefaultViewport;
Viewerbase.setInstanceClassDefaultViewportFunction = setInstanceClassDefaultViewportFunction;

// displayReferenceLines
import { displayReferenceLines } from './lib/displayReferenceLines';
Viewerbase.displayReferenceLines = displayReferenceLines;

/**
 * Exported Namespaces (sub-namespaces)
 */

// imageViewerViewportData.*
import { imageViewerViewportData } from './lib/imageViewerViewportData';
Viewerbase.imageViewerViewportData = imageViewerViewportData;

// panelNavigation.*
import { panelNavigation } from './lib/panelNavigation';
Viewerbase.panelNavigation = panelNavigation;

// WLPresets.*
import { WLPresets } from './lib/WLPresets';
Viewerbase.wlPresets = WLPresets;

// hotkeyUtils.*
import { hotkeyUtils } from './lib/hotkeyUtils';
Viewerbase.hotkeyUtils = hotkeyUtils;

// viewportOverlayUtils.*
import { viewportOverlayUtils } from './lib/viewportOverlayUtils';
Viewerbase.viewportOverlayUtils = viewportOverlayUtils;

// viewportUtils.*
import { viewportUtils } from './lib/viewportUtils';
Viewerbase.viewportUtils = viewportUtils;

// thumbnailDragHandlers.*
import { thumbnailDragHandlers } from './lib/thumbnailDragHandlers';
Viewerbase.thumbnailDragHandlers = thumbnailDragHandlers;

// dialogUtils.*
import { dialogUtils } from './lib/dialogUtils';
Viewerbase.dialogUtils = dialogUtils;

// unloadHandlers.*
import { unloadHandlers } from './lib/unloadHandlers';
Viewerbase.unloadHandlers = unloadHandlers;

// sortingManager.*
import { sortingManager } from './lib/sortingManager';
Viewerbase.sortingManager = sortingManager;

// crosshairsSynchronizers.*
import { crosshairsSynchronizers } from './lib/crosshairsSynchronizers';
Viewerbase.crosshairsSynchronizers = crosshairsSynchronizers;

// annotateTextUtils.*
import { annotateTextUtils } from './lib/annotateTextUtils';
Viewerbase.annotateTextUtils = annotateTextUtils;

// textMarkerUtils.*
import { textMarkerUtils } from './lib/textMarkerUtils';
Viewerbase.textMarkerUtils = textMarkerUtils;

// createStacks.*
import { createStacks } from './lib/createStacks';
Viewerbase.createStacks = createStacks;

/**
 * Exported Singletons
 */

// StackManager as "stackManager" (since it's a plain object instance, the exported name starts with a lowercase letter)
import { StackManager } from './lib/StackManager';
Viewerbase.stackManager = StackManager;

// toolManager
import { toolManager } from './lib/toolManager';
Viewerbase.toolManager = toolManager;

/**
 * Exported Helpers
 */

import { helpers } from './lib/helpers/';
Viewerbase.helpers = helpers;

/**
 * Exported Collections
 */

// sopClassDictionary
import { sopClassDictionary } from './lib/sopClassDictionary';
Viewerbase.sopClassDictionary = sopClassDictionary;

// dicomTagDescriptions
import { dicomTagDescriptions } from './lib/dicomTagDescriptions';
Viewerbase.dicomTagDescriptions = dicomTagDescriptions;

/**
 * Exported Classes
 */

// ImageSet
import { ImageSet } from './lib/classes/ImageSet';
Viewerbase.ImageSet = ImageSet;

// LayoutManager
import { LayoutManager } from './lib/classes/LayoutManager';
Viewerbase.LayoutManager = LayoutManager;

// ResizeViewportManager
import { ResizeViewportManager } from './lib/classes/ResizeViewportManager';
Viewerbase.ResizeViewportManager = ResizeViewportManager;

// StudyMetadata, SeriesMetadata, InstanceMetadata
import { StudyMetadata } from './lib/classes/metadata/StudyMetadata';
import { SeriesMetadata } from './lib/classes/metadata/SeriesMetadata';
import { InstanceMetadata } from './lib/classes/metadata/InstanceMetadata';
Viewerbase.metadata = { StudyMetadata, SeriesMetadata, InstanceMetadata };

// TypeSafeCollection
import { TypeSafeCollection } from './lib/classes/TypeSafeCollection';
Viewerbase.TypeSafeCollection = TypeSafeCollection;

// OHIFError
import { OHIFError } from './lib/classes/OHIFError';
Viewerbase.OHIFError = OHIFError;

// StackImagePositionOffsetSynchronizer
import { StackImagePositionOffsetSynchronizer } from './lib/classes/StackImagePositionOffsetSynchronizer';
Viewerbase.StackImagePositionOffsetSynchronizer = StackImagePositionOffsetSynchronizer;

// StudyMetadataSource
import { StudyMetadataSource } from './lib/classes/StudyMetadataSource';
Viewerbase.StudyMetadataSource = StudyMetadataSource;
<|endoftext|>


<commit_before>var filter_data = {
	all: {},
	per_lang: {
		fn: function(answer_id){
			return this[filter_data.all[answer_id]._meta.lang_text] == answer_id;
		}
	}
};

var renderAnswers = function(){

	var last_score = 0;
	var classification = 1;
	var invalid_index = 0;

	$table.html('
' +
		'
' +
			'	' +
			'Author	' +
			'Language	' +
			'Votes	' +
			' 	' +
		'
' +
	'
' +
	'
' +
		answers
			.sort(function(a, b){
				if(a.score != b.score)
				{
					return a.score - b.score;
				}
				return a.creation_date - b.creation_date;
			})
			.map(function(answer, index){

				if(index && last_score != answer.score)
				{
					classification = index + 1;
				}
				last_score = answer.score;

				return '
' +
					'' +
						(
							(
								HEURISTIC_INVALID_MARK && answer._meta.HEURISTIC_INVALID && answer._meta.HEURISTIC_INVALID_SCORE < -2
									? answer._meta.HEURISTIC_INVALID.map(function(comment){
										return ''
									})
									: ''
							) + ' ' + classification
						) +
					'	' +
					'' +
						'' +
							answer.owner.display_name +
						'' +
					'	' +
					'' +
						answer._meta.lang +
					'	' +
					'' +
						answer.score +
					'	' +
					'' +
						'View' +
					'	' +
				'
';
			}).join('') +
	'
');

	var $datatable = $table.DataTable({
		order: [],
		columnDefs: [
			{orderable: false, targets: 4},
			{searchable: false, targets: [0, 3, 4]},
			{type: 'html-num', targets: [0, 3]}
		]
	});

	var $filters = $('<select>').html(
		'<option value="all" selected="selected">All</option>' +
		'<option value="per_lang">Per Lang.</option>'
	).change(function(){
		$datatable.draw();
	});

	$('
')
		.css({'float': 'left'})
		.html(' Filter: </lavel>')
		.append($filters)
		.insertAfter('#DataTables_Table_0_length');

	//idea from http://stackoverflow.com/a/17539727/2729937
	$.fn.dataTable.ext.search.push(function(oSettings, aData, iDataIndex){
		var filter = $filters.val();

		if(filter == 'all')
		{
			return true;
		}

		var answer_id = oSettings.aoData[iDataIndex].nTr.getAttribute('data-answer_id');

		return filter_data[filter].fn(answer_id);
	});
}

var handleData = function(data){
	if(!data.length)
	{
		return;
	}
	var $span = $('');
	var $div = $('
');
	var answers = [];

	data.map(function(answer){
		var $h1 = $span.html(answer.body).find(':first-child').get(0);
			$h1.find('a').attr('target', '_blank');

		answer._meta = {
			lang: $h1.html(),
			lang_text: $h1.text().toLowerCase()
		};

		return answer;
	})
	.forEach(function(answer){

		filter_data.all[answer.answer_id] = answers[answers.length] = answer;

		if(HEURISTIC_INVALID_MARK && answer.comments && answer.comments.length)
		{
			analizeHeuristicValidity(answer);
		}

		if(filter_data.per_lang[answer._meta.lang_text])
		{
			var prev_answer = filter_data.all[filter_data.per_lang[answer._meta.lang_text]];

			if(prev_answer._meta.size == answer._meta.size)
			{
				filter_data.per_lang[answer._meta.lang_text] = prev_answer.creation_date > answer.creation_date
					? answer.answer_id
					: prev_answer.answer_id;
			}
			else if(prev_answer._meta.size > answer._meta.size)
			{
				filter_data.per_lang[answer._meta.lang_text] = answer.answer_id;
			}
		}
		else
		{
			filter_data.per_lang[answer._meta.lang_text] = answer.answer_id;
		}
	});

	setTimeout((function(){
		renderAnswers(this);
	}).bind(answers), 10);
};

handleData(answers);
<commit_msg>Update popularity-contest.js<commit_after>var filter_data = {
	all: {},
	per_lang: {
		fn: function(answer_id){
			return this[filter_data.all[answer_id]._meta.lang_text] == answer_id;
		}
	}
};

var renderAnswers = function(){

	var last_score = 0;
	var classification = 1;
	var invalid_index = 0;

	$table.html('
' +
		'
' +
			'	' +
			'Author	' +
			'Language	' +
			'Votes	' +
			' 	' +
		'
' +
	'
' +
	'
' +
		answers
			.sort(function(a, b){
				if(a.score != b.score)
				{
					return a.score - b.score;
				}
				return a.creation_date - b.creation_date;
			})
			.map(function(answer, index){

				if(index && last_score != answer.score)
				{
					classification = index + 1;
				}
				last_score = answer.score;

				return '
' +
					'' +
						(
							(
								HEURISTIC_INVALID_MARK && answer._meta.HEURISTIC_INVALID && answer._meta.HEURISTIC_INVALID_SCORE < -2
									? answer._meta.HEURISTIC_INVALID.map(function(comment){
										return ''
									})
									: ''
							) + ' ' + classification
						) +
					'	' +
					'' +
						'' +
							answer.owner.display_name +
						'' +
					'	' +
					'' +
						answer._meta.lang +
					'	' +
					'' +
						answer.score +
					'	' +
					'' +
						'View' +
					'	' +
				'
';
			}).join('') +
	'
');

	var $datatable = $table.DataTable({
		order: [],
		columnDefs: [
			{orderable: false, targets: 4},
			{searchable: false, targets: [0, 3, 4]},
			{type: 'html-num', targets: [0, 3]}
		]
	});

	var $filters = $('<select>').html(
		'<option value="all" selected="selected">All</option>' +
		'<option value="per_lang">Per Lang.</option>'
	).change(function(){
		$datatable.draw();
	});

	$('
')
		.css({'float': 'left'})
		.html(' Filter: </lavel>')
		.append($filters)
		.insertAfter('#DataTables_Table_0_length');

	//idea from http://stackoverflow.com/a/17539727/2729937
	$.fn.dataTable.ext.search.push(function(oSettings, aData, iDataIndex){
		var filter = $filters.val();

		if(filter == 'all')
		{
			return true;
		}

		var answer_id = oSettings.aoData[iDataIndex].nTr.getAttribute('data-answer_id');

		return filter_data[filter].fn(answer_id);
	});
}

var handleData = function(data){
	if(!data.length)
	{
		return;
	}
	var $span = $('');
	var answers = [];

	data.map(function(answer){
		$span.html(answer.body);
		var $h1 = $span.find(':first-child').get(0);
			console.log($h1);
			$h1.find('a').attr('target', '_blank');

		answer._meta = {
			lang: $h1.html(),
			lang_text: $h1.text().toLowerCase()
		};

		return answer;
	})
	.forEach(function(answer){

		filter_data.all[answer.answer_id] = answers[answers.length] = answer;

		if(HEURISTIC_INVALID_MARK && answer.comments && answer.comments.length)
		{
			analizeHeuristicValidity(answer);
		}

		if(filter_data.per_lang[answer._meta.lang_text])
		{
			var prev_answer = filter_data.all[filter_data.per_lang[answer._meta.lang_text]];

			if(prev_answer._meta.size == answer._meta.size)
			{
				filter_data.per_lang[answer._meta.lang_text] = prev_answer.creation_date > answer.creation_date
					? answer.answer_id
					: prev_answer.answer_id;
			}
			else if(prev_answer._meta.size > answer._meta.size)
			{
				filter_data.per_lang[answer._meta.lang_text] = answer.answer_id;
			}
		}
		else
		{
			filter_data.per_lang[answer._meta.lang_text] = answer.answer_id;
		}
	});

	setTimeout((function(){
		renderAnswers(this);
	}).bind(answers), 10);
};

handleData(answers);
<|endoftext|>


<commit_before>// Test the notebook dual mode feature.

// Test
casper.notebook_test(function () {
    var index = this.append_cell('print("a")');
    this.execute_cell_then(index);
    index = this.append_cell('print("b")');
    this.execute_cell_then(index);
    index = this.append_cell('print("c")');
    this.execute_cell_then(index);

    this.then(function () {
        this.validate_state('initial state', 'edit', 0);
        this.key_press('esc');
        this.validate_state('esc', 'command', 0);
        this.key_press('down');
        this.validate_state('down', 'command', 1);
        this.key_press('enter');
        this.validate_state('enter', 'edit', 1);
        this.key_press('j');
        this.validate_state('j in edit mode', 'edit', 1);
        this.key_press('esc');
        this.validate_state('esc', 'command', 1);
        this.key_press('j');
        this.validate_state('j in command mode', 'command', 2);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.key_press('esc');
        this.validate_state('esc', 'command', 3);

        // Open keyboard help
        this.evaluate(function(){
            $('#keyboard_shortcuts a').click();
        }, {});

        this.key_press('k');
        this.validate_state('k in command mode while keyboard help is up', 'command', 3);

        // Close keyboard help
        this.evaluate(function(){
            $('div.modal button.close').click();
        }, {});

        this.key_press('k');
        this.validate_state('k in command mode', 'command', 2);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.focus_notebook();
        this.validate_state('focus #notebook', 'command', 0);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.focus_notebook();
        this.validate_state('focus #notebook', 'command', 0);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.key_press('shift+enter');
        this.validate_state('shift+enter (no cell below)', 'edit', 4);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.key_press('shift+enter');
        this.validate_state('shift+enter (cell exists below)', 'command', 4);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.key_press('alt+enter');
        this.validate_state('alt+enter', 'edit', 4);
        this.key_press('ctrl+enter');
        this.validate_state('ctrl+enter', 'command', 4);
    });

    // Utility functions.
    this.validate_state = function(message, mode, cell_index) {
        // General tests.
        this.test.assertEquals(this._get_keyboard_mode(), this._get_notebook_mode(),
            message + '; keyboard and notebook modes match');
        // Is codemirror focused appropriately?
        this.test.assert(this.is_editor_focus_valid(), message + '; cell editor focused appropriately');
        // Is the selected cell the only cell that is selected?
        if (cell_index!==undefined) {
            this.test.assert(this.is_cell_selected(cell_index),
                message + '; cell ' + cell_index + ' is the only cell selected');
        }

        // Mode specific tests.
        if (mode==='command') {
            // Are the notebook and keyboard manager in command mode?
            this.test.assertEquals(this._get_keyboard_mode(), 'command',
                message + '; in command mode');
            // Make sure there isn't a single cell in edit mode.
            this.test.assert(this.is_cell_edit(null),
                message + '; all cells in command mode');

        } else if (mode==='edit') {
            // Are the notebook and keyboard manager in edit mode?
            this.test.assertEquals(this._get_keyboard_mode(), 'edit',
                message + '; in edit mode');
            // Is the specified cell the only cell in edit mode?
            if (cell_index!==undefined) {
                this.test.assert(this.is_cell_edit(cell_index),
                    message + '; cell ' + cell_index + ' is the only cell in edit mode');
            }

        } else {
            this.test.assert(false, message + '; ' + mode + ' is an unknown mode');
        }
    };

    this.is_editor_focus_valid = function() {
        var cells = this._get_cells();
        for (var i = 0; i < cells.length; i++) {
            if (!this.is_cell_editor_focus_valid(i)) {
                return false;
            }
        }
        return true;
    };

    this.is_cell_editor_focus_valid = function(i) {
        var cell = this._get_cell(i);
        if (cell) {
            if (cell.mode == 'edit') {
                return this._is_cell_editor_focused(i);
            } else {
                return !this._is_cell_editor_focused(i);
            }
        }
        return true;
    };

    this.is_cell_selected = function(i) {
        return this._is_cell_on(i, 'selected', 'unselected');
    };

    this.is_cell_edit = function(i) {
        return this._is_cell_on(i, 'edit_mode', 'command_mode');
    };

    this.click_cell = function(index) {
        // Code Mirror does not play nicely with emulated brower events.
        // Instead of trying to emulate a click, here we run code similar to
        // the code used in Code Mirror that handles the mousedown event on a
        // region of codemirror that the user can focus.
        this.evaluate(function (i) {
            cm = IPython.notebook.get_cell(i).code_mirror;
            if (cm.options.readOnly != "nocursor" && (document.activeElement != cm.display.input))
                cm.display.input.focus();
        }, {i: index});
    };

    this.focus_notebook = function() {
        this.evaluate(function (){
            $('#notebook').focus();
        }, {});
    };

    this.key_press = function(key) {
        this.evaluate(function (k) {
            IPython.keyboard.trigger_keydown(k);
        }, {k: key});
    };

    this._is_cell_editor_focused = function(i) {
        return this._is_cell_inputfield(i, '.CodeMirror-focused *');
    };

    this._is_cell_on = function(i, on_class, off_class) {
        var cells = this._get_cells();
        for (var j = 0; j < cells.length; j++) {
            if (j === i) {
                if (this._has_cell_class(j, off_class) || !this._has_cell_class(j, on_class)) {
                    return false;
                }
            } else {
                if (!this._has_cell_class(j, off_class) || this._has_cell_class(j, on_class)) {
                    return false;
                }
            }
        }
        return true;
    };

    this._get_keyboard_mode = function() {
        return this.evaluate(function() {
            return IPython.keyboard_manager.mode;
        }, {});
    };

    this._get_notebook_mode = function() {
        return this.evaluate(function() {
            return IPython.notebook.mode;
        }, {});
    };

    this._get_cells = function() {
        return this.evaluate(function() {
            return IPython.notebook.get_cells();
        }, {});
    };

    this._get_cell = function(index) {
        return this.evaluate(function(i) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return cell;
            }
            return null;
        }, {i : index});
    };

    this._is_cell_inputfield = function(index, selector) {
        return this.evaluate(function(i, s) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return $(cell.code_mirror.getInputField()).is(s);
            }
            return false;
        }, {i : index, s: selector});
    };

    this._has_cell_class = function(index, classes) {
        return this.evaluate(function(i, c) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return cell.element.hasClass(c);
            }
            return false;
        }, {i : index, c: classes});
    };
});
<commit_msg>s/key_press/trigger_keydown<commit_after>// Test the notebook dual mode feature.

// Test
casper.notebook_test(function () {
    var index = this.append_cell('print("a")');
    this.execute_cell_then(index);
    index = this.append_cell('print("b")');
    this.execute_cell_then(index);
    index = this.append_cell('print("c")');
    this.execute_cell_then(index);

    this.then(function () {
        this.validate_state('initial state', 'edit', 0);
        this.trigger_keydown('esc');
        this.validate_state('esc', 'command', 0);
        this.trigger_keydown('down');
        this.validate_state('down', 'command', 1);
        this.trigger_keydown('enter');
        this.validate_state('enter', 'edit', 1);
        this.trigger_keydown('j');
        this.validate_state('j in edit mode', 'edit', 1);
        this.trigger_keydown('esc');
        this.validate_state('esc', 'command', 1);
        this.trigger_keydown('j');
        this.validate_state('j in command mode', 'command', 2);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.trigger_keydown('esc');
        this.validate_state('esc', 'command', 3);

        // Open keyboard help
        this.evaluate(function(){
            $('#keyboard_shortcuts a').click();
        }, {});

        this.trigger_keydown('k');
        this.validate_state('k in command mode while keyboard help is up', 'command', 3);

        // Close keyboard help
        this.evaluate(function(){
            $('div.modal button.close').click();
        }, {});

        this.trigger_keydown('k');
        this.validate_state('k in command mode', 'command', 2);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.focus_notebook();
        this.validate_state('focus #notebook', 'command', 0);
        this.click_cell(0);
        this.validate_state('click cell 0', 'edit', 0);
        this.focus_notebook();
        this.validate_state('focus #notebook', 'command', 0);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.trigger_keydown('shift+enter');
        this.validate_state('shift+enter (no cell below)', 'edit', 4);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.trigger_keydown('shift+enter');
        this.validate_state('shift+enter (cell exists below)', 'command', 4);
        this.click_cell(3);
        this.validate_state('click cell 3', 'edit', 3);
        this.trigger_keydown('alt+enter');
        this.validate_state('alt+enter', 'edit', 4);
        this.trigger_keydown('ctrl+enter');
        this.validate_state('ctrl+enter', 'command', 4);
    });

    // Utility functions.
    this.validate_state = function(message, mode, cell_index) {
        // General tests.
        this.test.assertEquals(this._get_keyboard_mode(), this._get_notebook_mode(),
            message + '; keyboard and notebook modes match');
        // Is codemirror focused appropriately?
        this.test.assert(this.is_editor_focus_valid(), message + '; cell editor focused appropriately');
        // Is the selected cell the only cell that is selected?
        if (cell_index!==undefined) {
            this.test.assert(this.is_cell_selected(cell_index),
                message + '; cell ' + cell_index + ' is the only cell selected');
        }

        // Mode specific tests.
        if (mode==='command') {
            // Are the notebook and keyboard manager in command mode?
            this.test.assertEquals(this._get_keyboard_mode(), 'command',
                message + '; in command mode');
            // Make sure there isn't a single cell in edit mode.
            this.test.assert(this.is_cell_edit(null),
                message + '; all cells in command mode');

        } else if (mode==='edit') {
            // Are the notebook and keyboard manager in edit mode?
            this.test.assertEquals(this._get_keyboard_mode(), 'edit',
                message + '; in edit mode');
            // Is the specified cell the only cell in edit mode?
            if (cell_index!==undefined) {
                this.test.assert(this.is_cell_edit(cell_index),
                    message + '; cell ' + cell_index + ' is the only cell in edit mode');
            }

        } else {
            this.test.assert(false, message + '; ' + mode + ' is an unknown mode');
        }
    };

    this.is_editor_focus_valid = function() {
        var cells = this._get_cells();
        for (var i = 0; i < cells.length; i++) {
            if (!this.is_cell_editor_focus_valid(i)) {
                return false;
            }
        }
        return true;
    };

    this.is_cell_editor_focus_valid = function(i) {
        var cell = this._get_cell(i);
        if (cell) {
            if (cell.mode == 'edit') {
                return this._is_cell_editor_focused(i);
            } else {
                return !this._is_cell_editor_focused(i);
            }
        }
        return true;
    };

    this.is_cell_selected = function(i) {
        return this._is_cell_on(i, 'selected', 'unselected');
    };

    this.is_cell_edit = function(i) {
        return this._is_cell_on(i, 'edit_mode', 'command_mode');
    };

    this.click_cell = function(index) {
        // Code Mirror does not play nicely with emulated brower events.
        // Instead of trying to emulate a click, here we run code similar to
        // the code used in Code Mirror that handles the mousedown event on a
        // region of codemirror that the user can focus.
        this.evaluate(function (i) {
            cm = IPython.notebook.get_cell(i).code_mirror;
            if (cm.options.readOnly != "nocursor" && (document.activeElement != cm.display.input))
                cm.display.input.focus();
        }, {i: index});
    };

    this.focus_notebook = function() {
        this.evaluate(function (){
            $('#notebook').focus();
        }, {});
    };

    this.trigger_keydown = function(key) {
        this.evaluate(function (k) {
            IPython.keyboard.trigger_keydown(k);
        }, {k: key});
    };

    this._is_cell_editor_focused = function(i) {
        return this._is_cell_inputfield(i, '.CodeMirror-focused *');
    };

    this._is_cell_on = function(i, on_class, off_class) {
        var cells = this._get_cells();
        for (var j = 0; j < cells.length; j++) {
            if (j === i) {
                if (this._has_cell_class(j, off_class) || !this._has_cell_class(j, on_class)) {
                    return false;
                }
            } else {
                if (!this._has_cell_class(j, off_class) || this._has_cell_class(j, on_class)) {
                    return false;
                }
            }
        }
        return true;
    };

    this._get_keyboard_mode = function() {
        return this.evaluate(function() {
            return IPython.keyboard_manager.mode;
        }, {});
    };

    this._get_notebook_mode = function() {
        return this.evaluate(function() {
            return IPython.notebook.mode;
        }, {});
    };

    this._get_cells = function() {
        return this.evaluate(function() {
            return IPython.notebook.get_cells();
        }, {});
    };

    this._get_cell = function(index) {
        return this.evaluate(function(i) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return cell;
            }
            return null;
        }, {i : index});
    };

    this._is_cell_inputfield = function(index, selector) {
        return this.evaluate(function(i, s) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return $(cell.code_mirror.getInputField()).is(s);
            }
            return false;
        }, {i : index, s: selector});
    };

    this._has_cell_class = function(index, classes) {
        return this.evaluate(function(i, c) {
            var cell = IPython.notebook.get_cell(i);
            if (cell) {
                return cell.element.hasClass(c);
            }
            return false;
        }, {i : index, c: classes});
    };
});
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/*
 * NB: browser-only tests
 */

/*jshint expr: true */
/*global describe, it */

var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;

var $ = window.$;
var preprocess = window.tideline.preprocess;
var blip = window.tideline.blip;
var chartDailyFactory = blip.oneday;

var el = document.getElementById('tidelineContainer');
var imagesBaseUrl = '../../img';

var oneDay = chartDailyFactory(el, {imagesBaseUrl: imagesBaseUrl}).setupPools();
var data = require('./testpage');
data = preprocess.processData(data);

var tideline = require('../../js/index');
var containerId = '#tidelineContainer';

describe('the tideline container', function() {
  it('should have a width of 1200px', function() {
    expect($(containerId).width()).to.equal(1200);
  });

  it('should have a height of 800px', function() {
    expect($(containerId).height()).to.equal(800);
  });
});

describe('one-day view', function() {

  it('should exist', function() {
    oneDay.load(data).locate();
  });
});<commit_msg>start on visualizing unit testing: cbg data, including tooltips<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/*
 * NB: browser-only tests
 */

/*jshint expr: true */
/*global describe, it, before, after, beforeEach, afterEach */

var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;

var $ = window.$;
var d3 = window.d3;
var preprocess = window.tideline.preprocess;
var blip = window.tideline.blip;
var chartDailyFactory = blip.oneday;

var imagesBaseUrl = '../../img';

var testpage = require('../../dev/testpage/index');

var tideline = require('../../js/index');
var containerId = '#testContainer';

describe('the tideline container', function(done) {
  // this set of tests isn't really testing anything...EXCEPT
  // we're using the dimensions of the container to test some other things below
  // so these tests are basically canaries to help us debug potentially breaking tests
  before(function() {
    $(containerId).append('

');
  });

  it('should have a width of 960px', function() {
    expect($('.tideline-container').width()).to.equal(960);
  });

  it('should have a height of 590px', function() {
    expect($('.tideline-container').height()).to.equal(590);
  });

  after(function() {
    $(containerId).empty();
  });
});

describe('one-day view', function() {
  var i = 0, testPatterns = testpage.main;

  describe('full day of data', function() {
    var container, oneDay;

    before(function() {
      $(containerId).append('

');
      var el = document.getElementById('tideline_' + i);
      oneDay = chartDailyFactory(el, {imagesBaseUrl: imagesBaseUrl}).setupPools();
      var data = preprocess.processData(testPatterns.full());
      oneDay.load(data).locate();
      container = $('#tideline_' + i);
      i++;
    });

    describe('cbg data', function() {
      it('should display cbgs with radius 2.5', function() {
        expect(parseFloat(container.find('.d3-circle-cbg').attr('r'),10)).to.equal(2.5);
      });

      it('should display 289 cbgs with color #FF8B7C, when seed is 79 mg/dL', function() {
        var these = container.find('.d3-circle-cbg.d3-bg-low');
        expect(these.length).to.equal(289);
        expect(d3.rgb(these.css('fill')).toString()).to.equal('#FF8B7C'.toLowerCase());
      });

      it('should display 289 cbgs with color #9AD859, when seed is 100 mg/dL', function() {
        var these = container.find('.d3-circle-cbg.d3-bg-target');
        expect(these.length).to.equal(289);
        expect(d3.rgb(these.css('fill')).toString()).to.equal('#9AD859'.toLowerCase());
      });

      it('should display 289 cbgs with color #BB9AE7, when seed is 181 mg/dL', function() {
        var these = container.find('.d3-circle-cbg.d3-bg-high');
        expect(these.length).to.equal(289);
        expect(d3.rgb(these.css('fill')).toString()).to.equal('#BB9AE7'.toLowerCase());
      });

      describe('left edge cbg elements', function() {
        var leftLow, leftTarget, leftHigh;

        it('should have an x value at the axis gutter', function() {
          leftLow = container.find('.d3-circle-cbg.d3-bg-low').filter(':first');
          leftTarget = container.find('.d3-circle-cbg.d3-bg-target').filter(':first');
          leftHigh = container.find('.d3-circle-cbg.d3-bg-high').filter(':first');
          expect(parseInt(leftLow.attr('cx'), 10)).to.equal(oneDay.axisGutter());
          expect(parseInt(leftTarget.attr('cx'), 10)).to.equal(oneDay.axisGutter());
          expect(parseInt(leftHigh.attr('cx'), 10)).to.equal(oneDay.axisGutter());
        });

        it('(low and target) should offer a right and up tooltip (text = 60, 110) on hover', function() {
          leftLow.simulate('mouseover');
          var lowTooltipGroup = container.find('#tooltip_' + leftLow.attr('id').replace('cbg_', ''));
          expect(lowTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_low.svg');
          expect(lowTooltipGroup.find('text').html()).to.equal('60');
          leftTarget.simulate('mouseover');
          var targetTooltipGroup = container.find('#tooltip_' + leftTarget.attr('id').replace('cbg_', ''));
          expect(targetTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_target.svg');
          expect(targetTooltipGroup.find('text').html()).to.equal('110');
        });

        it('(high) should offer a right and down tooltip (text = 300) on hover', function() {
          leftHigh.simulate('mouseover');
          var highTooltipGroup = container.find('#tooltip_' + leftHigh.attr('id').replace('cbg_', ''));
          expect(highTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_high.svg');
          expect(highTooltipGroup.find('text').html()).to.equal('300');
        });
      });

      describe('right edge cbg elements', function() {
        var rightLow, rightTarget, rightHigh;

        it('should have an x value at the right edge', function() {
          rightLow = container.find('.d3-circle-cbg.d3-bg-low').filter(':last');
          rightTarget = container.find('.d3-circle-cbg.d3-bg-target').filter(':last');
          rightHigh = container.find('.d3-circle-cbg.d3-bg-high').filter(':last');
          expect(parseInt(rightLow.attr('cx'), 10)).to.equal(960);
          expect(parseInt(rightTarget.attr('cx'), 10)).to.equal(960);
          expect(parseInt(rightHigh.attr('cx'), 10)).to.equal(960);
        });

        it('(low and target) should offer a left and up tooltip (text = 60, 110) on hover', function() {
          rightLow.simulate('mouseover');
          var lowTooltipGroup = container.find('#tooltip_' + rightLow.attr('id').replace('cbg_', ''));
          expect(lowTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_low_left.svg');
          expect(lowTooltipGroup.find('text').html()).to.equal('60');
          rightTarget.simulate('mouseover');
          var targetTooltipGroup = container.find('#tooltip_' + rightTarget.attr('id').replace('cbg_', ''));
          expect(targetTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_target_left.svg');
          expect(targetTooltipGroup.find('text').html()).to.equal('110');
        });

        it('(high) should offer a left and down tooltip (text = 300) on hover', function() {
          rightHigh.simulate('mouseover');
          var highTooltipGroup = container.find('#tooltip_' + rightHigh.attr('id').replace('cbg_', ''));
          expect(highTooltipGroup.find('image').attr('href')).to.equal('../../img/cbg/cbg_tooltip_high_left.svg');
          expect(highTooltipGroup.find('text').html()).to.equal('300');
        });
      });
    });
  });
});<|endoftext|>


<commit_before>{% load i18n %}
{% load status_codes %}

{% include "status_codes.html" with label='stock' options=StockStatus.list %}
{% include "status_codes.html" with label='build' options=BuildStatus.list %}
{% include "status_codes.html" with label='purchaseOrder' options=PurchaseOrderStatus.list %}
{% include "status_codes.html" with label='salesOrder' options=SalesOrderStatus.list %}

function getAvailableTableFilters(tableKey) {

    tableKey = tableKey.toLowerCase();

    // Filters for "variant" table
    if (tableKey == "variants") {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
            template: {
                type: 'bool',
                title: '{% trans "Template" %}',
            },
            virtual: {
                type: 'bool',
                title: '{% trans "Virtual" %}',
            },
            trackable: {
                type: 'bool',
                title: '{% trans "Trackable" %}',
            },
        };
    }

    // Filters for Bill of Materials table
    if (tableKey == "bom") {
        return {
            sub_part_trackable: {
                type: 'bool',
                title: '{% trans "Trackable Part" %}'
            },
            validated: {
                type: 'bool',
                title: '{% trans "Validated" %}',
            },
        };
    }

    // Filters for the "used in" table
    if (tableKey == 'usedin') {
        return {
            'part_active': {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
        };
    }

    // Filters for the "customer stock" table (really a subset of "stock")
    if (tableKey == "customerstock") {
        return {
            serialized: {
                type: 'bool',
                title: '{% trans "Is Serialized" %}',
            },
            serial_gte: {
                title: '{% trans "Serial number GTE" %}',
                description: '{% trans "Serial number greater than or equal to" %}'
            },
            serial_lte: {
                title: '{% trans "Serial number LTE" %}',
                description: '{% trans "Serial number less than or equal to" %}',
            },
            serial: {
                title: '{% trans "Serial number" %}',
                description: '{% trans "Serial number" %}'
            },
            batch: {
                title: '{% trans "Batch" %}',
                description: '{% trans "Batch code" %}',
            },
        };
    }

    // Filters for the "Stock" table
    if (tableKey == 'stock') {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active parts" %}',
                description: '{% trans "Show stock for active parts" %}',
            },
            allocated: {
                type: 'bool',
                title: '{% trans "Is allocated" %}',
                description: '{% trans "Item has been alloacted" %}',
            },
            cascade: {
                type: 'bool',
                title: '{% trans "Include sublocations" %}',
                description: '{% trans "Include stock in sublocations" %}',
            },
            depleted: {
                type: 'bool',
                title: '{% trans "Depleted" %}',
                description: '{% trans "Show stock items which are depleted" %}',
            },
            in_stock: {
                type: 'bool',
                title: '{% trans "In Stock" %}',
                description: '{% trans "Show items which are in stock" %}',
            },
            is_building: {
                type: 'bool',
                title: '{% trans "In Production" %}',
                description: '{% trans "Show items which are in production" %}',
            },
            installed: {
                type: 'bool',
                title: '{% trans "Installed" %}',
                description: '{% trans "Show stock items which are installed in another item" %}',
            },
            sent_to_customer: {
                type: 'bool',
                title: '{% trans "Sent to customer" %}',
                description: '{% trans "Show items which have been assigned to a customer" %}',
            },
            serialized: {
                type: 'bool',
                title: '{% trans "Is Serialized" %}',
            },
            serial: {
                title: '{% trans "Serial number" %}',
                description: '{% trans "Serial number" %}'
            },
            serial_gte: {
                title: '{% trans "Serial number GTE" %}',
                description: '{% trans "Serial number greater than or equal to" %}'
            },
            serial_lte: {
                title: '{% trans "Serial number LTE" %}',
                description: '{% trans "Serial number less than or equal to" %}',
            },
            status: {
                options: stockCodes,
                title: '{% trans "Stock status" %}',
                description: '{% trans "Stock status" %}',
            },
            batch: {
                title: '{% trans "Batch" %}',
                description: '{% trans "Batch code" %}',
            }
        };
    }

    // Filters for the 'stock test' table
    if (tableKey == 'stocktests') {
        return {
            result: {
                type: 'bool',
                title: '{% trans "Test result" %}',
            },
        };
    }

    // Filters for the 'part test template' table
    if (tableKey == 'parttests') {
        return {
            required: {
                type: 'bool',
                title: '{% trans "Required" %}',
            }
        };
    }

    // Filters for the "Build" table
    if (tableKey == 'build') {
        return {
            status: {
                title: '{% trans "Build status" %}',
                options: buildCodes,
            },
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
            overdue: {
                type: 'bool',
                title: '{% trans "Overdue" %}',
            },
        };
    }

    // Filters for the "Order" table
    if (tableKey == "purchaseorder") {

        return {
            status: {
                title: '{% trans "Order status" %}',
                options: purchaseOrderCodes,
            },
            outstanding: {
                type: 'bool',
                title: '{% trans "Outstanding" %}',
            },
        };
    }

    if (tableKey == "salesorder") {
        return {
            status: {
                title: '{% trans "Order status" %}',
                options: salesOrderCodes,
            },
            outstanding: {
                type: 'bool',
                title: '{% trans "Outstanding" %}',
            },
        };
    }

    if (tableKey == 'supplier-part') {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active parts" %}',
            }
        };
    }

    // Filters for the "Parts" table
    if (tableKey == "parts") {
        return {
            cascade: {
                type: 'bool',
                title: '{% trans "Include subcategories" %}',
                description: '{% trans "Include parts in subcategories" %}',
            },
            has_ipn: {
                type: 'bool',
                title: '{% trans "Has IPN" %}',
                description: '{% trans "Part has internal part number" %}',
            },
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
                description: '{% trans "Show active parts" %}',
            },
            is_template: {
                type: 'bool',
                title: '{% trans "Template" %}',
            },
            has_stock: {
                type: 'bool',
                title: '{% trans "Stock available" %}'
            },
            low_stock: {
                type: 'bool',
                title: '{% trans "Low stock" %}',
            },
            assembly: {
                type: 'bool',
                title: '{% trans "Assembly" %}',
            },
            component: {
                type: 'bool',
                title: '{% trans "Component" %}',
            },
            starred: {
                type: 'bool',
                title: '{% trans "Starred" %}',
            },
            salable: {
                type: 'bool',
                title: '{% trans "Salable" %}',
            },
            trackable: {
                type: 'bool',
                title: '{% trans "Trackable" %}',
            },
            purchaseable: {
                type: 'bool',
                title: '{% trans "Purchasable" %}',
            },
        };
    }

    // Finally, no matching key
    return {};
}
<commit_msg>Add overdue filter for salesorder table<commit_after>{% load i18n %}
{% load status_codes %}

{% include "status_codes.html" with label='stock' options=StockStatus.list %}
{% include "status_codes.html" with label='build' options=BuildStatus.list %}
{% include "status_codes.html" with label='purchaseOrder' options=PurchaseOrderStatus.list %}
{% include "status_codes.html" with label='salesOrder' options=SalesOrderStatus.list %}

function getAvailableTableFilters(tableKey) {

    tableKey = tableKey.toLowerCase();

    // Filters for "variant" table
    if (tableKey == "variants") {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
            template: {
                type: 'bool',
                title: '{% trans "Template" %}',
            },
            virtual: {
                type: 'bool',
                title: '{% trans "Virtual" %}',
            },
            trackable: {
                type: 'bool',
                title: '{% trans "Trackable" %}',
            },
        };
    }

    // Filters for Bill of Materials table
    if (tableKey == "bom") {
        return {
            sub_part_trackable: {
                type: 'bool',
                title: '{% trans "Trackable Part" %}'
            },
            validated: {
                type: 'bool',
                title: '{% trans "Validated" %}',
            },
        };
    }

    // Filters for the "used in" table
    if (tableKey == 'usedin') {
        return {
            'part_active': {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
        };
    }

    // Filters for the "customer stock" table (really a subset of "stock")
    if (tableKey == "customerstock") {
        return {
            serialized: {
                type: 'bool',
                title: '{% trans "Is Serialized" %}',
            },
            serial_gte: {
                title: '{% trans "Serial number GTE" %}',
                description: '{% trans "Serial number greater than or equal to" %}'
            },
            serial_lte: {
                title: '{% trans "Serial number LTE" %}',
                description: '{% trans "Serial number less than or equal to" %}',
            },
            serial: {
                title: '{% trans "Serial number" %}',
                description: '{% trans "Serial number" %}'
            },
            batch: {
                title: '{% trans "Batch" %}',
                description: '{% trans "Batch code" %}',
            },
        };
    }

    // Filters for the "Stock" table
    if (tableKey == 'stock') {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active parts" %}',
                description: '{% trans "Show stock for active parts" %}',
            },
            allocated: {
                type: 'bool',
                title: '{% trans "Is allocated" %}',
                description: '{% trans "Item has been alloacted" %}',
            },
            cascade: {
                type: 'bool',
                title: '{% trans "Include sublocations" %}',
                description: '{% trans "Include stock in sublocations" %}',
            },
            depleted: {
                type: 'bool',
                title: '{% trans "Depleted" %}',
                description: '{% trans "Show stock items which are depleted" %}',
            },
            in_stock: {
                type: 'bool',
                title: '{% trans "In Stock" %}',
                description: '{% trans "Show items which are in stock" %}',
            },
            is_building: {
                type: 'bool',
                title: '{% trans "In Production" %}',
                description: '{% trans "Show items which are in production" %}',
            },
            installed: {
                type: 'bool',
                title: '{% trans "Installed" %}',
                description: '{% trans "Show stock items which are installed in another item" %}',
            },
            sent_to_customer: {
                type: 'bool',
                title: '{% trans "Sent to customer" %}',
                description: '{% trans "Show items which have been assigned to a customer" %}',
            },
            serialized: {
                type: 'bool',
                title: '{% trans "Is Serialized" %}',
            },
            serial: {
                title: '{% trans "Serial number" %}',
                description: '{% trans "Serial number" %}'
            },
            serial_gte: {
                title: '{% trans "Serial number GTE" %}',
                description: '{% trans "Serial number greater than or equal to" %}'
            },
            serial_lte: {
                title: '{% trans "Serial number LTE" %}',
                description: '{% trans "Serial number less than or equal to" %}',
            },
            status: {
                options: stockCodes,
                title: '{% trans "Stock status" %}',
                description: '{% trans "Stock status" %}',
            },
            batch: {
                title: '{% trans "Batch" %}',
                description: '{% trans "Batch code" %}',
            }
        };
    }

    // Filters for the 'stock test' table
    if (tableKey == 'stocktests') {
        return {
            result: {
                type: 'bool',
                title: '{% trans "Test result" %}',
            },
        };
    }

    // Filters for the 'part test template' table
    if (tableKey == 'parttests') {
        return {
            required: {
                type: 'bool',
                title: '{% trans "Required" %}',
            }
        };
    }

    // Filters for the "Build" table
    if (tableKey == 'build') {
        return {
            status: {
                title: '{% trans "Build status" %}',
                options: buildCodes,
            },
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
            },
            overdue: {
                type: 'bool',
                title: '{% trans "Overdue" %}',
            },
        };
    }

    // Filters for the "Order" table
    if (tableKey == "purchaseorder") {

        return {
            status: {
                title: '{% trans "Order status" %}',
                options: purchaseOrderCodes,
            },
            outstanding: {
                type: 'bool',
                title: '{% trans "Outstanding" %}',
            },
        };
    }

    if (tableKey == "salesorder") {
        return {
            status: {
                title: '{% trans "Order status" %}',
                options: salesOrderCodes,
            },
            outstanding: {
                type: 'bool',
                title: '{% trans "Outstanding" %}',
            },
            overdue: {
                type: 'bool',
                title: '{% trans "Overdue" %}',
            },
        };
    }

    if (tableKey == 'supplier-part') {
        return {
            active: {
                type: 'bool',
                title: '{% trans "Active parts" %}',
            }
        };
    }

    // Filters for the "Parts" table
    if (tableKey == "parts") {
        return {
            cascade: {
                type: 'bool',
                title: '{% trans "Include subcategories" %}',
                description: '{% trans "Include parts in subcategories" %}',
            },
            has_ipn: {
                type: 'bool',
                title: '{% trans "Has IPN" %}',
                description: '{% trans "Part has internal part number" %}',
            },
            active: {
                type: 'bool',
                title: '{% trans "Active" %}',
                description: '{% trans "Show active parts" %}',
            },
            is_template: {
                type: 'bool',
                title: '{% trans "Template" %}',
            },
            has_stock: {
                type: 'bool',
                title: '{% trans "Stock available" %}'
            },
            low_stock: {
                type: 'bool',
                title: '{% trans "Low stock" %}',
            },
            assembly: {
                type: 'bool',
                title: '{% trans "Assembly" %}',
            },
            component: {
                type: 'bool',
                title: '{% trans "Component" %}',
            },
            starred: {
                type: 'bool',
                title: '{% trans "Starred" %}',
            },
            salable: {
                type: 'bool',
                title: '{% trans "Salable" %}',
            },
            trackable: {
                type: 'bool',
                title: '{% trans "Trackable" %}',
            },
            purchaseable: {
                type: 'bool',
                title: '{% trans "Purchasable" %}',
            },
        };
    }

    // Finally, no matching key
    return {};
}
<|endoftext|>


<commit_before>'use strict';

    // Task related
var name = 'manage-assets',

    // Project & path related
    project         = require('../project'),

    // Asset related tasks
    image_assets    = require('./manage-image.task'),
    style_assets    = require('./manage-style.task'),
    script_assets   = require('./manage-script.task'),
    markup_assets   = require('./manage-markup.task'),

    // Gulp related
    Task        = require('./helpers/task.helper'),
    gulp        = require('gulp'),
    sequence    = require('run-sequence');

module.exports = {
    compile: new Task(
        name+':compile',
        function() {
            sequence(
                image_assets.compile.getName(),
                style_assets.compile.getName(),
                script_assets.compile.getName(),
                markup_assets.compile.getName()
            );
        }
    ),
    cleanup: new Task(
        name+':cleanup',
        function() {
            sequence(
                image_assets.cleanup.getName(),
                style_assets.cleanup.getName(),
                script_assets.cleanup.getName(),
                markup_assets.cleanup.getName()
            );
        }
    )
};
<commit_msg>Add assemble task to manage-assets task<commit_after>'use strict';

    // Task related
var name = 'manage-assets',

    // Project & path related
    project         = require('../project'),
    root            = project.path.root,

    // Asset related tasks
    image_assets    = require('./manage-image.task'),
    style_assets    = require('./manage-style.task'),
    script_assets   = require('./manage-script.task'),
    markup_assets   = require('./manage-markup.task'),

    // Gulp related
    Task        = require('./helpers/task.helper'),
    gulp        = require('gulp'),
    sequence    = require('run-sequence');

module.exports = {
    cleanup: new Task(
        name+':cleanup',
        function() {
            sequence(
                image_assets.cleanup.getName(),
                style_assets.cleanup.getName(),
                script_assets.cleanup.getName(),
                markup_assets.cleanup.getName()
            );
        }
    ),
    compile: new Task(
        name+':compile',
        function() {
            sequence(
                image_assets.compile.getName(),
                style_assets.compile.getName(),
                script_assets.compile.getName(),
                markup_assets.compile.getName()
            );
        }
    ),
    assemble: new Task(
        name+':assemble',
        function() {
            sequence(
                image_assets.assemble.getName(),
                style_assets.assemble.getName(),
                script_assets.assemble.getName(),
                markup_assets.assemble.getName()
            );
        }
    )
};
<|endoftext|>


<commit_before>var
  sys = require("sys"),
  jefe = new require("../lib/jefe"),
  elJefe = new jefe.Jefe(),
  scriptName = "while forever loop should not run forever";

elJefe.compile(scriptName, "while (true) {}", { maxTime: 5000 } );

elJefe.run(scriptName, {}, function (error, sandboxIn, sandboxOut) {
  if (error) {
    sys.puts("error = " + error);
  } else {
    sys.puts("completed without error");
    sys.puts("sandboxOut = " + JSON.stringify(sandboxOut));
  }

  var stats = elJefe.getScriptStats(scriptName);
  sys.p(stats);

  process.exit(0);
});

<commit_msg>while (true) {} example<commit_after>var
  sys = require("sys"),
  jefe = new require("../lib/jefe"),
  elJefe = new jefe.Jefe(),
  scriptName = "while forever loop should not run forever";

elJefe.compile(scriptName, "while (true) {}", { maxTime: 5000 } );

sys.error("this will wait up to 5s ...");

elJefe.run(scriptName, {}, function (error, sandboxIn, sandboxOut) {
  if (error) {
    sys.puts("error = " + error);
  } else {
    sys.puts("completed without error");
    sys.puts("sandboxOut = " + JSON.stringify(sandboxOut));
  }

  var stats = elJefe.getScriptStats(scriptName);
  sys.p(stats);

  process.exit(0);
});

<|endoftext|>


<commit_before>// @flow
import State from '../parser/state'
import { has } from '../utils'
import { types as tt, keywords, type TokenType } from '../tokenizer/types'

const isNumber = (code: number) => code >= 48 && code <= 57
const isLetter = (code: number) => (
	code >= 65 && code <= 90
	|| code >= 97 && code <= 122
)

export default class Tokenizer {
	// forward declarations: parser/util.js
	+expect: (type: TokenType) => void
	+unexpected: () => void
	state: State

	constructor() {
		this.state = new State()
	}

	expectNext(type: TokenType) {
		this.next()
		this.expect(type)
	}

	// getting the next item, but if next is called again then it will the lookahead
	// NOTE: use with caution, it will affect state to next token
	lookaheadFor(type: (TokenType) => bool) {
		this.next()
		if (type(this.state.type)) {
			return true
		}
		this.state.lookahead = true
		return false
	}

	next(): void {
		if (this.state.lookahead) {
			this.state.lookahead = false
			return
		}
		this.state.prevStart = this.state.start
		this.state.prevEnd = this.state.end
		this.nextToken()
	}

	match(type: TokenType) {
		return this.state.type === type
	}

	eat(type: TokenType) {
		if (this.match(type)) {
			this.next()
			return true
		}
		return false
	}

	nextToken(): void {
		this.skipSpace()
		const code = this.state.input.charCodeAt(this.state.pos)

		this.state.start = this.state.pos
		if (this.state.pos >= this.state.input.length) {
			return this.finishToken(tt.eof)
		}
		if (isNumber(code) || code === 46 /* . */) {
			return this.readNumber()
		}
		if (isLetter(code)) {
			return this.readIdentifier()
		}
		return this.getTokenFromCode(code)
	}

	getTokenFromCode(code: number): void {
		this.state.pos += 1

		switch (code) {
			case 43: // '+'
				return this.finishToken(tt.plus, '+')
			case 45: // '-'
				return this.finishToken(tt.minus, '-')
			case 42: // '*'
				return this.finishToken(tt.star, '*')
			case 47: // '/'
				return this.finishToken(tt.slash, '/')
			case 37: // '%'
				return this.finishToken(tt.modulo, '%')
			case 94: // '^'
				return this.finishToken(tt.exponent, '^')
			case 33: // '!'
				return this.finishToken(tt.bang, '!')
			case 61: // '='
				return this.finishToken(tt.eq, '=')
			case 44: // ','
				return this.finishToken(tt.comma)
			case 40: // '('
				return this.finishToken(tt.parenL)
			case 41: // ')'
				return this.finishToken(tt.parenR)
			case 124: // '|'
				return this.finishToken(tt.crotchet)
			case 59: // ';'
				return this.finishToken(tt.semi)
			default:
				this.finishWithValue(tt.error)
				return this.unexpected()
		}
	}

	readNumber() {
		const { state } = this
		let toBreak = false
		let hasDot = false

		while (!toBreak) {
			const code = state.input.charCodeAt(state.pos)
			if (isNumber(code)) {
				this.state.pos += 1
			} else if (code === 46 /* '.' */ && !hasDot) {
				this.state.pos += 1
				hasDot = true
			} else {
				toBreak = true
			}
		}

		this.finishWithValue(tt.num)
	}

	readIdentifier() {
		const { state } = this
		while (isLetter(state.input.charCodeAt(state.pos))) {
			state.pos += 1
		}

		const word = state.input.slice(state.start, state.pos)
		if (has(keywords, word)) {
			this.finishToken(keywords[word], word)
		} else {
			this.finishToken(tt.name, word)
		}
	}

	skipSpace() {
		const { state } = this
		let cur = state.input.charCodeAt(state.pos)
		let padding = 0

		while (cur === 32 /* ' ' */ || cur === 10 /* '\n' */ || cur === 9 /* '\t' */) {
			padding += 1
			cur = state.input.charCodeAt(state.pos + padding)
		}
		state.prevSpacePadding = padding
		state.pos += padding
	}

	finishWithValue(type: TokenType) {
		this.finishToken(
			type,
			this.state.input.slice(this.state.start, this.state.pos),
		)
	}

	finishToken(type: TokenType, value?: any) {
		this.state.value = value
		this.state.prevType = this.state.type
		this.state.type = type
		this.state.end = this.state.pos
	}
}
<commit_msg>better declaration of state<commit_after>// @flow
import State from '../parser/state'
import { has } from '../utils'
import { types as tt, keywords, type TokenType } from '../tokenizer/types'

const isNumber = (code: number) => code >= 48 && code <= 57
const isLetter = (code: number) => (
	code >= 65 && code <= 90
	|| code >= 97 && code <= 122
)

export default class Tokenizer {
	// forward declarations: parser/util.js
	+expect: (type: TokenType) => void
	+unexpected: () => void
	state: State = new State()

	expectNext(type: TokenType) {
		this.next()
		this.expect(type)
	}

	// getting the next item, but if next is called again then it will the lookahead
	// NOTE: use with caution, it will affect state to next token
	lookaheadFor(type: (TokenType) => bool) {
		this.next()
		if (type(this.state.type)) {
			return true
		}
		this.state.lookahead = true
		return false
	}

	next(): void {
		if (this.state.lookahead) {
			this.state.lookahead = false
			return
		}
		this.state.prevStart = this.state.start
		this.state.prevEnd = this.state.end
		this.nextToken()
	}

	match(type: TokenType) {
		return this.state.type === type
	}

	eat(type: TokenType) {
		if (this.match(type)) {
			this.next()
			return true
		}
		return false
	}

	nextToken(): void {
		this.skipSpace()
		const code = this.state.input.charCodeAt(this.state.pos)

		this.state.start = this.state.pos
		if (this.state.pos >= this.state.input.length) {
			return this.finishToken(tt.eof)
		}
		if (isNumber(code) || code === 46 /* . */) {
			return this.readNumber()
		}
		if (isLetter(code)) {
			return this.readIdentifier()
		}
		return this.getTokenFromCode(code)
	}

	getTokenFromCode(code: number): void {
		this.state.pos += 1

		switch (code) {
			case 43: // '+'
				return this.finishToken(tt.plus, '+')
			case 45: // '-'
				return this.finishToken(tt.minus, '-')
			case 42: // '*'
				return this.finishToken(tt.star, '*')
			case 47: // '/'
				return this.finishToken(tt.slash, '/')
			case 37: // '%'
				return this.finishToken(tt.modulo, '%')
			case 94: // '^'
				return this.finishToken(tt.exponent, '^')
			case 33: // '!'
				return this.finishToken(tt.bang, '!')
			case 61: // '='
				return this.finishToken(tt.eq, '=')
			case 44: // ','
				return this.finishToken(tt.comma)
			case 40: // '('
				return this.finishToken(tt.parenL)
			case 41: // ')'
				return this.finishToken(tt.parenR)
			case 124: // '|'
				return this.finishToken(tt.crotchet)
			case 59: // ';'
				return this.finishToken(tt.semi)
			default:
				this.finishWithValue(tt.error)
				return this.unexpected()
		}
	}

	readNumber() {
		const { state } = this
		let toBreak = false
		let hasDot = false

		while (!toBreak) {
			const code = state.input.charCodeAt(state.pos)
			if (isNumber(code)) {
				this.state.pos += 1
			} else if (code === 46 /* '.' */ && !hasDot) {
				this.state.pos += 1
				hasDot = true
			} else {
				toBreak = true
			}
		}

		this.finishWithValue(tt.num)
	}

	readIdentifier() {
		const { state } = this
		while (isLetter(state.input.charCodeAt(state.pos))) {
			state.pos += 1
		}

		const word = state.input.slice(state.start, state.pos)
		if (has(keywords, word)) {
			this.finishToken(keywords[word], word)
		} else {
			this.finishToken(tt.name, word)
		}
	}

	skipSpace() {
		const { state } = this
		let cur = state.input.charCodeAt(state.pos)
		let padding = 0

		while (cur === 32 /* ' ' */ || cur === 10 /* '\n' */ || cur === 9 /* '\t' */) {
			padding += 1
			cur = state.input.charCodeAt(state.pos + padding)
		}
		state.prevSpacePadding = padding
		state.pos += padding
	}

	finishWithValue(type: TokenType) {
		this.finishToken(
			type,
			this.state.input.slice(this.state.start, this.state.pos),
		)
	}

	finishToken(type: TokenType, value?: any) {
		this.state.value = value
		this.state.prevType = this.state.type
		this.state.type = type
		this.state.end = this.state.pos
	}
}
<|endoftext|>


<commit_before>javascript:(function(){
  $('li').each(function() {
    var fingerprint = $(this).attr('data-fingerprint');
    if(fingerprint != undefined) {
      var colorString = fingerprint.substring(0,6);
      var height = (document.URL.indexOf('face') === -1) ? "101px;" : "30px";
      $(this).append('

');
    }
  });
})();
<commit_msg>Always know who that meat is<commit_after>javascript:(function(){
  var whoaremeat = function() {
    element = $(this);
    var fingerprint = element.attr('data-fingerprint');
    if(fingerprint != undefined) {
      var colorString = fingerprint.substring(0,6);
      var height = (document.URL.indexOf('face') === -1) ? "101px;" : "30px";
      element.append('

');
    }
  };

  $('#chat-list').on("DOMNodeInserted", function(event) {
    event.target.nodeName == 'LI' && whoaremeat.bind(event.target)();
  }).find('li').each(whoaremeat);
})();
<|endoftext|>


<commit_before>// Load the http module to create an http server.
var express = require('express');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var firebase = require('firebase');
var _ = require('lodash');
var config = require('../node-server/helpers/config');
var command = require('./command.js');
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
// var server = http.createServer(function (request, response) {
//   response.writeHead(200, {"Content-Type": "text/plain"});
//   response.end("Hello World\n");
// });

var sms = function(request, response) {
  console.log("IN: ", _.pick(request.body, ['From', 'Body']));
  command(request, response);
};
var app = express();
// app.use(cors);

// Listen on port 8000, IP defaults to 127.0.0.1
app.post('/sms', sms);

var server = app.listen(8071);

function enableCORSMiddleware (req,res,next) {
     // You could use * instead of the url below to allow any origin,
     // but be careful, you're opening yourself up to all sorts of things!
     res.setHeader('Access-Control-Allow-Origin',  "http://localhost:8888");
     next()
}
server.use(enableCORSMiddleware);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

module.exports=sms;

<commit_msg>simplift<commit_after>// Load the http module to create an http server.
// var express = require('express');
// var bodyParser = require('body-parser');
// var twilio = require('twilio');
// var firebase = require('firebase');
// var _ = require('lodash');
// var config = require('../node-server/helpers/config');
var command = require('./command.js');
// var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
// var server = http.createServer(function (request, response) {
//   response.writeHead(200, {"Content-Type": "text/plain"});
//   response.end("Hello World\n");
// });

var sms = function(request, response) {
  console.log("IN: ", _.pick(request.body, ['From', 'Body']));
  command(request, response);
};
// var app = express();

// Listen on port 8000, IP defaults to 127.0.0.1
// app.post('/sms', sms);
// var server = app.listen(8071);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

module.exports=sms;

<|endoftext|>


<commit_before>(function() {
  var URI, async, path, plugin;

  async = require('async');

  path = require('path');

  URI = require('URIjs');

  module.exports = plugin = function(grunt) {
    var addPlugin, helpers;
    helpers = require('../../helpers')(grunt);
    addPlugin = function(plugin, fn) {
      var cmd, uri, key, vars = '';
      uri = new URI(plugin);
      if (uri.protocol() === '' && (plugin.substr(0, 1) === '.' || plugin.substr(0, 1) === '/')) {
        plugin = path.resolve(uri.path());
      }
      if(({}.toString).call(plugin).replace(/^(\[object(\s|\uFEFF|\xA0))|(\])$/g, '').toLowerCase() === 'object'){
        if(plugin.vars){
          for(key in plugin.vars){
            vars += ' --variable '+key+'='+plugin.vars[key];
          }
        }
        if(plugin.url){
          cmd = "cordova plugin add " + plugin.url + vars + " " + (helpers.setVerbosity());
        }
      }else{
        cmd = "cordova plugin add " + plugin + " " + (helpers.setVerbosity());
      }
      return helpers.exec(cmd, fn);
    };
    return {
      add: function(plugins, fn) {
        grunt.log.writeln('Adding plugins');
        return async.eachSeries(plugins, addPlugin, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

}).call(this);
<commit_msg>Update plugin.js<commit_after>(function() {
  var URI, async, path, plugin;

  async = require('async');

  path = require('path');

  URI = require('URIjs');

  module.exports = plugin = function(grunt) {
    var addPlugin, helpers;
    helpers = require('../../helpers')(grunt);
    addPlugin = function(plugin, fn) {
      var cmd, uri, key, vars = '';
      if(({}.toString).call(plugin).replace(/^(\[object(\s|\uFEFF|\xA0))|(\])$/g, '').toLowerCase() === 'object'){
        if(plugin.vars){
          for(key in plugin.vars){
            vars += ' --variable '+key+'='+plugin.vars[key];
          }
          console.log("cordova plugin add " + plugin.url + vars + " " + (helpers.setVerbosity()));
        }
        plugin = plugin.url;
      }
      uri = new URI(plugin);
      if (uri.protocol() === '' && (plugin.substr(0, 1) === '.' || plugin.substr(0, 1) === '/')) {
        plugin = path.resolve(uri.path());
      }
      cmd = "cordova plugin add " + plugin + " " + (helpers.setVerbosity());
      return helpers.exec(cmd, fn);
    };
    return {
      add: function(plugins, fn) {
        grunt.log.writeln('Adding plugins');
        return async.eachSeries(plugins, addPlugin, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

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


<commit_before>module.exports = function (grunt) {
    'use strict';

    grunt.registerTask("jasmine_node", "Runs jasmine-node.", function() {
      var jasmine = require('jasmine-node');
      var util;
      // TODO: ditch this when grunt v0.4 is released
      grunt.util = grunt.util || grunt.utils;
      var Path = require('path');
      var _ = grunt.util._;

      try {
          util = require('util');
      } catch(e) {
          util = require('sys');
      }

      var specFolders     = grunt.config("jasmine_node.specFolders") || ".";
      var source          = grunt.config("jasmine_node.source") || "src";
      var specNameMatcher = grunt.config("jasmine_node.specNameMatcher") || "spec";
      var teamcity        = grunt.config("jasmine_node.teamcity") || false;
      var useRequireJs    = grunt.config("jasmine_node.requirejs") || false;
      var extensions      = grunt.config("jasmine_node.extensions") || "js";
      var match           = grunt.config("jasmine_node.match") || ".";
      var matchall        = grunt.config("jasmine_node.matchall") || false;
      var autotest        = grunt.config("jasmine_node.autotest") || false;
      var useHelpers      = grunt.config("jasmine_node.useHelpers") || false;
      var forceExit       = grunt.config("jasmine_node.forceExit") || false;

      var isVerbose       = grunt.config("jasmine_node.verbose");
      var showColors      = grunt.config("jasmine_node.colors");

      if (_.isUndefined(isVerbose)) {
        isVerbose = true;
      }

      if (_.isUndefined(showColors)) {
        showColors = true;
      }

      var junitreport = {
          report: false,
          savePath : "./reports/",
          useDotNotation: true,
          consolidate: true
      };

      var jUnit = grunt.config("jasmine_node.jUnit") || junitreport;

      // Tell grunt this task is asynchronous.
      var done = this.async();

      var regExpSpec = new RegExp(match + (matchall ? "" : specNameMatcher + "\\.") + "(" + extensions + ")$", 'i');
      var onComplete = function(runner, log) {
        var exitCode;
        util.print('\n');
        if (runner.results().failedCount === 0) {
          exitCode = 0;
        } else {
          exitCode = 1;

          if (forceExit) {
            process.exit(exitCode);
          }
        }

        done();
      };

      var options = {
        specFolders:  specFolders,
        onComplete:   onComplete,
        isVerbose:    isVerbose,
        showColors:   showColors,
        teamcity:     teamcity,
        useRequireJs: useRequireJs,
        regExpSpec:   regExpSpec,
        junitreport:  jUnit
      };

      // order is preserved in node.js
      var legacyArguments = Object.keys(options).map(function(key) {
        return options[key];
      });

      try {
        // for jasmine-node@1.0.27 individual arguments need to be passed
        jasmine.executeSpecsInFolder.apply(this, legacyArguments);
      }
      catch (e) {
        try {
          // since jasmine-node@1.0.28 an options object need to be passed
          jasmine.executeSpecsInFolder(options);
        } catch (e) {
          console.log('Failed to execute "jasmine.executeSpecsInFolder": ' + e.stack);
        }
      }
    });
};
<commit_msg>allow use of projectRoot or specFolders<commit_after>module.exports = function (grunt) {
    'use strict';

    grunt.registerTask("jasmine_node", "Runs jasmine-node.", function() {
      var jasmine = require('jasmine-node');
      var util;
      // TODO: ditch this when grunt v0.4 is released
      grunt.util = grunt.util || grunt.utils;
      var Path = require('path');
      var _ = grunt.util._;

      try {
          util = require('util');
      } catch(e) {
          util = require('sys');
      }

      var specFolders     = grunt.config("jasmine_node.specFolders") || [];
      var source          = grunt.config("jasmine_node.source") || "src";
      var specNameMatcher = grunt.config("jasmine_node.specNameMatcher") || "spec";
      var teamcity        = grunt.config("jasmine_node.teamcity") || false;
      var useRequireJs    = grunt.config("jasmine_node.requirejs") || false;
      var extensions      = grunt.config("jasmine_node.extensions") || "js";
      var match           = grunt.config("jasmine_node.match") || ".";
      var matchall        = grunt.config("jasmine_node.matchall") || false;
      var autotest        = grunt.config("jasmine_node.autotest") || false;
      var useHelpers      = grunt.config("jasmine_node.useHelpers") || false;
      var forceExit       = grunt.config("jasmine_node.forceExit") || false;

      var isVerbose       = grunt.config("jasmine_node.verbose");
      var showColors      = grunt.config("jasmine_node.colors");

      if(grunt.config("jasmine_node.projectRoot")){
        specFolders.push(grunt.config("jasmine_node.projectRoot"));
      }

      if (_.isUndefined(isVerbose)) {
        isVerbose = true;
      }

      if (_.isUndefined(showColors)) {
        showColors = true;
      }

      var junitreport = {
          report: false,
          savePath : "./reports/",
          useDotNotation: true,
          consolidate: true
      };

      var jUnit = grunt.config("jasmine_node.jUnit") || junitreport;

      // Tell grunt this task is asynchronous.
      var done = this.async();

      var regExpSpec = new RegExp(match + (matchall ? "" : specNameMatcher + "\\.") + "(" + extensions + ")$", 'i');
      var onComplete = function(runner, log) {
        var exitCode;
        util.print('\n');
        if (runner.results().failedCount === 0) {
          exitCode = 0;
        } else {
          exitCode = 1;

          if (forceExit) {
            process.exit(exitCode);
          }
        }

        done();
      };

      var options = {
        specFolders:  specFolders,
        onComplete:   onComplete,
        isVerbose:    isVerbose,
        showColors:   showColors,
        teamcity:     teamcity,
        useRequireJs: useRequireJs,
        regExpSpec:   regExpSpec,
        junitreport:  jUnit
      };

      // order is preserved in node.js
      var legacyArguments = Object.keys(options).map(function(key) {
        return options[key];
      });

      try {
        // for jasmine-node@1.0.27 individual arguments need to be passed
        jasmine.executeSpecsInFolder.apply(this, legacyArguments);
      }
      catch (e) {
        try {
          // since jasmine-node@1.0.28 an options object need to be passed
          jasmine.executeSpecsInFolder(options);
        } catch (e) {
          console.log('Failed to execute "jasmine.executeSpecsInFolder": ' + e.stack);
        }
      }
    });
};
<|endoftext|>


<commit_before>var common = require("./common")
  , ibmdb = require("../")
  , assert = require("assert")
  , insertCount = 0;
  ;

//ibmdb.debug(true);
ibmdb.open(common.connectionString, function(err, conn) {
  if(err) {
    console.log(err);
    return;
  }

  // Insert array data using querySync API
  // =====================================
  err = conn.querySync("create table arrtab (c1 int, c2 double, c3 smallint, c4 varchar(10))");
  if(err.length) { console.log(err); return; }
  err = conn.querySync("insert into arrtab values (9, 4.5, true, 'rocket')");
  if(err.length) { console.log(err); return; }
  var param1 = {ParamType:"ARRAY", DataType:1, Data:[null,5,6,7,8]};
  var param2 = {ParamType:"ARRAY", DataType:"DOUBLE", Data:[4.1,null,6.14,7,8.3]};
  var param3 = {ParamType:"ARRAY", DataType:1, Data:[0,1,null,false,true]};
  var namearr = [null, "Row 200", null, "Row 4000", "Last Row"];
  var param4 = {ParamType:"ARRAY", DataType:1, Data:namearr, Length:9};
  var queryOptions = {sql:"insert into arrtab values (?, ?, ?, ?)",
                      params: [param1, param2, param3, param4],
                      ArraySize:5};

  conn.querySync(queryOptions);

  // Insert array data using prepare-bind-execute API
  // ================================================
  conn.querySync("create table arrtab2 (c1 int, c2 varchar(10))");
  var param5 = {ParamType:"ARRAY", DataType:1, Data:[10,20,30,40]};
  var namearr = ["Row 10", "Row 2000", "Row 30", "Last Row"];
  var param6 = {ParamType:"ARRAY", DataType:1, Data:namearr};

  //Note: param4 uses "Length" key, but param6 do not use Length key
  var tab2data =  [
        { C1: 10, C2: 'Row 10' },
        { C1: 20, C2: 'Row 20' },
        { C1: 30, C2: 'Row 30' },
        { C1: 40, C2: 'Last R' },
        { C1: 10, C2: 'Row 10' },
        { C1: 20, C2: 'Row 20' },
        { C1: 30, C2: 'Row 30' },
        { C1: 40, C2: 'Last R' }
      ];

  var stmt = conn.prepareSync("insert into arrtab2 values (?, ?)");
  stmt.bindSync([param5, param6]);
  stmt.setAttrSync(ibmdb.SQL_ATTR_PARAMSET_SIZE, 4);
  var result = stmt.executeSync();
  stmt.closeSync();

  // Insert array data using query API
  // =====================================
  conn.query(queryOptions, function(err, result) {
    if(err) console.log(err);
    else {
      var data = conn.querySync("select * from arrtab");
      console.log("\nSelected data for table ARRTAB =\n", data);
      conn.querySync("drop table arrtab");

      // Insert array data using prepare-bind-execute API
      // ================================================
      conn.prepare("insert into arrtab2 values (?, ?)", function(err, stmt) {
        if(err) { console.log(err); stmt.closeSync(); }
        else {
          stmt.setAttr(ibmdb.SQL_ATTR_PARAMSET_SIZE, 4, function(err, result) {
            if(err) { console.log(err); stmt.closeSync(); }
            else {
              stmt.execute([param5, param6], function(err, result) {
                if(err) console.log(err);
                stmt.closeSync();
                var data = conn.querySync("select * from arrtab2");
                console.log("\nSelected data for table ARRTAB2 =\n", data);
                conn.querySync("drop table arrtab2");
                assert.deepEqual(data, tab2data);
                conn.closeSync();
              });
            }
          });
        }
      });
    }
  });
});

<commit_msg>add test for issue #706<commit_after>var common = require("./common")
  , ibmdb = require("../")
  , assert = require("assert")
  , insertCount = 0;
  ;

//ibmdb.debug(true);
ibmdb.open(common.connectionString, function(err, conn) {
  if(err) {
    console.log(err);
    return;
  }

  // Insert array data using querySync API
  // =====================================
  err = conn.querySync("create table arrtab (c1 int, c2 double, c3 smallint, c4 varchar(10))");
  if(err.length) { console.log(err); return; }
  err = conn.querySync("insert into arrtab values (9, 4.5, true, 'rocket')");
  if(err.length) { console.log(err); return; }
  var param1 = {ParamType:"ARRAY", DataType:1, Data:[null,5,6,7,8]};
  var param2 = {ParamType:"ARRAY", DataType:"DOUBLE", Data:[4.1,null,6.14,7,8.3]};
  var param3 = {ParamType:"ARRAY", DataType:1, Data:[0,1,null,false,true]};
  var namearr = ["", "Row 200", null, "Row 4000", "Last Row"];
  var param4 = {ParamType:"ARRAY", DataType:1, Data:namearr, Length:9};
  var queryOptions = {sql:"insert into arrtab values (?, ?, ?, ?)",
                      params: [param1, param2, param3, param4],
                      ArraySize:5};

  conn.querySync(queryOptions);

  // Insert array data using prepare-bind-execute API
  // ================================================
  conn.querySync("create table arrtab2 (c1 int, c2 varchar(10))");
  var param5 = {ParamType:"ARRAY", DataType:1, Data:[10,20,30,40]};
  var namearr = ["Row 10", "Row 2000", "Row 30", "Last Row"];
  var param6 = {ParamType:"ARRAY", DataType:1, Data:namearr};

  //Note: param4 uses "Length" key, but param6 do not use Length key
  var tab2data =  [
        { C1: 10, C2: 'Row 10' },
        { C1: 20, C2: 'Row 20' },
        { C1: 30, C2: 'Row 30' },
        { C1: 40, C2: 'Last R' },
        { C1: 10, C2: 'Row 10' },
        { C1: 20, C2: 'Row 20' },
        { C1: 30, C2: 'Row 30' },
        { C1: 40, C2: 'Last R' }
      ];

  var stmt = conn.prepareSync("insert into arrtab2 values (?, ?)");
  stmt.bindSync([param5, param6]);
  stmt.setAttrSync(ibmdb.SQL_ATTR_PARAMSET_SIZE, 4);
  var result = stmt.executeSync();
  stmt.closeSync();

  // Insert array data using query API
  // =====================================
  conn.query(queryOptions, function(err, result) {
    if(err) console.log(err);
    else {
      var data = conn.querySync("select * from arrtab");
      console.log("\nSelected data for table ARRTAB =\n", data);
      conn.querySync("drop table arrtab");

      // Insert array data using prepare-bind-execute API
      // ================================================
      conn.prepare("insert into arrtab2 values (?, ?)", function(err, stmt) {
        if(err) { console.log(err); stmt.closeSync(); }
        else {
          stmt.setAttr(ibmdb.SQL_ATTR_PARAMSET_SIZE, 4, function(err, result) {
            if(err) { console.log(err); stmt.closeSync(); }
            else {
              stmt.execute([param5, param6], function(err, result) {
                if(err) console.log(err);
                stmt.closeSync();
                var data = conn.querySync("select * from arrtab2");
                console.log("\nSelected data for table ARRTAB2 =\n", data);
                conn.querySync("drop table arrtab2");
                assert.deepEqual(data, tab2data);
                conn.closeSync();
              });
            }
          });
        }
      });
    }
  });
});

ibmdb.open(common.connectionString, function(err, conn) {
  if(err) {
    console.log(err);
    return;
  }

  // Insert array data using querySync API
  // =====================================
  err = conn.querySync("create table arrtab3 (c1 varchar(10))");
  if(err.length) { console.log(err); return; }
  var params1 = [{ParamType:"ARRAY", DataType:1, Data: ["","Hello"], Length:5}];
  var params2 = [{ParamType:"ARRAY", DataType:1, Data: ["Hello",""], Length:5}];
  var queryOptions1 = {sql:"insert into arrtab3 values (?)",
                      params: [{ParamType:"ARRAY", DataType:1, Data: ["","Hello"], Length:5}],
                      ArraySize:2};
  var queryOptions2 = {sql:"insert into arrtab3 values (?)",
                      params: [{ParamType:"ARRAY", DataType:1, Data: ["Hello",""], Length:5}],
                      ArraySize:2};

  conn.querySync(queryOptions1);
  conn.querySync(queryOptions2);

  // Insert array data using prepare-bind-execute API
  // ================================================
  conn.querySync("create table arrtab4 (c1 varchar(10))");

  var tab4data =  [
        { C1: '' },
        { C1: 'Hello' },
        { C1: 'Hello' },
        { C1: '' }
      ];

  var stmt = conn.prepareSync("insert into arrtab4 values (?)");
  stmt.bindSync(params1);
  stmt.setAttrSync(ibmdb.SQL_ATTR_PARAMSET_SIZE, 2);
  var result = stmt.executeSync();
  stmt.closeSync();

  // Insert array data using query API
  // =====================================
  conn.query(queryOptions1, function(err, result) {
    if(err) console.log(err);
    else {
      var data = conn.querySync("select * from arrtab3");
      console.log("\nSelected data for table ARRTAB3 =\n", data);
      conn.querySync("drop table arrtab3");

      // Insert array data using prepare-bind-execute API
      // ================================================
      conn.prepare("insert into arrtab4 values (?)", function(err, stmt) {
        if(err) { console.log(err); stmt.closeSync(); }
        else {
          stmt.setAttr(ibmdb.SQL_ATTR_PARAMSET_SIZE, 2, function(err, result) {
            if(err) { console.log(err); stmt.closeSync(); }
            else {
              stmt.execute(params2, function(err, result) {
                if(err) console.log(err);
                stmt.closeSync();
                var data = conn.querySync("select * from arrtab4");
                console.log("\nSelected data for table ARRTAB4 =\n", data);
                conn.querySync("drop table arrtab4");
                assert.deepEqual(data, tab4data);
                conn.closeSync();
              });
            }
          });
        }
      });
    }
  });
});

<|endoftext|>