<commit_before>SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem = function(Facade, optionElement) {
	this.element = optionElement;
	this.type = "option";

	this.isSelected = function() {
		return (this.element.getAttribute("selected") === null) ? false : true;
	}

	this.getText = function() {
		return this.element.text;
	}

	this.getOptionGroupLabel = function() {
		return this.element.parentNode.label;
	}

	this.getValue = function() {
		return this.element.value;
	}

	this.setSelected = function() {
		Facade.publish("NativeSelectBox").setSelectedIndex(this.element.index);
		Facade.publish("NativeSelectBox").triggerChange();
		this.element.setSelectedAttribute();
	}

	this.removeSelected = function() {
		this.element.removeAttribute("selected", "selected");
	}

	this.getImageUrl = function() {
		return this.element.getDataAttribute("image-url");
	}

	this.getDescription = function() {
		return this.element.getDataAttribute("description");
	}

	this.getOptionGroup = function() {
		var parentNode = this.element.parentNode;
		var tagName = parentNode.tagName;
		if (tagName !== null && tagName !== undefined) {
			if (tagName.toLowerCase() === "optgroup")
				return parentNode;
		}
	}
};

SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem.prototype = Object.create(SELECT.ELEMENTS.Element.prototype);<commit_msg>is empty check<commit_after>SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem = function(Facade, optionElement) {
	this.element = optionElement;
	this.type = "option";

	this.isSelected = function() {
		return (this.element.getAttribute("selected") === null) ? false : true;
	}

	this.getText = function() {
		return this.element.text;
	}

	this.getOptionGroupLabel = function() {
		return this.element.parentNode.label;
	}

	this.getValue = function() {
		return this.element.value;
	}

	this.setSelected = function() {
		Facade.publish("NativeSelectBox").setSelectedIndex(this.element.index);
		Facade.publish("NativeSelectBox").triggerChange();
		this.element.setSelectedAttribute();
	}

	this.removeSelected = function() {
		this.element.removeAttribute("selected", "selected");
	}

	this.getImageUrl = function() {
		return this.element.getDataAttribute("image-url");
	}

	this.getDescription = function() {
		return this.element.getDataAttribute("description");
	}

	this.getOptionGroup = function() {
		var parentNode = this.element.parentNode;
		if (SELECT.UTILS.isEmpty(parentNode))
			return;
		var tagName = parentNode.tagName;
		if (tagName !== null && tagName !== undefined) {
			if (tagName.toLowerCase() === "optgroup")
				return parentNode;
		}
	}
};

SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem.prototype = Object.create(SELECT.ELEMENTS.Element.prototype);<|endoftext|>


<commit_before>var Promise = require('bluebird');
var db = require('../../db');
var contract = require('../../utils/contract');

// select * from users u, userdetails ud where ud.userid = u.id and u.isactive = true limit 10 offset 10;

function findAll(params, limit, offset){
  params['users.id'] = '$userdetails.userid$';

  return db.execute({
    type: 'select',
    table: ['users', 'userdetails'],
    columns: ['userdetails.userid', 'userdetails.name', 'userdetails.contactnumber', 'userdetails.email', 'userdetails.usertype', 'userdetails.isonline', 'userdetails.isavailable'],
    where: {
      'users.id': '$userdetails.userid$'
    },
    limit: limit,
    offset: offset
  });
};

function get(){
  // get user info
  return true;
};

function post(){
  //save user info
  return true;
};

function patch(params){
  // update user info
  return true;
};

function remove(){
  // delete user info
  return true;
}

module.exports = {
  fetchAll: findAll,
  create: post,
  fetchOne: get,
  update: patch,
  remove: remove
};<commit_msg>added alias to users and fetchAll working fine<commit_after>var Promise = require('bluebird');

var db = require('../../db');
var contract = require('../../utils/contract');
var utils = require('../../utils/utils');

// select * from users u, userdetails ud where ud.userid = u.id and u.isactive = true limit 10 offset 10;

function findAll(params, limit, offset){
  var ref = {
    isActive: 'users.isActive',
    userId: 'userdetails.userId',
    name: 'userdetails.name',
    contactNumber: 'userdetails.contactNumber',
    email: 'userdetails.email',
    userType: 'userdetails.userType',
    isOnline: 'userdetails.isOnline',
    isavailable: 'userdetails.isavailable'
  };
  params =  utils.aliases(params, ref);
  params['users.id'] = '$userdetails.userid$';

  return db.execute({
    type: 'select',
    table: ['users', 'userdetails'],
    columns: ['users.isActive', 'userdetails.userid', 'userdetails.name', 'userdetails.contactnumber', 'userdetails.email', 'userdetails.usertype', 'userdetails.isonline', 'userdetails.isavailable'],
    where: params,
    limit: limit,
    offset: offset
  });
};

function get(){
  // get user info
  return true;
};

function post(){
  //save user info
  return true;
};

function patch(params){
  // update user info
  return true;
};

function remove(){
  // delete user info
  return true;
}

module.exports = {
  fetchAll: findAll,
  create: post,
  fetchOne: get,
  update: patch,
  remove: remove
};<|endoftext|>


<commit_before>"use strict";

var $ = require('jquery'),
    L = require('leaflet'),
    mapModule = require('./map'),
    mapUtil = require('./lib/mapUtil'),
    zoom = require('./lib/mapUtil').ZOOM,
    SelectableBlockfaceLayer = require('./lib/SelectableBlockfaceLayer'),
    BlockfaceLayer = require('./lib/BlockfaceLayer'),
    SavedState = require('./lib/SavedState'),

    MIN_ZOOM = zoom.NEIGHBORHOOD,

    statePrompter = require('./lib/statePrompter').init({
        warning: 'You have unsaved block edge reservations.',
        question: ''
    }),

    attrs = {
        blockfaceId: 'data-blockface-id',
        blockfaceStatus: 'data-blockface-status',
        blockfaceAction: 'data-blockface-action'
    },

    dom = {
        modals: '.modal',
        currentReservations: "#current-reservations",
        totalReservations: "#total-reservations",
        finishReservations: "#finish-reservations",
        hiddenInput: "#reservation-ids",
        requestAccessButton: '[data-action="request-access"]',
        limitReachedModal: '#limit-reached-modal',
        alreadyReservedModal: '#already-reserved-modal',
        requestAccessModal: '#request-access-modal',
        requestAccessCompleteModal: '#request-access-complete-modal',
        requestAccessFailModal: '#request-access-fail-modal',
        unavailableBlockfaceModal: '#unavailable-blockface-modal',

        addRemoveBtn: '#reservations-add-remove',

        cartActionBar: '#reservations-cart-action',
        cartHelpText: '#reservations-help-text',
        cartHelpTextZoomedOut: '.js-zoomed-out-help',
        cartHelpTextZoomedIn: '.js-zoomed-in-help',
        cartFinishSection: '#reservations-finish-section',

        blockActionBar: '#reservations-blockface-action',
        blockActionPopupContainer: '#reservations-blockface-popup-container',
        blockActionBarClose: '#close-blockface-action',

        legendTitle: '.js-legend-title',
        mapSidebar: '.map-sidebar',

        popupTemplate: '#reservations-blockface-popup-template',
        popupBlockfaceId: '[' + attrs.blockfaceId + ']',
        popupBlockfaceStatus: '[' + attrs.blockfaceStatus + ']',
        popupAction: '[' + attrs.blockfaceAction + ']'
    },

    actions = {
        remove: 'Remove',
        add: 'Add to Cart'
    },

    currentlyReservedIds = [];

require('./lib/mapHelp');

// Extends the leaflet object
require('leaflet-utfgrid');
require('leaflet-geometryutil');

var reservationMap = mapModule.create({
    geolocation: true,
    legend: true,
    search: true
});

var $current = $(dom.currentReservations),
    $hiddenInput = $(dom.hiddenInput),
    $finishButton = $(dom.finishReservations),

    selectedBlockfacesCount = +($current.text()),
    blockfaceLimit = +($(dom.totalReservations).text()),
    selectedBlockfaces = {},
    blockfaceLayers = {},

    tileLayer = mapModule.addTileLayer(reservationMap, {minZoom: MIN_ZOOM}),
    grid = mapModule.addGridLayer(reservationMap);

var selectedLayer = new SelectableBlockfaceLayer(reservationMap, grid, {
    onAdd: function(gridData, latlng) {
        if (selectedBlockfacesCount >= blockfaceLimit) {
            $(dom.limitReachedModal).modal('show');
        } else if (gridData.restriction === "none") {
            selectedLayer.clearLayers();
            showPopup(gridData.id, latlng, 'Available', actions.add);

            return true;
        }
        return false;
    },

    onRemove: function(feature) {
        reservationMap.closePopup();
        return true;
    }
});

// Zoom the map to fit a blockface ID passed in the URL hash, if it is an
// already reserved block
var blockfaceId = mapUtil.getBlockfaceIdFromUrl();

var reservedLayer = new BlockfaceLayer(reservationMap, {
    color: '#CE2029',
    onEachFeature: function(feature, layer) {
        layer.on('click', function(e) {
            selectReservedBlockface(feature, layer, e.latlng);
        });

        if (feature.properties.id === blockfaceId) {
            blockfaceId = null;

            // We need to add this to the map *after* the reserved blockface
            // layer is done adding things
            window.setTimeout(function() {
                reservationMap.fitBounds(layer.getBounds());

                var middlePoint = L.GeometryUtil.interpolateOnLine(reservationMap, layer.getLatLngs()[0], 0.5);
                selectReservedBlockface(feature, layer, middlePoint.latLng);
            }, 1);
        }
    }
});

var cartLayer = new BlockfaceLayer(reservationMap, {
    color: '#FF69B4',
    onEachFeature: function(feature, layer) {
        layer.on('click', function(e) {
            showPopup(feature.properties.id, e.latlng, 'In Cart', actions.remove);
            selectFeature(feature, layer);
        });
    }
});

reservationMap.on('zoomend', updateForZoom);

function updateForZoom() {
    // At low zooms, generating map tiles which show reservable blocks
    // is expensive and unnecessary.
    var showTiles = (reservationMap.getZoom() >= MIN_ZOOM);

    toggleLayer(tileLayer);
    toggleLayer(grid);

    $(dom.cartHelpTextZoomedIn).toggle(showTiles);
    $(dom.cartHelpTextZoomedOut).toggle(!showTiles);

    function toggleLayer(layer) {
        if (showTiles && !reservationMap.hasLayer(layer)) {
            reservationMap.addLayer(layer);
        } else if (!showTiles && reservationMap.hasLayer(layer)) {
            reservationMap.removeLayer(layer);
        }
    }
}

function selectReservedBlockface(feature, layer, latlng) {
    showPopup(feature.properties.id, latlng, 'Expires ' + feature.properties.expires_at, actions.remove);
    selectFeature(feature, layer);
}

function selectFeature(feature, layer) {
    selectedLayer.clearLayers();
    blockfaceLayers[feature.properties.id] = layer;
    selectedLayer.addData(feature);
}

// Keep this URL in sync with src/nyc_trees/apps/survey/urls/blockface.py
$.getJSON("/blockedge/reserved-blockedges.json", function(data) {
    $.each(data, function(__, blockface) {
        selectedBlockfaces[blockface.properties.id] = blockface;
        reservedLayer.addData(blockface);
        currentlyReservedIds.push(blockface.properties.id);
    });
});

function showPopup(blockfaceId, latlng, status, action) {
    var $popup = $($(dom.popupTemplate).html());

    $popup.find(dom.popupBlockfaceStatus).html(status);

    // Bit of a cludge here, 'id' and 'action' are both on the same element,
    // Calling '.html(...)' for action last ensures the correct text is present
    $popup.find(dom.popupBlockfaceId).attr(attrs.blockfaceId, blockfaceId).html(blockfaceId);
    $popup.find(dom.popupAction).attr(attrs.blockfaceAction, action).html(action);

    // We add the blockface popup in 2 places, as a leaflet popup and as an
    // action bar item.
    // CSS media queries will hide one or the other depending on screen size.

    // But we don't want invisible popups to auto-pan the map in "mobile" view,
    // so only add the popup if we are in "desktop" view -- determined by
    // whether the legend is visible.
    if ($(dom.legendTitle + ':visible').length > 0) {
        // Find right edge of sidebar so we can make the popup avoid it
        var $sidebar = $(dom.mapSidebar),
            sidebarRight = $sidebar.offset().left + $sidebar.outerWidth();
        L.popup({
            className: 'reservation-leaflet-popup',
            autoPanPaddingTopLeft: [sidebarRight + 8, 8]
        })
            .setLatLng(latlng)
            .setContent($popup[0])
            .openOn(reservationMap);
    }
    $(dom.blockActionBar).addClass('active');
    $(dom.blockActionPopupContainer).html($popup.clone());
    $(dom.cartActionBar).removeClass('active');
}

$(dom.blockActionBarClose).on('click', closeActionbar);

function closeActionbar() {
    $(dom.blockActionBar).removeClass('active');
    $(dom.cartActionBar).addClass('active');
    selectedLayer.clearLayers();
}

reservationMap.on('popupclose', function() {
    selectedLayer.clearLayers();
    closeActionbar();
});

$('body').on('click', dom.popupAction, function(e) {
    var $elem = $(e.currentTarget),
        action = $elem.text(),
        blockfaceId = $elem.attr(attrs.blockfaceId);

    if (action === actions.add) {
        addToCart(blockfaceId);
    } else if (action === actions.remove) {
        removeFromCart(blockfaceId);
    }

    selectedLayer.clearLayers();
    reservationMap.closePopup();
    closeActionbar();
});

function addToCart(id) {
    $(dom.cartHelpText).addClass('hidden');
    $(dom.cartFinishSection).removeClass('hidden');

    selectedBlockfaces[id] = null;
    selectedBlockfacesCount++;
    $current.text(selectedBlockfacesCount);

    updateForm();

    cartLayer.addData(selectedLayer.getLayers()[0].feature);
    reservedLayer.removeLayer(blockfaceLayers[id]);
    delete blockfaceLayers[id];
}

function removeFromCart(id) {
    $(dom.cartHelpText).addClass('hidden');
    $(dom.cartFinishSection).removeClass('hidden');

    if (selectedBlockfacesCount > 0) {
        selectedBlockfacesCount--;
        $current.text(selectedBlockfacesCount);
    }
    delete selectedBlockfaces[id];
    updateForm();

    cartLayer.removeLayer(blockfaceLayers[id]);
    reservedLayer.removeLayer(blockfaceLayers[id]);
    delete blockfaceLayers[id];
}

function updateForm() {
    var ids = Object.keys(selectedBlockfaces);
    // Check if the blockfaces in the cart are identical to those already
    // reserved, and enable the button if they are different

    if ( ! arrayEquals(ids, currentlyReservedIds)) {
        $hiddenInput.val(ids.join());
        statePrompter.lock();
        $finishButton.prop('disabled', false);
    } else {
        statePrompter.unlock();
        $finishButton.prop('disabled', true);
    }
}

function arrayEquals(a, b) {
    // compare lengths - can save a lot of time
    if (a.length != b.length) {
        return false;
    }
    a.sort();
    b.sort();

    for (var i = 0, l=a.length; i < l; i++) {
        if (a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

grid.on('click', function(e) {
    if (!e.data) {
        return;
    }
    if (e.data.restriction === 'group_territory') {
        $(dom.requestAccessModal)
            .find(dom.requestAccessButton)
            .data('group-slug', e.data.group_slug);
        $(dom.requestAccessModal).modal('show');
    } else if (e.data.restriction === 'reserved') {
        $(dom.alreadyReservedModal).modal('show');
    } else if (e.data.restriction !== 'none') {
        $(dom.unavailableBlockfaceModal).modal('show');
    }
});

reservationMap.addLayer(cartLayer);
reservationMap.addLayer(reservedLayer);
reservationMap.addLayer(selectedLayer);

$(dom.requestAccessModal).on('click', dom.requestAccessButton, function() {
    var groupSlug = $(dom.requestAccessButton).data('group-slug');
    $(dom.modals).modal('hide');
    $.ajax({
            // Keep this URL in sync with "request_mapper_status"
            // in src/nyc_trees/apps/users/urls/group.py
            url: '/group/' + groupSlug + '/request-trusted-mapper-status/',
            type: 'POST'
        })
        .done(function() {
            $(dom.requestAccessCompleteModal).modal('show');
        })
        .fail(function() {
            $(dom.requestAccessFailModal).modal('show');
        });
});

$finishButton.on('click', statePrompter.unlock);

updateForZoom();<commit_msg>Show user location on the reservations page.<commit_after>"use strict";

var $ = require('jquery'),
    L = require('leaflet'),
    mapModule = require('./map'),
    mapUtil = require('./lib/mapUtil'),
    zoom = require('./lib/mapUtil').ZOOM,
    SelectableBlockfaceLayer = require('./lib/SelectableBlockfaceLayer'),
    BlockfaceLayer = require('./lib/BlockfaceLayer'),
    SavedState = require('./lib/SavedState'),

    MIN_ZOOM = zoom.NEIGHBORHOOD,

    statePrompter = require('./lib/statePrompter').init({
        warning: 'You have unsaved block edge reservations.',
        question: ''
    }),

    attrs = {
        blockfaceId: 'data-blockface-id',
        blockfaceStatus: 'data-blockface-status',
        blockfaceAction: 'data-blockface-action'
    },

    dom = {
        modals: '.modal',
        currentReservations: "#current-reservations",
        totalReservations: "#total-reservations",
        finishReservations: "#finish-reservations",
        hiddenInput: "#reservation-ids",
        requestAccessButton: '[data-action="request-access"]',
        limitReachedModal: '#limit-reached-modal',
        alreadyReservedModal: '#already-reserved-modal',
        requestAccessModal: '#request-access-modal',
        requestAccessCompleteModal: '#request-access-complete-modal',
        requestAccessFailModal: '#request-access-fail-modal',
        unavailableBlockfaceModal: '#unavailable-blockface-modal',

        addRemoveBtn: '#reservations-add-remove',

        cartActionBar: '#reservations-cart-action',
        cartHelpText: '#reservations-help-text',
        cartHelpTextZoomedOut: '.js-zoomed-out-help',
        cartHelpTextZoomedIn: '.js-zoomed-in-help',
        cartFinishSection: '#reservations-finish-section',

        blockActionBar: '#reservations-blockface-action',
        blockActionPopupContainer: '#reservations-blockface-popup-container',
        blockActionBarClose: '#close-blockface-action',

        legendTitle: '.js-legend-title',
        mapSidebar: '.map-sidebar',

        popupTemplate: '#reservations-blockface-popup-template',
        popupBlockfaceId: '[' + attrs.blockfaceId + ']',
        popupBlockfaceStatus: '[' + attrs.blockfaceStatus + ']',
        popupAction: '[' + attrs.blockfaceAction + ']'
    },

    actions = {
        remove: 'Remove',
        add: 'Add to Cart'
    },

    currentlyReservedIds = [];

require('./lib/mapHelp');

// Extends the leaflet object
require('leaflet-utfgrid');
require('leaflet-geometryutil');

var reservationMap = mapModule.create({
    geolocation: true,
    legend: true,
    search: true
});

mapModule.startTrackingUserPosition(reservationMap);

var $current = $(dom.currentReservations),
    $hiddenInput = $(dom.hiddenInput),
    $finishButton = $(dom.finishReservations),

    selectedBlockfacesCount = +($current.text()),
    blockfaceLimit = +($(dom.totalReservations).text()),
    selectedBlockfaces = {},
    blockfaceLayers = {},

    tileLayer = mapModule.addTileLayer(reservationMap, {minZoom: MIN_ZOOM}),
    grid = mapModule.addGridLayer(reservationMap);

var selectedLayer = new SelectableBlockfaceLayer(reservationMap, grid, {
    onAdd: function(gridData, latlng) {
        if (selectedBlockfacesCount >= blockfaceLimit) {
            $(dom.limitReachedModal).modal('show');
        } else if (gridData.restriction === "none") {
            selectedLayer.clearLayers();
            showPopup(gridData.id, latlng, 'Available', actions.add);

            return true;
        }
        return false;
    },

    onRemove: function(feature) {
        reservationMap.closePopup();
        return true;
    }
});

// Zoom the map to fit a blockface ID passed in the URL hash, if it is an
// already reserved block
var blockfaceId = mapUtil.getBlockfaceIdFromUrl();

var reservedLayer = new BlockfaceLayer(reservationMap, {
    color: '#CE2029',
    onEachFeature: function(feature, layer) {
        layer.on('click', function(e) {
            selectReservedBlockface(feature, layer, e.latlng);
        });

        if (feature.properties.id === blockfaceId) {
            blockfaceId = null;

            // We need to add this to the map *after* the reserved blockface
            // layer is done adding things
            window.setTimeout(function() {
                reservationMap.fitBounds(layer.getBounds());

                var middlePoint = L.GeometryUtil.interpolateOnLine(reservationMap, layer.getLatLngs()[0], 0.5);
                selectReservedBlockface(feature, layer, middlePoint.latLng);
            }, 1);
        }
    }
});

var cartLayer = new BlockfaceLayer(reservationMap, {
    color: '#FF69B4',
    onEachFeature: function(feature, layer) {
        layer.on('click', function(e) {
            showPopup(feature.properties.id, e.latlng, 'In Cart', actions.remove);
            selectFeature(feature, layer);
        });
    }
});

reservationMap.on('zoomend', updateForZoom);

function updateForZoom() {
    // At low zooms, generating map tiles which show reservable blocks
    // is expensive and unnecessary.
    var showTiles = (reservationMap.getZoom() >= MIN_ZOOM);

    toggleLayer(tileLayer);
    toggleLayer(grid);

    $(dom.cartHelpTextZoomedIn).toggle(showTiles);
    $(dom.cartHelpTextZoomedOut).toggle(!showTiles);

    function toggleLayer(layer) {
        if (showTiles && !reservationMap.hasLayer(layer)) {
            reservationMap.addLayer(layer);
        } else if (!showTiles && reservationMap.hasLayer(layer)) {
            reservationMap.removeLayer(layer);
        }
    }
}

function selectReservedBlockface(feature, layer, latlng) {
    showPopup(feature.properties.id, latlng, 'Expires ' + feature.properties.expires_at, actions.remove);
    selectFeature(feature, layer);
}

function selectFeature(feature, layer) {
    selectedLayer.clearLayers();
    blockfaceLayers[feature.properties.id] = layer;
    selectedLayer.addData(feature);
}

// Keep this URL in sync with src/nyc_trees/apps/survey/urls/blockface.py
$.getJSON("/blockedge/reserved-blockedges.json", function(data) {
    $.each(data, function(__, blockface) {
        selectedBlockfaces[blockface.properties.id] = blockface;
        reservedLayer.addData(blockface);
        currentlyReservedIds.push(blockface.properties.id);
    });
});

function showPopup(blockfaceId, latlng, status, action) {
    var $popup = $($(dom.popupTemplate).html());

    $popup.find(dom.popupBlockfaceStatus).html(status);

    // Bit of a cludge here, 'id' and 'action' are both on the same element,
    // Calling '.html(...)' for action last ensures the correct text is present
    $popup.find(dom.popupBlockfaceId).attr(attrs.blockfaceId, blockfaceId).html(blockfaceId);
    $popup.find(dom.popupAction).attr(attrs.blockfaceAction, action).html(action);

    // We add the blockface popup in 2 places, as a leaflet popup and as an
    // action bar item.
    // CSS media queries will hide one or the other depending on screen size.

    // But we don't want invisible popups to auto-pan the map in "mobile" view,
    // so only add the popup if we are in "desktop" view -- determined by
    // whether the legend is visible.
    if ($(dom.legendTitle + ':visible').length > 0) {
        // Find right edge of sidebar so we can make the popup avoid it
        var $sidebar = $(dom.mapSidebar),
            sidebarRight = $sidebar.offset().left + $sidebar.outerWidth();
        L.popup({
            className: 'reservation-leaflet-popup',
            autoPanPaddingTopLeft: [sidebarRight + 8, 8]
        })
            .setLatLng(latlng)
            .setContent($popup[0])
            .openOn(reservationMap);
    }
    $(dom.blockActionBar).addClass('active');
    $(dom.blockActionPopupContainer).html($popup.clone());
    $(dom.cartActionBar).removeClass('active');
}

$(dom.blockActionBarClose).on('click', closeActionbar);

function closeActionbar() {
    $(dom.blockActionBar).removeClass('active');
    $(dom.cartActionBar).addClass('active');
    selectedLayer.clearLayers();
}

reservationMap.on('popupclose', function() {
    selectedLayer.clearLayers();
    closeActionbar();
});

$('body').on('click', dom.popupAction, function(e) {
    var $elem = $(e.currentTarget),
        action = $elem.text(),
        blockfaceId = $elem.attr(attrs.blockfaceId);

    if (action === actions.add) {
        addToCart(blockfaceId);
    } else if (action === actions.remove) {
        removeFromCart(blockfaceId);
    }

    selectedLayer.clearLayers();
    reservationMap.closePopup();
    closeActionbar();
});

function addToCart(id) {
    $(dom.cartHelpText).addClass('hidden');
    $(dom.cartFinishSection).removeClass('hidden');

    selectedBlockfaces[id] = null;
    selectedBlockfacesCount++;
    $current.text(selectedBlockfacesCount);

    updateForm();

    cartLayer.addData(selectedLayer.getLayers()[0].feature);
    reservedLayer.removeLayer(blockfaceLayers[id]);
    delete blockfaceLayers[id];
}

function removeFromCart(id) {
    $(dom.cartHelpText).addClass('hidden');
    $(dom.cartFinishSection).removeClass('hidden');

    if (selectedBlockfacesCount > 0) {
        selectedBlockfacesCount--;
        $current.text(selectedBlockfacesCount);
    }
    delete selectedBlockfaces[id];
    updateForm();

    cartLayer.removeLayer(blockfaceLayers[id]);
    reservedLayer.removeLayer(blockfaceLayers[id]);
    delete blockfaceLayers[id];
}

function updateForm() {
    var ids = Object.keys(selectedBlockfaces);
    // Check if the blockfaces in the cart are identical to those already
    // reserved, and enable the button if they are different

    if ( ! arrayEquals(ids, currentlyReservedIds)) {
        $hiddenInput.val(ids.join());
        statePrompter.lock();
        $finishButton.prop('disabled', false);
    } else {
        statePrompter.unlock();
        $finishButton.prop('disabled', true);
    }
}

function arrayEquals(a, b) {
    // compare lengths - can save a lot of time
    if (a.length != b.length) {
        return false;
    }
    a.sort();
    b.sort();

    for (var i = 0, l=a.length; i < l; i++) {
        if (a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

grid.on('click', function(e) {
    if (!e.data) {
        return;
    }
    if (e.data.restriction === 'group_territory') {
        $(dom.requestAccessModal)
            .find(dom.requestAccessButton)
            .data('group-slug', e.data.group_slug);
        $(dom.requestAccessModal).modal('show');
    } else if (e.data.restriction === 'reserved') {
        $(dom.alreadyReservedModal).modal('show');
    } else if (e.data.restriction !== 'none') {
        $(dom.unavailableBlockfaceModal).modal('show');
    }
});

reservationMap.addLayer(cartLayer);
reservationMap.addLayer(reservedLayer);
reservationMap.addLayer(selectedLayer);

$(dom.requestAccessModal).on('click', dom.requestAccessButton, function() {
    var groupSlug = $(dom.requestAccessButton).data('group-slug');
    $(dom.modals).modal('hide');
    $.ajax({
            // Keep this URL in sync with "request_mapper_status"
            // in src/nyc_trees/apps/users/urls/group.py
            url: '/group/' + groupSlug + '/request-trusted-mapper-status/',
            type: 'POST'
        })
        .done(function() {
            $(dom.requestAccessCompleteModal).modal('show');
        })
        .fail(function() {
            $(dom.requestAccessFailModal).modal('show');
        });
});

$finishButton.on('click', statePrompter.unlock);

updateForZoom();<|endoftext|>


<commit_before>  jQuery.benchmarker.tests = [
		"*",
		"body", "body div", "div",
		"div div div", "div div", ".dialog", "div.dialog", "div .dialog",
		"#speech5", "div#speech5", "div #speech5", "div > div", "div.scene div.dialog",
		"div#scene1.scene div.dialog div", "#scene1 #speech1", "body > div.dialog div#speech5",
		"div:nth-child(even)", "div:nth-child(odd)",
		"div:nth-child(1)", "div:nth-child(2n)",
		"div:nth-child(2n+3)", "div:first-child",
		"div:last-child", "div:only-child",
		"div:contains(CELIA)",
		"div ~ div", "div + div",
		"div[@class]", "div[@class=dialog]", "div[@class!=dialog]",
		"div[@class^=dialog]", "div[@class$=dialog]", "div[@class*=dialog]"
		]

  jQuery.fn.benchmark = function() {
    this.each(function() {
      try {
        jQuery(this).parent().children("*:gt(1)").remove();
      } catch(e) { }
    })
    // set # times to run the test in index.html
    var times = parseInt(jQuery("#times").val());
    jQuery.benchmarker.startingList = this.get();
    benchmark(this.get(), times, jQuery.benchmarker.libraries);
  }

  jQuery(function() {
    for(i = 0; i < jQuery.benchmarker.tests.length; i++) {
      jQuery("tbody").append("
" + jQuery.benchmarker.tests[i] + "
");
    }
    jQuery("tbody tr:first-child").remove();
    jQuery("td.test").before("<input type='checkbox' checked='checked' />	");
    jQuery("button.runTests").bind("click", function() {
      jQuery('td:has(input:checked) + td.test').benchmark();
    });

    jQuery("button.retryTies").bind("click", function() { jQuery("tr:has(td.tie) td.test").benchmark() })

    jQuery("button.selectAll").bind("click", function() { jQuery("input[@type=checkbox]").each(function() { this.checked = true }) })
    jQuery("button.deselectAll").bind("click", function() { jQuery("input[@type=checkbox]").each(function() { this.checked = false }) })

    jQuery("#addTest").bind("click", function() {
      jQuery("table").append("
<input type='checkbox' />	<input type='text' /><button>Add</button>
");
      jQuery("div#time-test > button").each(function() { this.disabled = true; })
      jQuery("tbody tr:last button").bind("click", function() {
        var td = jQuery(this).parent();
        td.html("<button>-</button>" + jQuery(this).prev().val()).addClass("test");
        jQuery("div#time-test > button").each(function() { this.disabled = false; })
        jQuery("button", td).bind("click", function() { jQuery(this).parents("tr").remove(); })
      })
    })

    var headers = jQuery.map(jQuery.benchmarker.libraries, function(i,n) {
      var extra = n == 0 ? "basis - " : "";
      return "" + extra + i + "	"
    }).join("");

    jQuery("thead tr").append(headers);

    var footers = "";
    for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
      footers += "	"

    var wlfooters = "";
    for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
      wlfooters += "W / F	"

    jQuery("tfoot tr:first").append(footers);
    jQuery("tfoot tr:last").append(wlfooters);

  });

   benchmark = function(list, times, libraries) {
     if(list[0]) {
       var times = times || 50;
       var el = list[0];
       var code = jQuery(el).text().replace(/^-/, "");
         if(!libraries[0].match(/^jQ/)) {
           code = code.replace(/@/, "");
         }
         var timeArr = []
         for(i = 0; i < times + 2; i++) {
           var time = new Date()
           try {
             window[libraries[0]](code);
           } catch(e) { }
           timeArr.push(new Date() - time);
         }
         var diff = Math.sum(timeArr) - Math.max.apply( Math, timeArr )
		- Math.min.apply( Math, timeArr );
         try {
           var libRes = window[libraries[0]](code);
           var jqRes = jQuery(code);
           if(((jqRes.length == 0) && (libRes.length != 0)) ||
             (libRes.length > 0 && (jqRes.length == libRes.length)) ||
             ((libraries[0] == "cssQuery" || libraries[0] == "jQuery") && code.match(/nth\-child/) && (libRes.length > 0)) ||
             ((libraries[0] == "jQold") && jqRes.length > 0)) {
             jQuery(el).parent().append("" + Math.round(diff / times * 100) / 100 + "ms	");
           } else {
             jQuery(el).parent().append("FAIL	");
           }
         } catch(e) {
           jQuery(el).parent().append("FAIL	");
         }
       setTimeout(benchmarkList(list, times, libraries), 100);
     } else if(libraries[1]) {
       benchmark(jQuery.benchmarker.startingList, times, libraries.slice(1));
     } else {
       jQuery("tbody tr").each(function() {
         var winners = jQuery("td:gt(1)", this).min(2);
         if(winners.length == 1) winners.addClass("winner");
         else winners.addClass("tie");
       });
       setTimeout(count, 100);
     }
   }

  function benchmarkList(list, times, libraries) {
    return function() {
      benchmark(list.slice(1), times, libraries);
    }
  }

 function count() {
   for(i = 3; i <= jQuery.benchmarker.libraries.length + 2 ; i++) {
     var fails = jQuery("td:nth-child(" + i + ").fail").length;
     var wins = jQuery("td:nth-child(" + i + ").winner").length;
     jQuery("tfoot tr:first th:eq(" + (i - 1) + ")")
      .html("" + wins + " / " + fails + "");
   }
 }

 jQuery.fn.maxmin = function(tolerance, maxmin, percentage) {
   tolerance = tolerance || 0;
   var target = Math[maxmin].apply(Math, jQuery.map(this, function(i) {
     var parsedNum = parseFloat(i.innerHTML.replace(/[^\.\d]/g, ""));
     if(parsedNum || (parsedNum == 0)) return parsedNum;
   }));
   return this.filter(function() {
     if( withinTolerance(parseFloat(this.innerHTML.replace(/[^\.\d]/g, "")), target, tolerance, percentage) ) return true;
   })
 }

 jQuery.fn.max = function(tolerance, percentage) { return this.maxmin(tolerance, "max", percentage) }
 jQuery.fn.min = function(tolerance, percentage) { return this.maxmin(tolerance, "min", percentage) }

 function withinTolerance(number, target, tolerance, percentage) {
   if(percentage) { var high = target + ((tolerance / 100) * target); var low = target - ((tolerance / 100) * target); }
   else { var high = target + tolerance; var low = target - tolerance; }
   if(number >= low && number <= high) return true;
 }

 Math.sum = function(arr) {
   var sum = 0;
   for(i = 0; i < arr.length; i++) sum += arr[i];
   return sum;
 }
<commit_msg>Removed all uses of @ in the benchmarker and added a couple :not() tests.<commit_after>  jQuery.benchmarker.tests = [
		"*",
		"body", "body div", "div",
		"div div div", "div div", ".dialog", "div.dialog", "div .dialog",
		"#speech5", "div#speech5", "div #speech5", "div > div", "div.scene div.dialog",
		"div#scene1.scene div.dialog div", "#scene1 #speech1", "body > div.dialog div#speech5",
		"div:not(#speech5)", "div:not(.dialog)",
		"div:nth-child(even)", "div:nth-child(odd)",
		"div:nth-child(1)", "div:nth-child(2n)",
		"div:nth-child(2n+3)", "div:first-child",
		"div:last-child", "div:only-child",
		"div:contains(CELIA)",
		"div ~ div", "div + div",
		"div[class]", "div[class=dialog]", "div[class!=dialog]",
		"div[class^=dialog]", "div[class$=dialog]", "div[class*=dialog]"
		]

  jQuery.fn.benchmark = function() {
    this.each(function() {
      try {
        jQuery(this).parent().children("*:gt(1)").remove();
      } catch(e) { }
    })
    // set # times to run the test in index.html
    var times = parseInt(jQuery("#times").val());
    jQuery.benchmarker.startingList = this.get();
    benchmark(this.get(), times, jQuery.benchmarker.libraries);
  }

  jQuery(function() {
    for(i = 0; i < jQuery.benchmarker.tests.length; i++) {
      jQuery("tbody").append("
" + jQuery.benchmarker.tests[i] + "
");
    }
    jQuery("tbody tr:first-child").remove();
    jQuery("td.test").before("<input type='checkbox' checked='checked' />	");
    jQuery("button.runTests").bind("click", function() {
      jQuery('td:has(input:checked) + td.test').benchmark();
    });

    jQuery("button.retryTies").bind("click", function() { jQuery("tr:has(td.tie) td.test").benchmark() })

    jQuery("button.selectAll").bind("click", function() { jQuery("input[type=checkbox]").each(function() { this.checked = true }) })
    jQuery("button.deselectAll").bind("click", function() { jQuery("input[type=checkbox]").each(function() { this.checked = false }) })

    jQuery("#addTest").bind("click", function() {
      jQuery("table").append("
<input type='checkbox' />	<input type='text' /><button>Add</button>
");
      jQuery("div#time-test > button").each(function() { this.disabled = true; })
      jQuery("tbody tr:last button").bind("click", function() {
        var td = jQuery(this).parent();
        td.html("<button>-</button>" + jQuery(this).prev().val()).addClass("test");
        jQuery("div#time-test > button").each(function() { this.disabled = false; })
        jQuery("button", td).bind("click", function() { jQuery(this).parents("tr").remove(); })
      })
    })

    var headers = jQuery.map(jQuery.benchmarker.libraries, function(i,n) {
      var extra = n == 0 ? "basis - " : "";
      return "" + extra + i + "	"
    }).join("");

    jQuery("thead tr").append(headers);

    var footers = "";
    for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
      footers += "	"

    var wlfooters = "";
    for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
      wlfooters += "W / F	"

    jQuery("tfoot tr:first").append(footers);
    jQuery("tfoot tr:last").append(wlfooters);

  });

   benchmark = function(list, times, libraries) {
     if(list[0]) {
       var times = times || 50;
       var el = list[0];
       var code = jQuery(el).text().replace(/^-/, "");
         var timeArr = []
         for(i = 0; i < times + 2; i++) {
           var time = new Date()
           try {
             window[libraries[0]](code);
           } catch(e) { }
           timeArr.push(new Date() - time);
         }
         var diff = Math.sum(timeArr) - Math.max.apply( Math, timeArr )
		- Math.min.apply( Math, timeArr );
         try {
           var libRes = window[libraries[0]](code);
           var jqRes = jQuery(code);
           if(((jqRes.length == 0) && (libRes.length != 0)) ||
             (libRes.length > 0 && (jqRes.length == libRes.length)) ||
             ((libraries[0] == "cssQuery" || libraries[0] == "jQuery") && code.match(/nth\-child/) && (libRes.length > 0)) ||
             ((libraries[0] == "jQold") && jqRes.length > 0)) {
             jQuery(el).parent().append("" + Math.round(diff / times * 100) / 100 + "ms	");
           } else {
             jQuery(el).parent().append("FAIL	");
           }
         } catch(e) {
           jQuery(el).parent().append("FAIL	");
         }
       setTimeout(benchmarkList(list, times, libraries), 100);
     } else if(libraries[1]) {
       benchmark(jQuery.benchmarker.startingList, times, libraries.slice(1));
     } else {
       jQuery("tbody tr").each(function() {
         var winners = jQuery("td:gt(1)", this).min(2);
         if(winners.length == 1) winners.addClass("winner");
         else winners.addClass("tie");
       });
       setTimeout(count, 100);
     }
   }

  function benchmarkList(list, times, libraries) {
    return function() {
      benchmark(list.slice(1), times, libraries);
    }
  }

 function count() {
   for(i = 3; i <= jQuery.benchmarker.libraries.length + 2 ; i++) {
     var fails = jQuery("td:nth-child(" + i + ").fail").length;
     var wins = jQuery("td:nth-child(" + i + ").winner").length;
     jQuery("tfoot tr:first th:eq(" + (i - 1) + ")")
      .html("" + wins + " / " + fails + "");
   }
 }

 jQuery.fn.maxmin = function(tolerance, maxmin, percentage) {
   tolerance = tolerance || 0;
   var target = Math[maxmin].apply(Math, jQuery.map(this, function(i) {
     var parsedNum = parseFloat(i.innerHTML.replace(/[^\.\d]/g, ""));
     if(parsedNum || (parsedNum == 0)) return parsedNum;
   }));
   return this.filter(function() {
     if( withinTolerance(parseFloat(this.innerHTML.replace(/[^\.\d]/g, "")), target, tolerance, percentage) ) return true;
   })
 }

 jQuery.fn.max = function(tolerance, percentage) { return this.maxmin(tolerance, "max", percentage) }
 jQuery.fn.min = function(tolerance, percentage) { return this.maxmin(tolerance, "min", percentage) }

 function withinTolerance(number, target, tolerance, percentage) {
   if(percentage) { var high = target + ((tolerance / 100) * target); var low = target - ((tolerance / 100) * target); }
   else { var high = target + tolerance; var low = target - tolerance; }
   if(number >= low && number <= high) return true;
 }

 Math.sum = function(arr) {
   var sum = 0;
   for(i = 0; i < arr.length; i++) sum += arr[i];
   return sum;
 }
<|endoftext|>


<commit_before>import {fromEvent} from 'rxjs'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'

const handlers = []

fromEvent(document, 'keydown')
    .subscribe(
        event => _.find([...handlers], handler => handler(event))
    )

export default class Keybinding extends React.Component {
    handler = null

    constructor(props) {
        super(props)
        this.handler = this.getHandler.bind(this)
    }

    getHandler(event) {
        const {keymap, disabled} = this.props
        if (!disabled) {
            const key = [
                {key: 'Ctrl', value: event.ctrlKey},
                {key: 'Alt', value: event.altKey},
                {key: 'Shift', value: event.shiftKey},
                {key: 'Meta', value: event.metaKey}]
                .filter(({value}) => value)
                .map(({key}) => key)
                .concat([event.key])
                .join('+')
            const handler = keymap[key]
            if (handler) {
                handler(event)
                event.preventDefault()
                return true
            } else if (keymap.default) {
                keymap.default(event)
                event.preventDefault()
                return true
            }
        }
        return false
    }

    addHandler() {
        handlers.unshift(this.handler)
    }

    removeHandler() {
        _.pull(handlers, this.handler)
    }

    render() {
        const {children} = this.props
        return children || null
    }

    componentDidMount() {
        this.addHandler()
    }

    componentWillUnmount() {
        this.removeHandler()
    }
}

Keybinding.propTypes = {
    disabled: PropTypes.any,
    keymap: PropTypes.object
}
<commit_msg>Added and removed keybindings when component is enabled/disabled.<commit_after>import {fromEvent} from 'rxjs'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import {connect} from 'store'

const handlers = []

fromEvent(document, 'keydown')
    .subscribe(
        event => _.find([...handlers], handler => handler(event))
    )

class Keybinding extends React.Component {
    handler = null

    constructor(props) {
        super(props)
        const {onEnable, onDisable} = props
        this.handler = this.getHandler.bind(this)
        onEnable(() => this.addHandler())
        onDisable(() => this.removeHandler())
    }

    getHandler(event) {
        const {keymap, disabled} = this.props
        if (!disabled) {
            const key = [
                {key: 'Ctrl', value: event.ctrlKey},
                {key: 'Alt', value: event.altKey},
                {key: 'Shift', value: event.shiftKey},
                {key: 'Meta', value: event.metaKey}]
                .filter(({value}) => value)
                .map(({key}) => key)
                .concat([event.key])
                .join('+')
            const handler = keymap[key]
            if (handler) {
                handler(event)
                event.preventDefault()
                return true
            } else if (keymap.default) {
                keymap.default(event)
                event.preventDefault()
                return true
            }
        }
        return false
    }

    addHandler() {
        handlers.unshift(this.handler)
    }

    removeHandler() {
        _.pull(handlers, this.handler)
    }

    render() {
        const {children} = this.props
        return children || null
    }

    componentDidMount() {
        this.addHandler()
    }

    componentWillUnmount() {
        this.removeHandler()
    }
}

export default connect()(
    Keybinding
)

Keybinding.propTypes = {
    disabled: PropTypes.any,
    keymap: PropTypes.object
}
<|endoftext|>


<commit_before>/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /measurements              ->  index
 * POST    /measurements              ->  create
 * GET     /measurements/:id          ->  show
 * PUT     /measurements/:id          ->  update
 * DELETE  /measurements/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var Measurement = require('./measurement.model');
var lambda = require('./lambda');

// Get list of measurements
exports.index = function(req, res) {
  Measurement.find(function (err, measurements) {
    if(err) { return handleError(res, err); }
    return res.json(200, measurements);
  });
};

// Get a single measurement
exports.show = function(req, res) {
  Measurement.findOne( { "uid" : req.params.id } , function (err, measurement) {
    if(err) { return handleError(res, err); }
    if(!measurement) { return res.send(404); }
    return res.json(measurement);
  });
};

// Creates a new measurement in the DB.
var create = function(req, res) {

  req.body.video = lambda.calculate( req.body.video ? req.body.video : {} );
  req.body.audio = lambda.calculate( req.body.audio ? req.body.audio : {} );
  Measurement.create(req.body, function(err, measurement) {
    if(err) { return handleError(res, err); }
    return res.json(201, measurement);
  });
};

exports.create = create;

// Updates an existing measurement in the DB.
exports.update = function(req, res) {

  if(req.body._id) { delete req.body._id; } // from original code generation

  Measurement.findOne( { "uid" : req.params.id } , function (err, measurement) {
    if (err || !measurement) {
      return create(req, res);
    }

    var newitem = { };
    var updated = { };
    if ( req.body.name ) {
	newitem = {
		name : ( req.body ? req.body.name : "" )
	};
    	updated = _.merge(measurement, newitem); // from original code generation
    } else {
	newitem = {
		video : { data : req.body.video ? ( req.body.video.data ? req.body.video.data : measurement.video.data ) : measurement.video.data } ,
		audio : { data : req.body.audio ? ( req.body.audio.data ? req.body.audio.data : measurement.audio.data ) : measurement.audio.data }
   	};
    	updated = _.merge(measurement, newitem); // from original code generation
    	if ( req.body.name ) {
	  console.log( "lambda.calculate(updated.video);" );
    	  lambda.calculate(updated.video);
    	  console.log( "lambda.calculate(updated.audio);" );
    	  lambda.calculate(updated.audio);
    	}
    }

    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, measurement);
    });
  });
};

// Deletes a measurement from the DB.
exports.destroy = function(req, res) {
  Measurement.findById(req.params.id, function (err, measurement) {
    if(err) { return handleError(res, err); }
    if(!measurement) { return res.send(404); }
    measurement.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
<commit_msg>Finally fix the calculation error<commit_after>/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /measurements              ->  index
 * POST    /measurements              ->  create
 * GET     /measurements/:id          ->  show
 * PUT     /measurements/:id          ->  update
 * DELETE  /measurements/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var Measurement = require('./measurement.model');
var lambda = require('./lambda');

// Get list of measurements
exports.index = function(req, res) {
  Measurement.find(function (err, measurements) {
    if(err) { return handleError(res, err); }
    return res.json(200, measurements);
  });
};

// Get a single measurement
exports.show = function(req, res) {
  Measurement.findOne( { "uid" : req.params.id } , function (err, measurement) {
    if(err) { return handleError(res, err); }
    if(!measurement) { return res.send(404); }
    return res.json(measurement);
  });
};

// Creates a new measurement in the DB.
var create = function(req, res) {

  req.body.video = lambda.calculate( req.body.video ? req.body.video : {} );
  req.body.audio = lambda.calculate( req.body.audio ? req.body.audio : {} );
  Measurement.create(req.body, function(err, measurement) {
    if(err) { return handleError(res, err); }
    return res.json(201, measurement);
  });
};

exports.create = create;

// Updates an existing measurement in the DB.
exports.update = function(req, res) {

  if(req.body._id) { delete req.body._id; } // from original code generation
  if(req.body.__v) { delete req.body.__v; } // from original code generation

  Measurement.findOne( { "uid" : req.params.id } , function (err, measurement) {
    if (err || !measurement) {
//      return create(req, res);
    }

    var newitem = { };
    var updated = { };
    if ( req.body.name ) {
	newitem = {
		name : ( req.body ? req.body.name : "" )
	};
    	updated = _.merge(measurement, newitem); // from original code generation
    } else {
	newitem = {
		video : { data : req.body.video ? ( req.body.video.data ? req.body.video.data : measurement.video.data ) : measurement.video.data } ,
		audio : { data : req.body.audio ? ( req.body.audio.data ? req.body.audio.data : measurement.audio.data ) : measurement.audio.data }
   	};
    	updated = _.merge(measurement, newitem); // from original code generation
        updated.video = lambda.calculate(updated.video);
        updated.audio = lambda.calculate(updated.audio);
    }

    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, updated);
    });
  });
};

// Deletes a measurement from the DB.
exports.destroy = function(req, res) {
  Measurement.findById(req.params.id, function (err, measurement) {
    if(err) { return handleError(res, err); }
    if(!measurement) { return res.send(404); }
    measurement.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
<|endoftext|>


<commit_before><commit_msg>Fix duplicate voices in Chromevox options page.<commit_after><|endoftext|>


<commit_before>var listesManager = listesManager || {};

(function($)
{
	listesManager.init = function()
	{
		this.btnSubmitCreating = $('#btn-submit-list'); // bouton de soumission du formulaire de création
		this.textNewListTitle = $('#add-list-name'); // input type text, champs titre de la nouvelle liste
		this.btnRemoveList = '.btn-remove-list';
		this.contentList = $('#details-liste');
		this.editing = false;

		this.initTooltip();
		this.observeSubmit();
		this.observeRemoveList();
		this.observeListDetailsDisplay();
		this.observeRemoveBookmarkFromList();
		this.observeEditingListTitle();
	};

	// Function to init tooltip on some btn
	listesManager.initTooltip = function()
	{
		$('.btn-tooltip').tooltip();
	};

	// Function to handle list add
	listesManager.observeSubmit = function()
	{
		this.btnSubmitCreating.on('click', function(e)
		{
			e.preventDefault();

			// Checking list name field filled
			if( listesManager.textNewListTitle.val() == '' || listesManager.textNewListTitle.val() == listesManager.textNewListTitle.attr('placeholder') )
			{
				listesManager.textNewListTitle.focus();
				return false;
			}

			listesManager.btnSubmitCreating.button('loading');
			$.ajax({
				url: listesManager.btnSubmitCreating.attr('href'),
				type: 'POST',
				dataType: 'json',
				data: {
					routeName: listesManager.btnSubmitCreating.attr('data-route'),
					listName: listesManager.textNewListTitle.val()
				},
				success: function(data)
				{
					$('#modal_add_list').modal('hide');
					listesManager.btnSubmitCreating.button('reset');
					if( data.success )
					{
						// Success message & refresh lists number
						alertify.success('La liste "'+ data.listName +'" a bien été créée.');
						$('#lists_number').html(data.listNumber);
						// Adding new list DOM if list shown > limitation
						if( $('.listes-content').find('.no-list').length > 0 )
						{
							$('.listes-content').html(data.html);
						} else
						{
							if( $('.listes-content').find('.une-liste').length < data.limitation )
								$('.listes-content').append(data.html);
						}
						listesManager.initTooltip();
					} else
					{
						alertify.error('Erreur lors de l\'ajout de la liste.');
					}
					listesManager.textNewListTitle.val('');
				}
			});
		});
	};

	// Function to handle a delete of a list
	listesManager.observeRemoveList = function()
	{
		$('.listes-content').on('click', this.btnRemoveList , function(e)
		{
			e.stopPropagation();
			e.preventDefault();
			// Cleaning block of list details and adding loader
			listesManager.contentList.empty().html( $('.ajax-loader-div-hidden').clone().removeClass('hide') );
			var btn_delete = $(this);
			$.ajax({
				url: btn_delete.attr('href'),
				dataType: 'json',
				type: 'POST',
				success: function(data)
				{
					if( data.success )
					{
						// Success message & refresh lists number
						alertify.success('La liste a bien été supprimée.');
						$('#lists_number').html( data.listNumber );
						// Cleaning block of list details and adding message
						listesManager.contentList.empty().html( data.message );
						// Removing DOM element
						btn_delete.closest('li').fadeOut(300, function()
						{
							$(this).remove();
						});
					} else
					{
						alertify.error('Erreur lors de la suppression de la liste.');
					}
				}
			});
		});
	};

	// Function to handle list details show
	listesManager.observeListDetailsDisplay = function()
	{
		$('.listes-content').on('click', 'li.une-liste', function(e)
		{
			e.stopPropagation();
			e.preventDefault();
			// Cleaning block of list details and adding loader
			listesManager.contentList.empty().html( $('.ajax-loader-div-hidden').clone().removeClass('hide') );
			$.ajax({
				url: $(this).attr('href'),
				type: 'POST',
				dataType: 'json',
				success: function(data)
				{
					if( data.success )
					{
						listesManager.contentList.empty().html(data.html);
						listesManager.initTooltip();
					}
					else
						alertify.error(data.error);
				}
			});
		});
	};

	// Function to handle deleting bookmark from list
	listesManager.observeRemoveBookmarkFromList = function()
	{
		$('#details-liste').on('click', '.btn-remove-bookmark-list', function(e)
		{
			e.preventDefault();
			e.stopPropagation();
			var bouton_suppr = $(this);
			var div_bookmark = bouton_suppr.closest('.bookmark-list');
			div_bookmark.fadeOut(300);
			$.ajax({
				url: bouton_suppr.attr('href'),
				type: 'POST',
				dataType: 'json',
				success: function(data)
				{
					if(data.success)
					{
						div_bookmark.remove();
						alertify.success(data.message);
					} else
						alertify.error(data.message);
				}
			});
		});
	};

	// Function to change DOM between click
	listesManager.handleEditingAction = function(bouton, $type)
	{
		if( $type === "editing" )
		{
			bouton.siblings('span.list-name').hide();
			//bouton.siblings('.input-submitting-list-name').show().focus();
			$('#list-input-edit-name').show().focus();
			bouton.find('i').hide();
			bouton.attr('data-action', 'submitting');
			listesManager.observeEditingSubmitListTitle();
		} else if( $type === "submitting")
		{
			bouton.siblings('span.list-name').show();
			$('#list-input-edit-name').hide();
			bouton.find('i').show();
			bouton.attr('data-action', 'editing');
		}
	};

	// Function to handle editing list title
	listesManager.observeEditingListTitle = function()
	{
		$('#details-liste').on('click', '.btn-edit-list-name', function(e)
		{
			e.preventDefault();
			e.stopPropagation();

			var $type = $(this).attr('data-action');
			listesManager.handleEditingAction( $(this), $type);
		});
	};

	// Fonction pour envoyer
	listesManager.observeEditingSubmitListTitle = function()
	{
		$('#list-input-edit-name').unbind('keypress');
		$('#list-input-edit-name').bind('keypress', function(e)
		{
			if(e.which === 13 && !listesManager.editing )
			{
				listesManager.editing = true;
				$('#img-loader-edit-name').show();
				$(this).attr('disabled', 'disabled');
				var input_text = $(this);
				$.ajax({
					url: basepath+"ajax/list/"+$(this).attr('data-id-list')+"/update/title",
					type: "POST",
					data: { 'name': $(this).val() },
					dataType: 'json',
					success: function(data)
					{
						if( data.success )
						{
							alertify.success(data.message);
							$('.list-name', $('#liste-'+input_text.attr('data-id-list'))).html(data.newName);
							input_text.siblings('.list-name').html(data.newName);
						} else
						{
							alertify.error(data.message);
						}
						input_text.removeAttr('disabled');
						listesManager.editing = false;
						listesManager.handleEditingAction(input_text.siblings('.btn-edit-list-name'), 'submitting');
						$('#img-loader-edit-name').hide();
					}
				});
			}
		});
	};

})(jQuery);

$(function()
{
	listesManager.init();
});
<commit_msg>JS comment & corrections<commit_after>var listesManager = listesManager || {};

(function($)
{
	listesManager.init = function()
	{
		this.btnSubmitCreating = $('#btn-submit-list'); // bouton de soumission du formulaire de création
		this.textNewListTitle = $('#add-list-name'); // input type text, champs titre de la nouvelle liste
		this.btnRemoveList = '.btn-remove-list';
		this.contentList = $('#details-liste');
		this.editing = false;

		this.initTooltip();
		this.observeSubmit();
		this.observeRemoveList();
		this.observeListDetailsDisplay();
		this.observeRemoveBookmarkFromList();
		this.observeEditingListTitle();
	};

	// Function to init tooltip on some btn
	listesManager.initTooltip = function()
	{
		$('.btn-tooltip').tooltip();
	};

	// Function to handle list add
	listesManager.observeSubmit = function()
	{
		this.btnSubmitCreating.on('click', function(e)
		{
			e.preventDefault();

			// Checking list name field filled
			if( listesManager.textNewListTitle.val() == '' || listesManager.textNewListTitle.val() == listesManager.textNewListTitle.attr('placeholder') )
			{
				listesManager.textNewListTitle.focus();
				return false;
			}

			listesManager.btnSubmitCreating.button('loading');
			$.ajax({
				url: listesManager.btnSubmitCreating.attr('href'),
				type: 'POST',
				dataType: 'json',
				data: {
					routeName: listesManager.btnSubmitCreating.attr('data-route'),
					listName: listesManager.textNewListTitle.val()
				},
				success: function(data)
				{
					$('#modal_add_list').modal('hide');
					listesManager.btnSubmitCreating.button('reset');
					if( data.success )
					{
						// Success message & refresh lists number
						alertify.success('La liste "'+ data.listName +'" a bien été créée.');
						$('#lists_number').html(data.listNumber);
						// Adding new list DOM if list shown > limitation
						if( $('.listes-content').find('.no-list').length > 0 )
						{
							$('.listes-content').html(data.html);
						} else
						{
							if( $('.listes-content').find('.une-liste').length < data.limitation )
								$('.listes-content').append(data.html);
						}
						listesManager.initTooltip();
					} else
					{
						alertify.error('Erreur lors de l\'ajout de la liste.');
					}
					listesManager.textNewListTitle.val('');
				}
			});
		});
	};

	// Function to handle a delete of a list
	listesManager.observeRemoveList = function()
	{
		$('.listes-content').on('click', this.btnRemoveList , function(e)
		{
			e.stopPropagation();
			e.preventDefault();
			// Cleaning block of list details and adding loader
			listesManager.contentList.empty().html( $('.ajax-loader-div-hidden').clone().removeClass('hide') );
			var btn_delete = $(this);
			$.ajax({
				url: btn_delete.attr('href'),
				dataType: 'json',
				type: 'POST',
				success: function(data)
				{
					if( data.success )
					{
						// Success message & refresh lists number
						alertify.success('La liste a bien été supprimée.');
						$('#lists_number').html( data.listNumber );
						// Cleaning block of list details and adding message
						listesManager.contentList.empty().html( data.message );
						// Removing DOM element
						btn_delete.closest('li').fadeOut(300, function()
						{
							$(this).remove();
						});
					} else
					{
						alertify.error('Erreur lors de la suppression de la liste.');
					}
				}
			});
		});
	};

	// Function to handle list details show
	listesManager.observeListDetailsDisplay = function()
	{
		$('.listes-content').on('click', 'li.une-liste', function(e)
		{
			e.stopPropagation();
			e.preventDefault();
			// Cleaning block of list details and adding loader
			listesManager.contentList.empty().html( $('.ajax-loader-div-hidden').clone().removeClass('hide') );
			$.ajax({
				url: $(this).attr('href'),
				type: 'POST',
				dataType: 'json',
				success: function(data)
				{
					if( data.success )
					{
						listesManager.contentList.empty().html(data.html);
						listesManager.initTooltip();
					}
					else
						alertify.error(data.error);
				}
			});
		});
	};

	// Function to handle deleting bookmark from list
	listesManager.observeRemoveBookmarkFromList = function()
	{
		$('#details-liste').on('click', '.btn-remove-bookmark-list', function(e)
		{
			e.preventDefault();
			e.stopPropagation();
			var bouton_suppr = $(this);
			var div_bookmark = bouton_suppr.closest('.bookmark-list');
			div_bookmark.fadeOut(300);
			$.ajax({
				url: bouton_suppr.attr('href'),
				type: 'POST',
				dataType: 'json',
				success: function(data)
				{
					if(data.success)
					{
						div_bookmark.remove();
						alertify.success(data.message);
					} else
						alertify.error(data.message);
				}
			});
		});
	};

	// Function to change DOM between click
	listesManager.handleEditingAction = function(bouton, $type)
	{
		if( $type === "editing" )
		{
			// Hide span / Show input
			bouton.siblings('span.list-name').hide();
			$('#list-input-edit-name').show().focus();
			bouton.find('i').hide();
			bouton.attr('data-action', 'submitting');
			// Listen keypress enter
			listesManager.observeEditingSubmitListTitle();
		} else if( $type === "submitting")
		{
			// Show span / Hide input
			bouton.siblings('span.list-name').show();
			$('#list-input-edit-name').hide();
			bouton.find('i').show();
			bouton.attr('data-action', 'editing');
		}
	};

	// Function to handle editing list title
	listesManager.observeEditingListTitle = function()
	{
		$('#details-liste').on('click', '.btn-edit-list-name', function(e)
		{
			e.preventDefault();
			e.stopPropagation();

			var $type = $(this).attr('data-action');
			listesManager.handleEditingAction( $(this), $type);
		});
	};

	// Fonction pour envoyer
	listesManager.observeEditingSubmitListTitle = function()
	{
		$('#list-input-edit-name').unbind('keypress');
		$('#list-input-edit-name').bind('keypress', function(e)
		{
			if(e.which === 13 && !listesManager.editing )
			{
				// Lock submit
				listesManager.editing = true;
				$(this).attr('disabled', 'disabled');
				// Show loader
				$('#img-loader-edit-name').show();
				var input_text = $(this);
				$.ajax({
					url: basepath+"ajax/list/"+$(this).attr('data-id-list')+"/update/title",
					type: "POST",
					data: { 'name': $(this).val() },
					dataType: 'json',
					success: function(data)
					{
						if( data.success )
						{
							alertify.success(data.message);
							// Refresh list name on DOM
							$('.list-name', $('#liste-'+input_text.attr('data-id-list'))).html(data.newName);
							input_text.siblings('.list-name').html(data.newName);
						} else
						{
							alertify.error(data.message);
						}
						input_text.removeAttr('disabled');
						// Unlock submit
						listesManager.editing = false;
						listesManager.handleEditingAction(input_text.siblings('.btn-edit-list-name'), 'submitting');
						$('#img-loader-edit-name').hide();
					}
				});
			}
		});
	};

})(jQuery);

$(function()
{
	listesManager.init();
});
<|endoftext|>


<commit_before>var $db = require(global.cwd + '/lib/mongo');
var $q = require('q');
var _sanitize = require('./lib/sanitize');

/* this method provides more data that .locate */
module.exports = function stats(game, player) {
    var defer = $q.defer();
    $db.get(game + '_players').findOne({name: _sanitize(player, true)}, function(err, player_data) {
        if (!player_data) return defer.reject();

        /* remove any sensitive data from response */
        delete player_data.uid;

        /* left join last 50 games */
        player_data.games = player_data.games.slice(-50);
        $db.get(game + '_games').find({idno: {$in: player_data.games}}, {sort: {date: -1}}, function(err, game_data) {
            if (game_data && game_data.length > 0) {
                game_data.forEach(function(stats, index) {
                    player_data.games[index] = stats;
                });
            }

            /* leaderboard position; todo make more efficient */
            player_data.rank = 0;
            var ladder = global.ladder[game] || [];
            for (var i = 0; i < ladder.length; i++) {
                if (ladder[i].name == player_data.name) {
                    player_data.rank = ladder[i].rank;
                    break;
                }
            }

            defer.resolve(player_data);
        });
    });

    return defer.promise;
};
<commit_msg>adding resiliency if player has no games<commit_after>var $db = require(global.cwd + '/lib/mongo');
var $q = require('q');
var _sanitize = require('./lib/sanitize');

/* this method provides more data that .locate */
module.exports = function stats(game, player) {
    var defer = $q.defer();
    $db.get(game + '_players').findOne({name: _sanitize(player, true)}, function(err, player_data) {
        if (!player_data) return defer.reject();
        player_data.games = player_data.games || [];

        /* remove any sensitive data from response */
        delete player_data.uid;

        /* left join last 50 games */
        player_data.games = player_data.games.slice(-50);
        if (player_data.games.length) {
            $db.get(game + '_games').find({idno: {$in: player_data.games}}, {sort: {date: -1}}, function (err, game_data) {
                if (game_data && game_data.length > 0) {
                    game_data.forEach(function (stats, index) {
                        player_data.games[index] = stats;
                    });
                }

                /* leaderboard position; todo make more efficient */
                player_data.rank = 0;
                var ladder = global.ladder[game] || [];
                for (var i = 0; i < ladder.length; i++) {
                    if (ladder[i].name == player_data.name) {
                        player_data.rank = ladder[i].rank;
                        break;
                    }
                }

                defer.resolve(player_data);
            });
        }
    });

    return defer.promise;
};
<|endoftext|>


<commit_before>import React from 'react';
import "babel-polyfill";
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../../actions/transactions';
import AddTransaction from '../Modals/AddTransaction.js'
import EditTransaction from '../Modals/EditTransaction.js'
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';

import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
} from 'material-ui/Table';

import styles from './styles.scss';

function mapStateToProps(state) {
  return {
    data: state.transactions.data,
    token: state.auth.token,
    loaded: state.transactions.loaded,
    isFetching: state.transactions.isFetching,
    selectedAccount: state.accounts.selectedAccount,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '400px',
  };

  fetchData(account_id=null) {
    if (account_id === null) {
      account_id = this.props.selectedAccount
    }
    if (account_id !== null)
    {
      const token = this.props.token
      this.props.fetchTransactionsData(token, account_id)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedAccount !== this.props.selectedAccount) {
      this.fetchData(nextProps.selectedAccount)
    }
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled,
    });
  };

  handleChange = (event) => {
    this.setState({height: event.target.value});
  };

  scrollToBottom() {
    if (this.refs.table !== undefined) {
      this.refs.table.refs.tableDiv.scrollTop = this.refs.table.refs.tableDiv.scrollHeight
    }
  }

  createTransaction( transaction ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.createTransaction(token, transaction));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  editTransaction( transaction ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.editTransaction(token, transaction));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  deleteTransaction( id ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.deleteTransaction(token, id));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  renderTransactionsList( transactions ) {
    transactions.sort((a,b) => {
      return new Date(a.date) - new Date(b.date);
    });
    // filter future recurring transactions
    transactions = transactions.filter((element) => {
      return element.recurring_group_id === null
      || (element.recurring_group_id !== null && new Date(element.date) <= new Date)
    })
    const rows = transactions.map((row, index) => {
      let credit = parseFloat(row.amount) < 0 ? '' : Number(row.amount).toFixed(2)
      let debit = parseFloat(row.amount) < 0 ? Number(row.amount).toFixed(2) : ''
      return (
        <TableRow key={row.transaction_id}>
          <TableHeaderColumn className={styles.smallColumn}>{row.date.toString()}</TableHeaderColumn>
          <TableHeaderColumn>{row.label}</TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}>{debit}</TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}>{credit}</TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}>
            <EditTransaction
              fields={row}
              editTransaction={this.editTransaction.bind(this)}
              deleteTransaction={this.deleteTransaction.bind(this)}
            />
          </TableHeaderColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    if (this.props.selectedAccount === undefined || this.props.selectedAccount === null) {
      return (

Select an account or create one.

      )
    }

    return (

      {!this.props.loaded
        ?
Loading data...

        :

            <TableHeader
              displaySelectAll={this.state.showCheckboxes}
              adjustForCheckbox={this.state.showCheckboxes}
              enableSelectAll={this.state.enableSelectAll}
            >
              <TableRow>
                <TableHeaderColumn className={styles.smallColumn}>Date</TableHeaderColumn>
                <TableHeaderColumn>Label</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Debit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Credit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}></TableHeaderColumn>
              </TableRow>
            </TableHeader>
            <TableBody
              displayRowCheckbox={this.state.showCheckboxes}
              deselectOnClickaway={this.state.deselectOnClickaway}
              showRowHover={this.state.showRowHover}
              stripedRows={this.state.stripedRows}
              style={{height: '100%'}}
            >
              {this.renderTransactionsList(this.props.data)}
            </TableBody>
            <TableFooter
              adjustForCheckbox={this.state.showCheckboxes}
            >
              <TableRow>
                <TableRowColumn colSpan="5">
                  <AddTransaction
                    selectedAccount={this.props.selectedAccount}
                    createTransaction={this.createTransaction.bind(this)} />
                </TableRowColumn>
              </TableRow>
            </TableFooter>

      }

    );
  }
}

TransactionsList.propTypes = {
  fetchTransactionsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
  selectedAccount: React.PropTypes.number,
};
<commit_msg>Use TableRowColumn for transactions list rows<commit_after>import React from 'react';
import "babel-polyfill";
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../../actions/transactions';
import AddTransaction from '../Modals/AddTransaction.js'
import EditTransaction from '../Modals/EditTransaction.js'
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';

import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
} from 'material-ui/Table';

import styles from './styles.scss';

function mapStateToProps(state) {
  return {
    data: state.transactions.data,
    token: state.auth.token,
    loaded: state.transactions.loaded,
    isFetching: state.transactions.isFetching,
    selectedAccount: state.accounts.selectedAccount,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '400px',
  };

  fetchData(account_id=null) {
    if (account_id === null) {
      account_id = this.props.selectedAccount
    }
    if (account_id !== null)
    {
      const token = this.props.token
      this.props.fetchTransactionsData(token, account_id)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedAccount !== this.props.selectedAccount) {
      this.fetchData(nextProps.selectedAccount)
    }
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled,
    });
  };

  handleChange = (event) => {
    this.setState({height: event.target.value});
  };

  scrollToBottom() {
    if (this.refs.table !== undefined) {
      this.refs.table.refs.tableDiv.scrollTop = this.refs.table.refs.tableDiv.scrollHeight
    }
  }

  createTransaction( transaction ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.createTransaction(token, transaction));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  editTransaction( transaction ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.editTransaction(token, transaction));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  deleteTransaction( id ) {
    const token = this.props.token;
    let call = async () =>
      await (await this.props.deleteTransaction(token, id));
    call()
      .then(() => {
        this.fetchData();
        this.props.updateBalance();
      })
  }

  renderTransactionsList( transactions ) {
    transactions.sort((a,b) => {
      return new Date(a.date) - new Date(b.date);
    });
    // filter future recurring transactions
    transactions = transactions.filter((element) => {
      return element.recurring_group_id === null
      || (element.recurring_group_id !== null && new Date(element.date) <= new Date)
    })
    const rows = transactions.map((row, index) => {
      let credit = parseFloat(row.amount) < 0 ? '' : Number(row.amount).toFixed(2)
      let debit = parseFloat(row.amount) < 0 ? Number(row.amount).toFixed(2) : ''
      return (
        <TableRow key={row.transaction_id}>
          <TableRowColumn className={styles.smallColumn}>{row.date.toString()}</TableRowColumn>
          <TableRowColumn>{row.label}</TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>{debit}</TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>{credit}</TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            <EditTransaction
              fields={row}
              editTransaction={this.editTransaction.bind(this)}
              deleteTransaction={this.deleteTransaction.bind(this)}
            />
          </TableRowColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    if (this.props.selectedAccount === undefined || this.props.selectedAccount === null) {
      return (

Select an account or create one.

      )
    }

    return (

      {!this.props.loaded
        ?
Loading data...

        :

            <TableHeader
              displaySelectAll={this.state.showCheckboxes}
              adjustForCheckbox={this.state.showCheckboxes}
              enableSelectAll={this.state.enableSelectAll}
            >
              <TableRow>
                <TableHeaderColumn className={styles.smallColumn}>Date</TableHeaderColumn>
                <TableHeaderColumn>Label</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Debit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Credit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}></TableHeaderColumn>
              </TableRow>
            </TableHeader>
            <TableBody
              displayRowCheckbox={this.state.showCheckboxes}
              deselectOnClickaway={this.state.deselectOnClickaway}
              showRowHover={this.state.showRowHover}
              stripedRows={this.state.stripedRows}
              style={{height: '100%'}}
            >
              {this.renderTransactionsList(this.props.data)}
            </TableBody>
            <TableFooter
              adjustForCheckbox={this.state.showCheckboxes}
            >
              <TableRow>
                <TableRowColumn colSpan="5">
                  <AddTransaction
                    selectedAccount={this.props.selectedAccount}
                    createTransaction={this.createTransaction.bind(this)} />
                </TableRowColumn>
              </TableRow>
            </TableFooter>

      }

    );
  }
}

TransactionsList.propTypes = {
  fetchTransactionsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
  selectedAccount: React.PropTypes.number,
};
<|endoftext|>


<commit_before>/*!
 * Backbone.keys.js v0.2.0
 * Copyright 2012, Raymond Julin (@nervetattoo)
 * backbone.keys.js may be freely distributed under the MIT license.
 */(function(e){"use strict";"function"==typeof define&&define.amd?define(["underscore","backbone","jquery"],e):e(_,Backbone,$)})(function(e,t){"use strict";var i=t.View.prototype.delegateEvents,n=t.View.prototype.undelegateEvents,s=function(e){return 1===e.length?e.toUpperCase().charCodeAt(0):r[e]},r={backspace:8,tab:9,enter:13,space:32,shift:16,ctrl:17,alt:18,meta:91,caps_lock:20,esc:27,num_lock:144,page_up:33,page_down:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,"delete":46,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,fslash:191};return e.each({options:"alt","return":"enter"},function(e,t){r[t]=r[e]}),t.View=t.View.extend({bindKeysOn:"keyup",_keyEventBindings:null,delegateEvents:function(){return i.apply(this,Array.prototype.slice.apply(arguments)),this.delegateKeys(),this},undelegateEvents:function(){return this.undelegateKeys(),n.apply(this,arguments),this},delegateKeys:function(t){return this.undelegateKeys(),this.bindTo=[],t=t||this.keys,t&&(e.each(t,function(t,i){var n={},s=i,r="";i.indexOf(" ")>=0&&(s=i.split(" ")[0],r=i.substring(i.indexOf(" ")+1));var o;o=e.isFunction(t)?t:e.isFunction(t.action)?t.action:t.action?this[t.action]:this[t],n.on=t.on||this.bindKeysOn,n.action=o,n.target=r,this.bindTo.push(n);var h=s.replace(/,/g," ");this.keyOn(h,n)},this),this.bindTo=e.uniq(this.bindTo,!1,function(e){return"on:"+e.on+"|target:"+e.target}),e.each(this.bindTo,function(t){var i={view:this,target:t.target};""!==t.target&&this.$el?this.$el.on(t.on,t.target,e.bind(this.triggerKey,i)):this.$el.on(t.on,e.bind(this.triggerKey,i))},this)),this},undelegateKeys:function(){return this._keyEventBindings={},this.$el&&(this.$el.off("keyup"),this.$el.off("keydown")),this.bindTo&&(e.each(this.bindTo,function(e){e&&this.$el&&this.$el.find(e.target).off(e.on)},this),this.bindTo=null),this},keyName:function(e){var t;for(t in r)if(r[t]===e)return t;return String.fromCharCode(e)},triggerKey:function(t){var i;return e.isObject(t)?i=t.which:e.isString(t)?i=s(t):e.isNumber(t)&&(i=t),"keydown"!==t.type||this.view.ctrlPressed||(this.view.ctrlPressed=t.ctrlKey),"keydown"!==t.type||this.view.altPressed||(this.view.altPressed=t.altKey),e(this.view._keyEventBindings[i]).each(function(i){if(i.target===this.target){var n=t.type===i.on;if(i.modifiers.length>0)n=n&&e(i.modifiers).all(function(e){return t[e+"Key"]===!0});else if(this.view.ctrlPressed||this.view.altPressed)return;if(n&&i.method){if(this.view.preventKeyboardAction===!0)return t.stopPropagation(),void 0;i.method(t,i.key)}}},this),"keyup"===t.type&&this.view.ctrlPressed&&(this.view.ctrlPressed=t.ctrlKey),"keyup"===t.type&&this.view.altPressed&&(this.view.altPressed=t.altKey),this.view},keyOn:function(t,i){t=t.split(" ");{if(!(t.length>1)){t=t.pop().toLowerCase();var n=t.split("+");t=n.shift();var r=s(t);return this._keyEventBindings.hasOwnProperty(r)||(this._keyEventBindings[r]=[]),this._keyEventBindings[r].push({key:t,modifiers:n||!1,method:i.action?e.bind(i.action,this):null,on:i.on,target:i.target}),this}for(var o=t.length;o--;)this.keyOn(t[o],i)}},keyOff:function(t,i){if(i=i||!1,null===t)return this._keyEventBindings={},this;var n=s(t);return e.isFunction(i)||(i=this[i]),i?(this._keyEventBindings[n]=e.filter(this._keyEventBindings[n],function(e){return e.method===i}),this):(this._keyEventBindings[n]=[],this)}}),t});<commit_msg>Minify for release<commit_after>/*!
 * Backbone.keys.js v1.0.0
 * Copyright 2012, Raymond Julin (@nervetattoo)
 * backbone.keys.js may be freely distributed under the MIT license.
 */(function(e){"use strict";"function"==typeof define&&define.amd?define(["underscore","backbone","jquery"],e):e(_,Backbone,$)})(function(e,t){"use strict";var i=t.View.prototype.delegateEvents,n=t.View.prototype.undelegateEvents,s=function(e){return 1===e.length?e.toUpperCase().charCodeAt(0):r[e]},r={backspace:8,tab:9,enter:13,space:32,shift:16,ctrl:17,alt:18,meta:91,caps_lock:20,esc:27,num_lock:144,page_up:33,page_down:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,"delete":46,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,fslash:191};return e.each({options:"alt","return":"enter"},function(e,t){r[t]=r[e]}),t.View=t.View.extend({bindKeysOn:"keyup",_keyEventBindings:null,delegateEvents:function(){return i.apply(this,Array.prototype.slice.apply(arguments)),this.delegateKeys(),this},undelegateEvents:function(){return this.undelegateKeys(),n.apply(this,arguments),this},delegateKeys:function(t){return this.undelegateKeys(),this.bindTo=[],t=t||this.keys,t&&(e.each(t,function(t,i){var n={},s=i,r="";i.indexOf(" ")>=0&&(s=i.split(" ")[0],r=i.substring(i.indexOf(" ")+1));var o;o=e.isFunction(t)?t:e.isFunction(t.action)?t.action:t.action?this[t.action]:this[t],n.on=t.on||this.bindKeysOn,n.action=o,n.target=r,this.bindTo.push(n);var h=s.replace(/,/g," ");this.keyOn(h,n)},this),this.bindTo=e.uniq(this.bindTo,!1,function(e){return"on:"+e.on+"|target:"+e.target}),e.each(this.bindTo,function(t){var i={view:this,target:t.target};""!==t.target&&this.$el?this.$el.on(t.on,t.target,e.bind(this.triggerKey,i)):this.$el.on(t.on,e.bind(this.triggerKey,i))},this)),this},undelegateKeys:function(){return this._keyEventBindings={},this.$el&&(this.$el.off("keyup"),this.$el.off("keydown")),this.bindTo&&(e.each(this.bindTo,function(e){e&&this.$el&&this.$el.find(e.target).off(e.on)},this),this.bindTo=null),this},keyName:function(e){var t;for(t in r)if(r[t]===e)return t;return String.fromCharCode(e)},triggerKey:function(t){var i;return e.isObject(t)?i=t.which:e.isString(t)?i=s(t):e.isNumber(t)&&(i=t),"keydown"!==t.type||this.view.ctrlPressed||(this.view.ctrlPressed=t.ctrlKey),"keydown"!==t.type||this.view.altPressed||(this.view.altPressed=t.altKey),e(this.view._keyEventBindings[i]).each(function(i){if(i.target===this.target){var n=t.type===i.on;if(i.modifiers.length>0)n=n&&e(i.modifiers).all(function(e){return t[e+"Key"]===!0});else if(this.view.ctrlPressed||this.view.altPressed)return;if(n&&i.method){if(this.view.preventKeyboardAction===!0)return t.stopPropagation(),void 0;i.method(t,i.key)}}},this),"keyup"===t.type&&this.view.ctrlPressed&&(this.view.ctrlPressed=t.ctrlKey),"keyup"===t.type&&this.view.altPressed&&(this.view.altPressed=t.altKey),this.view},keyOn:function(t,i){t=t.split(" ");{if(!(t.length>1)){t=t.pop().toLowerCase();var n=t.split("+");t=n.shift();var r=s(t);return this._keyEventBindings.hasOwnProperty(r)||(this._keyEventBindings[r]=[]),this._keyEventBindings[r].push({key:t,modifiers:n||!1,method:i.action?e.bind(i.action,this):null,on:i.on,target:i.target}),this}for(var o=t.length;o--;)this.keyOn(t[o],i)}},keyOff:function(t,i){if(i=i||!1,null===t)return this._keyEventBindings={},this;var n=s(t);return e.isFunction(i)||(i=this[i]),i?(this._keyEventBindings[n]=e.filter(this._keyEventBindings[n],function(e){return e.method===i}),this):(this._keyEventBindings[n]=[],this)}}),t});<|endoftext|>


<commit_before>var prolific = require('prolific')
var abend = require('abend')
var Isochronous = require('isochronous')

exports.createShuttle = function (net, Shuttle) {
    return function (program, interval, parameters, finale) {
        if (arguments.length == 3) {
            finale = parameters
            parameters = {}
        }
        if (program.env.PROLIFIC_CONFIGURATION != null) {
// TODO Maybe delete and internalize?
            var configuration = JSON.parse(program.env.PROLIFIC_CONFIGURATION)
            var pipe = new net.Socket({ fd: configuration.fd  })
            var shuttle = new Shuttle(pipe, pipe, program.stderr, finale)
            shuttle.queue.write(new Buffer(JSON.stringify(parameters) + '\n'))
            prolific.sink = shuttle.queue
            program.on('uncaughtException', shuttle.uncaughtException.bind(shuttle))
            program.on('exit', shuttle.stop.bind(shuttle))
            var isochronous = new Isochronous({
                operation: { object: shuttle.queue, method: 'flush' },
                interval: interval,
                unref: true
            })
            program.on('exit', isochronous.stop.bind(isochronous))
            isochronous.run(abend)
        }
    }
}
<commit_msg>Question about interval.<commit_after>var prolific = require('prolific')
var abend = require('abend')
var Isochronous = require('isochronous')

exports.createShuttle = function (net, Shuttle) {
// TODO Is the interval necessary? Just flush constantly. Use Reactor (as heavy
// as Isochronous.)
    return function (program, interval, parameters, finale) {
        if (arguments.length == 3) {
            finale = parameters
            parameters = {}
        }
        if (program.env.PROLIFIC_CONFIGURATION != null) {
// TODO Maybe delete and internalize?
            var configuration = JSON.parse(program.env.PROLIFIC_CONFIGURATION)
            var pipe = new net.Socket({ fd: configuration.fd  })
            var shuttle = new Shuttle(pipe, pipe, program.stderr, finale)
            shuttle.queue.write(new Buffer(JSON.stringify(parameters) + '\n'))
            prolific.sink = shuttle.queue
            program.on('uncaughtException', shuttle.uncaughtException.bind(shuttle))
            program.on('exit', shuttle.stop.bind(shuttle))
            var isochronous = new Isochronous({
                operation: { object: shuttle.queue, method: 'flush' },
                interval: interval,
                unref: true
            })
            program.on('exit', isochronous.stop.bind(isochronous))
            isochronous.run(abend)
        }
    }
}
<|endoftext|>


<commit_before>const path = require('path');
const config = require('../config');
const webpackHelpers = require('./webpackHelpers');

const projectRoot = path.resolve(__dirname, '../');
const isDevelopment = process.env.NODE_ENV == 'development';
const eslintLoaderEnabled = isDevelopment ? config.dev.enableESLintLoader : config.build.enableESLintLoader;
const tslintLoaderEnabled = isDevelopment ? config.dev.enableTSLintLoader : config.build.enableTSLintLoader;

module.exports = {
	entry: {
		app: './src/bootstrap.js'
	},
	output: {
		path: path.join(projectRoot, 'dist'),
		publicPath: '/',
		filename: '[name].js',
		chunkFilename : '[id].js'
	},
	resolve: {
		extensions: ['.vue', '.js', '.ts', '.scss'],
		modules: [path.join(projectRoot, 'src'), path.join(projectRoot, 'node_modules')],
		alias: {
			'modernizr$': path.join(projectRoot, '.modernizrrc'),
			'TweenLite': path.resolve(projectRoot, 'node_modules/gsap/src/uncompressed/TweenLite'),
		}
	},
	module: {
		rules: [
			{
				test: /\.js$/,
				use: [
					webpackHelpers.getBabelLoaderConfig(isDevelopment)
				],
				include: [
					path.join(projectRoot, 'src')
				],
				exclude: /node_modules/
			},
			{
				test: /\.modernizrrc$/,
				loader: 'modernizr-loader!json-loader'
			},
			webpackHelpers.getESLintLoader(eslintLoaderEnabled, projectRoot),
			{
				test: /\.ts$/,
				include: [
					path.join(projectRoot, 'src')
				],
				use: [
					webpackHelpers.getBabelLoaderConfig(isDevelopment),
					{
						loader: 'awesome-typescript-loader',
						options: {
							configFileName: path.resolve(__dirname, '../tsconfig.json'),
						},
					},
				]
			},
			webpackHelpers.getTSLintLoader(tslintLoaderEnabled, projectRoot),
			{
				test: /\.svg$/,
				loader: 'svg-inline-loader'
			}
		]
	}
};

<commit_msg>add raw-loader config for shaders and text files<commit_after>const path = require('path');
const config = require('../config');
const webpackHelpers = require('./webpackHelpers');

const projectRoot = path.resolve(__dirname, '../');
const isDevelopment = process.env.NODE_ENV == 'development';
const eslintLoaderEnabled = isDevelopment ? config.dev.enableESLintLoader : config.build.enableESLintLoader;
const tslintLoaderEnabled = isDevelopment ? config.dev.enableTSLintLoader : config.build.enableTSLintLoader;

module.exports = {
	entry: {
		app: './src/bootstrap.js'
	},
	output: {
		path: path.join(projectRoot, 'dist'),
		publicPath: '/',
		filename: '[name].js',
		chunkFilename : '[id].js'
	},
	resolve: {
		extensions: ['.vue', '.js', '.ts', '.scss'],
		modules: [path.join(projectRoot, 'src'), path.join(projectRoot, 'node_modules')],
		alias: {
			'modernizr$': path.join(projectRoot, '.modernizrrc'),
			'TweenLite': path.resolve(projectRoot, 'node_modules/gsap/src/uncompressed/TweenLite'),
		}
	},
	module: {
		rules: [
			{
				test: /\.js$/,
				use: [
					webpackHelpers.getBabelLoaderConfig(isDevelopment)
				],
				include: [
					path.join(projectRoot, 'src')
				],
				exclude: /node_modules/
			},
			{
				test: /\.modernizrrc$/,
				loader: 'modernizr-loader!json-loader'
			},
			{
				test: /\.(glsl|txt)$/,
				use: 'raw-loader'
			},
			webpackHelpers.getESLintLoader(eslintLoaderEnabled, projectRoot),
			{
				test: /\.ts$/,
				include: [
					path.join(projectRoot, 'src')
				],
				use: [
					webpackHelpers.getBabelLoaderConfig(isDevelopment),
					{
						loader: 'awesome-typescript-loader',
						options: {
							configFileName: path.resolve(__dirname, '../tsconfig.json'),
						},
					},
				]
			},
			webpackHelpers.getTSLintLoader(tslintLoaderEnabled, projectRoot),
			{
				test: /\.svg$/,
				loader: 'svg-inline-loader'
			}
		]
	}
};

<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import { Icon } from 'react-fa'
import { links, externalLinks } from '../meta/nav'

export default class MenuContent extends React.Component {
  render () {
    return (

            {links.map(link =>

                <Link to={link.url} className="adj-menu-item-link adj-link-unstyled" onClick={this.props.onLinkClick}>
                  <Icon name={link.icon}  className="adj-menu-item-icon" />
                  {link.name}
                </Link>

            )}

            {externalLinks.map(link =>

                <Link to={prefixLink(link.url)} className="adj-menu-item-link adj-link-unstyled" target="_blank">
                  <Icon name={link.icon} className="adj-menu-item-icon" />
                  {link.name}
                </Link>

            )}

    )
  }
}
<commit_msg>Don't prefix external links in menu.<commit_after>import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import { Icon } from 'react-fa'
import { links, externalLinks } from '../meta/nav'

export default class MenuContent extends React.Component {
  render () {
    return (

            {links.map(link =>

                <Link to={link.url} className="adj-menu-item-link adj-link-unstyled" onClick={this.props.onLinkClick}>
                  <Icon name={link.icon}  className="adj-menu-item-icon" />
                  {link.name}
                </Link>

            )}

            {externalLinks.map(link =>

                <Link to={link.url} className="adj-menu-item-link adj-link-unstyled" target="_blank">
                  <Icon name={link.icon} className="adj-menu-item-icon" />
                  {link.name}
                </Link>

            )}

    )
  }
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

module.exports = function() {
  var dbName = 'mongodb://172.23.238.253:27018/nginx'
  //var dbName = 'mongodb://localhost/sampleData'
  var db = mongoose.connect(dbName);

  require('./models/log.server.model');
  require('./models/log.config.model');
  require('./models/log.user.model');

  return db;
}
<commit_msg>small changes<commit_after>var mongoose = require('mongoose');

module.exports = function() {
  //var dbName = 'mongodb://172.23.238.253:27018/nginx'
  var dbName = 'mongodb://localhost/sampleData'
  var db = mongoose.connect(dbName);

  require('./models/log.server.model');
  require('./models/log.config.model');
  require('./models/log.user.model');

  return db;
}
<|endoftext|>