<commit_before>'use strict';
var utils = require('../../lib').utils;

function mergeCommonFields(params, commonFields) {
	var _params = utils.cloneObj(params);
	delete _params.commonFields;

	// Extend _params with commonFields
	params.commonFields.forEach(function(field) {
		_params[field] = commonFields[field];
	});

	return _params;
}

function castType(value, type, cfg) {
	switch(type) {
		case 'string':
		case 'integer':
		case 'number':
		case 'boolean':
		case 'regexp':
			value = castTypeSimpleData(value, type);
			break;
		case 'array':
			doArray(value, cfg.items);
			break;
		case 'object':
			doObject(value, cfg);
			break;
		default:
			break;
	}
	return value;

	function doArray(arr, cfg) {
		if(cfg) {
			for(var i = 0; i < arr.length; i++) {
				if(cfg.type) {
					if(cfg.type === 'array' && cfg.items) {
						doArray(arr[i], cfg.items);
					}
					else if(cfg.type === 'object' && cfg) {
						doObject(arr[i], cfg);
					}
					else {
						arr[i] = castTypeSimpleData(arr[i], cfg.type);
					}
				}
			}
		}
	}

	function doObject(obj, cfg) {
		var objCfg =null;
		if(cfg && (cfg.properties || (cfg.additionalProperties && typeof(cfg.additionalProperties) === 'object') )) {
			objCfg = cfg.properties || cfg.additionalProperties;
			for(var key in obj) {
				if(obj.hasOwnProperty(key)) {
					if(objCfg[key].type === 'array') {
						doArray(obj[key], objCfg[key].items);
					}
					else if(objCfg[key].type === 'object' || objCfg[key].patternProperties) {
						doObject(obj[key], objCfg[key]);
					}
					else if(objCfg[key].type) {
						obj[key] = castTypeSimpleData(obj[key], objCfg[key].type);
					}
				}
			}
		}
		if(cfg && (cfg.patternProperties && typeof(cfg.patternProperties) === 'object')) {
			objCfg = cfg.patternProperties;
			var patterns = Object.keys(objCfg);
			for(var i =0; i < patterns.length; i++){
				var regexp = new RegExp(patterns[i]);
				for(var key2 in obj){
					if(obj.hasOwnProperty(key2)){
						if(regexp.test(key2)){
							doObject(obj[key2], objCfg[patterns[i]]);
						}
					}
				}
			}
		}
	}

	function castTypeSimpleData(value, type) {
		var castedValue = null;
		try {
			switch(type) {
				case 'string':
					castedValue = value.toString();
					break;
				case 'integer':
					castedValue = parseInt(value, 10);
					break;
				case 'number':
					castedValue = parseFloat(value);
					break;
				case 'boolean':
					castedValue = (value.toString() === 'true');
					break;
				case 'regexp':
					castedValue = new RegExp(value);
					break;
				default:
					break;
			}
		} catch(ex) {
			castedValue = value;
		}
		return (castedValue !== null) ? castedValue : value;
	}
}

module.exports = {
	mapFormatAndValidate: function(obj, cb) {
		var sources = {};

		var sourceProblem = false;
		if(!obj.req || typeof obj.req !== "object") {
			sourceProblem = true;
		}
		for(var i = 0; i < obj.inputmaskSrc.length; i++) {
			if(obj.req.hasOwnProperty(obj.inputmaskSrc[i])) {
				sources[obj.inputmaskSrc[i]] = utils.cloneObj(obj.req[obj.inputmaskSrc[i]]);
				if(typeof sources[obj.inputmaskSrc[i]] !== "object") {
					sourceProblem = true;
				}
			}
			else {
				sourceProblem = true;
			}
		}
		if(sourceProblem) {
			return cb({"code": 171, "msg": "request does not have all the sources needed: " + obj.inputmaskSrc});
		}

		sources['servicesConfig'] = (obj.req.soajs && obj.req.soajs.servicesConfig) ? obj.req.soajs.servicesConfig : {};
		sources['clientIP'] = ( obj.req.getClientIP && obj.req.getClientIP() ) || {};
		sources['session'] = (obj.req.soajs && obj.req.soajs.session) ? obj.req.soajs.session.getSERVICE() : {};

		var params = obj.config.schema[obj.apiName];

		if(utils.validProperty(params, 'commonFields')) {
			params = mergeCommonFields(params, obj.config.schema.commonFields);
		}

		var data = {};
		var err = null;
		var errors = [];

		for(var param in params) {
			var force = false;
			if(params.hasOwnProperty(param)) {
				var fetched;
				var paramConfig = params[param];
				if(params[param].source && params[param].source.some(function(source) {
						var path = source.split("."), pathLength = path.length, traversed = sources;
						if(path[0] === 'query'){ force = true; }
						var next = path.shift();
						while(next) {
							if(traversed.hasOwnProperty(next)) {
								traversed = traversed[next];
								next = path.shift();
							}
							else {
								return;
							}
						}
						if(pathLength === 1) {
							if(traversed.hasOwnProperty(param)) {
								traversed = traversed[param];
							} else {
								return;
							}
						}

						fetched = traversed;
						return fetched != null;
					})) {
					data[param] = fetched;
					var validation;
					var type = paramConfig.validation.type;

					//apply type casting if headers content-type is not JSON, otherwise inputs are received as strings
					if(force || !obj.req.headers['content-type'] || obj.req.headers['content-type'].indexOf('application/json') === -1) {
						data[param] = castType(data[param], type, paramConfig.validation);
					}

					if(utils.validProperty(paramConfig, "validation")) {
						if(!(validation = obj.configValidator.validate(data[param], paramConfig.validation)).valid) {
							if(!err) {
								err = {};
							}
							if(err[173]) {
								err[173] += ", " + param;
							} else {
								err[173] = "Validation failed for field: " + param;
								validation.errors.forEach(function(validationErr) {
									err[173] += " -> The parameter '" + param + "' " + validationErr.message;
								});
							}
						}
					}
				}
				else {
					if(paramConfig.hasOwnProperty("default")) {
						data[param] = paramConfig.default;
					} else {
						if(!utils.validProperty(paramConfig, "required") || !paramConfig.required) {
							continue;
						}
						if(!err) {
							err = {};
						}
						if(err[172]) {
							err[172] += ", " + param;
						} else {
							err [172] = "Missing required field: " + param;
						}
					}
				}
			}
		}
		if(err) {
			for(var e in err) {
				if(err.hasOwnProperty(e)) {
					errors.push({"code": Number(e), "msg": err[e]});
				}
			}
		}
		if(errors.length === 0) {
			errors = null;
		}
		return cb(errors, data);
	}
};<commit_msg>assured req object<commit_after>'use strict';
var utils = require('../../lib').utils;

function mergeCommonFields(params, commonFields) {
	var _params = utils.cloneObj(params);
	delete _params.commonFields;

	// Extend _params with commonFields
	params.commonFields.forEach(function(field) {
		_params[field] = commonFields[field];
	});

	return _params;
}

function castType(value, type, cfg) {
	switch(type) {
		case 'string':
		case 'integer':
		case 'number':
		case 'boolean':
		case 'regexp':
			value = castTypeSimpleData(value, type);
			break;
		case 'array':
			doArray(value, cfg.items);
			break;
		case 'object':
			doObject(value, cfg);
			break;
		default:
			break;
	}
	return value;

	function doArray(arr, cfg) {
		if(cfg) {
			for(var i = 0; i < arr.length; i++) {
				if(cfg.type) {
					if(cfg.type === 'array' && cfg.items) {
						doArray(arr[i], cfg.items);
					}
					else if(cfg.type === 'object' && cfg) {
						doObject(arr[i], cfg);
					}
					else {
						arr[i] = castTypeSimpleData(arr[i], cfg.type);
					}
				}
			}
		}
	}

	function doObject(obj, cfg) {
		var objCfg =null;
		if(cfg && (cfg.properties || (cfg.additionalProperties && typeof(cfg.additionalProperties) === 'object') )) {
			objCfg = cfg.properties || cfg.additionalProperties;
			for(var key in obj) {
				if(obj.hasOwnProperty(key)) {
					if(objCfg[key].type === 'array') {
						doArray(obj[key], objCfg[key].items);
					}
					else if(objCfg[key].type === 'object' || objCfg[key].patternProperties) {
						doObject(obj[key], objCfg[key]);
					}
					else if(objCfg[key].type) {
						obj[key] = castTypeSimpleData(obj[key], objCfg[key].type);
					}
				}
			}
		}
		if(cfg && (cfg.patternProperties && typeof(cfg.patternProperties) === 'object')) {
			objCfg = cfg.patternProperties;
			var patterns = Object.keys(objCfg);
			for(var i =0; i < patterns.length; i++){
				var regexp = new RegExp(patterns[i]);
				for(var key2 in obj){
					if(obj.hasOwnProperty(key2)){
						if(regexp.test(key2)){
							doObject(obj[key2], objCfg[patterns[i]]);
						}
					}
				}
			}
		}
	}

	function castTypeSimpleData(value, type) {
		var castedValue = null;
		try {
			switch(type) {
				case 'string':
					castedValue = value.toString();
					break;
				case 'integer':
					castedValue = parseInt(value, 10);
					break;
				case 'number':
					castedValue = parseFloat(value);
					break;
				case 'boolean':
					castedValue = (value.toString() === 'true');
					break;
				case 'regexp':
					castedValue = new RegExp(value);
					break;
				default:
					break;
			}
		} catch(ex) {
			castedValue = value;
		}
		return (castedValue !== null) ? castedValue : value;
	}
}

module.exports = {
	mapFormatAndValidate: function(obj, cb) {
		var sources = {};

		var sourceProblem = false;
		if(!obj.req || typeof obj.req !== "object") {
			sourceProblem = true;
		}
        else {
            for (var i = 0; i < obj.inputmaskSrc.length; i++) {
                if (obj.req.hasOwnProperty(obj.inputmaskSrc[i])) {
                    sources[obj.inputmaskSrc[i]] = utils.cloneObj(obj.req[obj.inputmaskSrc[i]]);
                    if (typeof sources[obj.inputmaskSrc[i]] !== "object") {
                        sourceProblem = true;
                    }
                }
                else {
                    sourceProblem = true;
                }
            }
        }
		if(sourceProblem) {
			return cb({"code": 171, "msg": "request does not have all the sources needed: " + obj.inputmaskSrc});
		}

		sources['servicesConfig'] = (obj.req.soajs && obj.req.soajs.servicesConfig) ? obj.req.soajs.servicesConfig : {};
		sources['clientIP'] = ( obj.req.getClientIP && obj.req.getClientIP() ) || {};
		sources['session'] = (obj.req.soajs && obj.req.soajs.session) ? obj.req.soajs.session.getSERVICE() : {};

		var params = obj.config.schema[obj.apiName];

		if(utils.validProperty(params, 'commonFields')) {
			params = mergeCommonFields(params, obj.config.schema.commonFields);
		}

		var data = {};
		var err = null;
		var errors = [];

		for(var param in params) {
			var force = false;
			if(params.hasOwnProperty(param)) {
				var fetched;
				var paramConfig = params[param];
				if(params[param].source && params[param].source.some(function(source) {
						var path = source.split("."), pathLength = path.length, traversed = sources;
						if(path[0] === 'query'){ force = true; }
						var next = path.shift();
						while(next) {
							if(traversed.hasOwnProperty(next)) {
								traversed = traversed[next];
								next = path.shift();
							}
							else {
								return;
							}
						}
						if(pathLength === 1) {
							if(traversed.hasOwnProperty(param)) {
								traversed = traversed[param];
							} else {
								return;
							}
						}

						fetched = traversed;
						return fetched != null;
					})) {
					data[param] = fetched;
					var validation;
					var type = paramConfig.validation.type;

					//apply type casting if headers content-type is not JSON, otherwise inputs are received as strings
					if(force || !obj.req.headers['content-type'] || obj.req.headers['content-type'].indexOf('application/json') === -1) {
						data[param] = castType(data[param], type, paramConfig.validation);
					}

					if(utils.validProperty(paramConfig, "validation")) {
						if(!(validation = obj.configValidator.validate(data[param], paramConfig.validation)).valid) {
							if(!err) {
								err = {};
							}
							if(err[173]) {
								err[173] += ", " + param;
							} else {
								err[173] = "Validation failed for field: " + param;
								validation.errors.forEach(function(validationErr) {
									err[173] += " -> The parameter '" + param + "' " + validationErr.message;
								});
							}
						}
					}
				}
				else {
					if(paramConfig.hasOwnProperty("default")) {
						data[param] = paramConfig.default;
					} else {
						if(!utils.validProperty(paramConfig, "required") || !paramConfig.required) {
							continue;
						}
						if(!err) {
							err = {};
						}
						if(err[172]) {
							err[172] += ", " + param;
						} else {
							err [172] = "Missing required field: " + param;
						}
					}
				}
			}
		}
		if(err) {
			for(var e in err) {
				if(err.hasOwnProperty(e)) {
					errors.push({"code": Number(e), "msg": err[e]});
				}
			}
		}
		if(errors.length === 0) {
			errors = null;
		}
		return cb(errors, data);
	}
};<|endoftext|>


<commit_before>$(document).ready(function() {
  $('.like-btn').show();

  $('.post-like').on('ajax:success', function(event, data) {
    var like_button = $('#post-' + data.id + ' .post-like');
    var like_badge = $('#post-'+ data.id + ' .like-badge');

    $('#post-' + data.id + ' .like-count').text(data.like_count);
    if (data.liked_by_member) {
      like_badge.addClass('liked');
      like_button.data('method', 'delete');
      like_button.attr('href', data.url);
      like_button.text('Unlike');
    } else {
      like_badge.removeClass('liked');
      like_button.data('method', 'post');
      like_button.attr('href', '/likes.json?post_id=' + data.id);
      like_button.text('Like');
    }
  });

  $('.photo-like').on('ajax:success', function(event, data) {
    var like_badge = $('#photo-'+ data.id + ' .like-badge');
    var like_button = $('#photo-'+ data.id + ' .like-btn');

    $('#photo-' + data.id + ' .like-count').text(data.like_count);
    if (data.liked_by_member) {
      like_badge.addClass('liked');
      // Turn the button into an unlike button
      like_button.data('method', 'delete');
      like_button.attr('href', data.url);
    } else {
      like_badge.removeClass('liked');
      // Turn the button into an *like* button
      like_button.data('method', 'post');
      like_button.attr('href', '/likes.json?photo_id=' + data.id);
    }
  });
});
<commit_msg>Use camel case in js<commit_after>$(document).ready(function() {
  $('.like-btn').show();

  $('.post-like').on('ajax:success', function(event, data) {
    var likeButton = $('#post-' + data.id + ' .post-like');
    var likeBadge = $('#post-'+ data.id + ' .like-badge');

    $('#post-' + data.id + ' .like-count').text(data.like_count);
    if (data.liked_by_member) {
      likeBadge.addClass('liked');
      likeButton.data('method', 'delete');
      likeButton.attr('href', data.url);
      likeButton.text('Unlike');
    } else {
      likeBadge.removeClass('liked');
      likeButton.data('method', 'post');
      likeButton.attr('href', '/likes.json?post_id=' + data.id);
      likeButton.text('Like');
    }
  });

  $('.photo-like').on('ajax:success', function(event, data) {
    var likeBadge = $('#photo-'+ data.id + ' .like-badge');
    var likeButton = $('#photo-'+ data.id + ' .like-btn');

    $('#photo-' + data.id + ' .like-count').text(data.like_count);
    if (data.liked_by_member) {
      likeBadge.addClass('liked');
      // Turn the button into an unlike button
      likeButton.data('method', 'delete');
      likeButton.attr('href', data.url);
    } else {
      likeBadge.removeClass('liked');
      // Turn the button into an *like* button
      likeButton.data('method', 'post');
      likeButton.attr('href', '/likes.json?photo_id=' + data.id);
    }
  });
});
<|endoftext|>


<commit_before>oT.backup = {};

oT.backup.openPanel = function(){
    oT.backup.populatePanel();
    $('.backup-window').height( $('.textbox-container').height() * (3/5) );
    $('.backup-panel').fadeIn('fast');
}

oT.backup.closePanel = function(){
    $('.backup-panel').fadeOut('fast',function(){
        $('.backup-window').empty();

    });
}

oT.backup.generateBlock = function(ref){
    // create icon and 'restore' button
    var text = localStorage.getItem(ref);
    var timestamp = ref.replace('oTranscribe-backup-','');
    var date = oT.backup.formatDate(timestamp);

    var block = document.createElement('div');
    var doc = document.createElement('div');
    var restoreButton = document.createElement('div');

    block.className = 'backup-block';
    doc.className = 'backup-doc';
    restoreButton.className = 'backup-restore-button';

    doc.innerHTML = text;
    restoreButton.innerHTML = date+' - restore';
    block.appendChild(doc);
    block.appendChild(restoreButton);

    return block;
}

oT.backup.formatDate = function(timestamp){
    var d = new Date( parseFloat(timestamp) );
    var day =  d.getDate() + '/' + (d.getMonth()+1);
    var now = new Date();
    today = now.getDate() + '/' + (now.getMonth()+1);
    yesterday = (now.getDate()-1) + '/' + (now.getMonth()+1);
    if (day === today) {
        day = 'Today';
    } else if (day === yesterday) {
        day = 'Yesterday'
    }
    var time = d.getHours() + ':';
    if (d.getMinutes() < 10) {
        time += '0';
    }
    time += d.getMinutes();

    formattedDate = day + ' ' + time;
    return formattedDate;
}

oT.backup.populatePanel = function(){
    oT.backup.addDocsToPanel(0,8);
    if (oT.backup.list().length === 0) {
        $('.backup-window').append( '
No backups found.
' );
    }
}

oT.backup.addDocsToPanel = function(start,end){
    $('.more-backups').remove();
    var allDocs = oT.backup.list();
    docs = allDocs.slice(start,end);
    for (var i = 0; i < docs.length; i++) {
        $('.backup-window').append( oT.backup.generateBlock(docs[i]) );
    }
    if (allDocs[end]) {
        $('.backup-window').append( '
Load older backups
' );
    }
}

oT.backup.save = function(){
    // save current text to timestamped localStorage item
    var text = document.getElementById("textbox");
    var timestamp = new Date().getTime();
    oT.backup.saveToLocalStorage('oTranscribe-backup-'+timestamp, text.innerHTML);
    // and bleep icon
    $('.sbutton.backup').addClass('flash');
    setTimeout(function(){
        $('.sbutton.backup').removeClass('flash');
    },1000);
    // and add to tray
    var newBlock = oT.backup.generateBlock('oTranscribe-backup-'+timestamp);
    newBlock.className += ' new-block';
    $('.backup-window').prepend( newBlock );
    $( newBlock ).animate({
        'opacity': 1,
        'width': '25%'
    },'slow',function(){
        $( newBlock ).find('.backup-restore-button').fadeIn();
    });

}

oT.backup.saveToLocalStorage = function(name){
    console.log(name);
    try {
       localStorage.setItem( name );
    } catch (e) {
        console.log('error');
       if(e.name === "NS_ERROR_DOM_QUOTA_REACHED") {
           oT.backup.removeOldest();
           // oT.backup.save();
       }
    }

}

oT.backup.init = function(){
    setInterval(function(){
        oT.backup.save();
        oT.backup.cleanup();
    },300000 /* 5 minutes */);
}

oT.backup.list = function(){
    var result = [];
    for (var i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i).indexOf('oTranscribe-backup') > -1) {
            result.push(localStorage.key(i));
        }
    }
    return result.sort().reverse();
}

oT.backup.restore = function(timestamp){
    oT.backup.save();
    var textbox = document.getElementById("textbox");
    var newText = localStorage.getItem('oTranscribe-backup-'+timestamp);
    document.getElementById("textbox").innerHTML = newText;
    oT.backup.closePanel();
}

oT.backup.cleanup = function(){
    var backups = oT.backup.list();
    for (var i = 0; i < backups.length; i++) {
        var bu = backups[i];
        var ts = bu.replace('oTranscribe-backup-','');
        var date = new Date( parseFloat( ts ) );
        var diff = Date.now() - date;
        // 1 day = 86400000 miliseconds
        if (diff > (86400000*7) ) {
            localStorage.removeItem( bu );
        }
    }
}

oT.backup.removeOldest = function(){
	localStorage.clear();

    var list = oT.backup.list();
    // var toDelete = list.slice(Math.max(list.length - 5, 1));
    var toDelete = list;
    console.log('todelete: ',toDelete);
    for (var i = 0; i < toDelete.length; i++) {
        console.log('deleting '+toDelete[i])
        localStorage.removeItem( toDelete[i] );
    }
}

// original autosave function
function saveText(){
    var field = document.getElementById("textbox");
    // load existing autosave (if present)
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    // autosave every second - but wait five seconds before kicking in
    setTimeout(function(){
        setInterval(function(){
           oT.backup.saveToLocalStorage("autosave", field.innerHTML);
        }, 1000);
    }, 5000);
}
<commit_msg>Add back in lost bugfix<commit_after>oT.backup = {};

oT.backup.openPanel = function(){
    oT.backup.populatePanel();
    $('.backup-window').height( $('.textbox-container').height() * (3/5) );
    $('.backup-panel').fadeIn('fast');
}

oT.backup.closePanel = function(){
    $('.backup-panel').fadeOut('fast',function(){
        $('.backup-window').empty();

    });
}

oT.backup.generateBlock = function(ref){
    // create icon and 'restore' button
    var text = localStorage.getItem(ref);
    var timestamp = ref.replace('oTranscribe-backup-','');
    var date = oT.backup.formatDate(timestamp);

    var block = document.createElement('div');
    var doc = document.createElement('div');
    var restoreButton = document.createElement('div');

    block.className = 'backup-block';
    doc.className = 'backup-doc';
    restoreButton.className = 'backup-restore-button';

    doc.innerHTML = text;
    restoreButton.innerHTML = date+' - restore';
    block.appendChild(doc);
    block.appendChild(restoreButton);

    return block;
}

oT.backup.formatDate = function(timestamp){
    var d = new Date( parseFloat(timestamp) );
    var day =  d.getDate() + '/' + (d.getMonth()+1);
    var now = new Date();
    today = now.getDate() + '/' + (now.getMonth()+1);
    yesterday = (now.getDate()-1) + '/' + (now.getMonth()+1);
    if (day === today) {
        day = 'Today';
    } else if (day === yesterday) {
        day = 'Yesterday'
    }
    var time = d.getHours() + ':';
    if (d.getMinutes() < 10) {
        time += '0';
    }
    time += d.getMinutes();

    formattedDate = day + ' ' + time;
    return formattedDate;
}

oT.backup.populatePanel = function(){
    oT.backup.addDocsToPanel(0,8);
    if (oT.backup.list().length === 0) {
        $('.backup-window').append( '
No backups found.
' );
    }
}

oT.backup.addDocsToPanel = function(start,end){
    $('.more-backups').remove();
    var allDocs = oT.backup.list();
    docs = allDocs.slice(start,end);
    for (var i = 0; i < docs.length; i++) {
        $('.backup-window').append( oT.backup.generateBlock(docs[i]) );
    }
    if (allDocs[end]) {
        $('.backup-window').append( '
Load older backups
' );
    }
}

oT.backup.save = function(){
    // save current text to timestamped localStorage item
    var text = document.getElementById("textbox");
    var timestamp = new Date().getTime();
    oT.backup.saveToLocalStorage('oTranscribe-backup-'+timestamp, text.innerHTML);
    // and bleep icon
    $('.sbutton.backup').addClass('flash');
    setTimeout(function(){
        $('.sbutton.backup').removeClass('flash');
    },1000);
    // and add to tray
    var newBlock = oT.backup.generateBlock('oTranscribe-backup-'+timestamp);
    newBlock.className += ' new-block';
    $('.backup-window').prepend( newBlock );
    $( newBlock ).animate({
        'opacity': 1,
        'width': '25%'
    },'slow',function(){
        $( newBlock ).find('.backup-restore-button').fadeIn();
    });

}

oT.backup.saveToLocalStorage = function(name){
    console.log(name);
    try {
       localStorage.setItem( name );
    } catch (e) {
        console.log('error');
       if(e.name === "NS_ERROR_DOM_QUOTA_REACHED") {
           oT.backup.removeOldest();
           // oT.backup.save();
       }
    }

}

oT.backup.init = function(){
    setInterval(function(){
        oT.backup.save();
        oT.backup.cleanup();
    },300000 /* 5 minutes */);
}

oT.backup.list = function(){
    var result = [];
    for (var i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i).indexOf('oTranscribe-backup') > -1) {
            result.push(localStorage.key(i));
        }
    }
    return result.sort().reverse();
}

oT.backup.restore = function(timestamp){
    oT.backup.save();
    var textbox = document.getElementById("textbox");
    var newText = localStorage.getItem('oTranscribe-backup-'+timestamp);
    document.getElementById("textbox").innerHTML = newText;
    oT.backup.closePanel();
}

oT.backup.cleanup = function(){
    var backups = oT.backup.list();
    for (var i = 0; i < backups.length; i++) {
        var bu = backups[i];
        var ts = bu.replace('oTranscribe-backup-','');
        var date = new Date( parseFloat( ts ) );
        var diff = Date.now() - date;
        // 1 day = 86400000 miliseconds
        if (diff > (86400000*7) ) {
            localStorage.removeItem( bu );
        }
    }
}

oT.backup.removeOldest = function(){
	localStorage.clear();

    var list = oT.backup.list();
    // var toDelete = list.slice(Math.max(list.length - 5, 1));
    var toDelete = list;
    console.log('todelete: ',toDelete);
    for (var i = 0; i < toDelete.length; i++) {
        console.log('deleting '+toDelete[i])
        localStorage.removeItem( toDelete[i] );
    }
}

// original autosave function
function saveText(){
    var field = document.getElementById("textbox");
    // load existing autosave (if present)
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    // autosave every second - but wait five seconds before kicking in
    setTimeout(function(){
        // prevent l10n from replacing user text
        $('#textbox p[data-l10n-id]').attr('data-l10n-id','');
        setInterval(function(){
           oT.backup.saveToLocalStorage("autosave", field.innerHTML);
        }, 1000);
    }, 5000);
}
<|endoftext|>


<commit_before>const config = require('config');

module.exports.info = {
	name: 'Restart',
	category: 'development',
	aliases: [
		'restart',
		'reboot'
	]
};

module.exports.command = (message) => {
	if (config.get('admins').includes(message.author.id)) {
		message.channel.createMessage('Restarting...')
		//	.then(() =>
		//		process.exit(0)
		//	);
	}
};
<commit_msg>whoops<commit_after>const config = require('config');

module.exports.info = {
	name: 'Restart',
	category: 'development',
	aliases: [
		'restart',
		'reboot'
	]
};

module.exports.command = (message) => {
	if (config.get('admins').includes(message.author.id)) {
		message.channel.createMessage('Restarting...')
			.then(() =>
				process.exit(0)
			);
	}
};
<|endoftext|>


<commit_before>var gulp        = require('gulp'),
    plumber     = require('gulp-plumber'),
    cache       = require('gulp-cache'),
    uglify      = require('gulp-uglify'),
	concat      = require('gulp-concat'),
    minifyCss   = require('gulp-minify-css'),
    imagemin    = require('gulp-imagemin');

/**
 * Imagemin Task
 */
gulp.task('imagemin', function () {
    return gulp.src('src/img/**/*.{jpg,png,gif}')
        .pipe(plumber())
        .pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
        .pipe(gulp.dest('assets/img/'));
});

/**
 * Javascript Task
 */
gulp.task('js', function () {
    return gulp.src('src/js/**/*.js')
        .pipe(plumber())
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js/'));
});

/**
 * CSS Task
 */
gulp.task('css', function () {
    return gulp.src('src/css/*.css')
        .pipe(plumber())
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('assets/css/'));
});

/**
 * Watch stylus files for changes & recompile
 * Watch html/md files, run jekyll & reload BrowserSync
 */
gulp.task('watch', function () {
    gulp.watch('src/js/**/*.js', ['js']);
    gulp.watch('src/css/*.css', ['css']);
    gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
});

gulp.task('default', ['imagemin', 'js', 'css', 'watch']);
<commit_msg>remove cache task imagemin<commit_after>var gulp        = require('gulp'),
    plumber     = require('gulp-plumber'),
    cache       = require('gulp-cache'),
    uglify      = require('gulp-uglify'),
	concat      = require('gulp-concat'),
    minifyCss   = require('gulp-minify-css'),
    imagemin    = require('gulp-imagemin');

/**
 * Imagemin Task
 */
gulp.task('imagemin', function () {
    return gulp.src('src/img/**/*.{jpg,png,gif}')
        .pipe(plumber())
        .pipe(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true }))
        .pipe(gulp.dest('assets/img/'));
});

/**
 * Javascript Task
 */
gulp.task('js', function () {
    return gulp.src('src/js/**/*.js')
        .pipe(plumber())
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js/'));
});

/**
 * CSS Task
 */
gulp.task('css', function () {
    return gulp.src('src/css/*.css')
        .pipe(plumber())
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('assets/css/'));
});

/**
 * Watch stylus files for changes & recompile
 * Watch html/md files, run jekyll & reload BrowserSync
 */
gulp.task('watch', function () {
    gulp.watch('src/js/**/*.js', ['js']);
    gulp.watch('src/css/*.css', ['css']);
    gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
});

gulp.task('default', ['imagemin', 'js', 'css', 'watch']);
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var History = {};

chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#777" });

function Update(tabId, url) {
  if (url) {
    var now = new Date();
    if (!(tabId in History)) {
      History[tabId] = [];
    }
    History[tabId].unshift([now, url]);

    var history_limit = parseInt(localStorage["history_size"]);
    if (! history_limit) {
      history_limit = 23;
    }
    while (History[tabId].length > history_limit) {
      History[tabId].pop();
    }

    chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0m'});
    chrome.browserAction.setPopup({ 'tabId': tabId, 'popup': "popup.html#tabId=" + tabId});
  }
}

function HandleUpdate(tabId, changeInfo, tab) {
  Update(tabId, changeInfo.url);
}

function HandleRemove(tabId, removeInfo) {
  delete History[tabId];
}

function HandleReplace(addedTabId, removedTabId) {
  delete History[removedTabId];
}

function UpdateBadges() {
  var now = new Date();
  for (tabId in History) {
    var description = FormatDuration(now - History[tabId][0][0]);
    chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
  }
}

setInterval(UpdateBadges, 3000);

chrome.tabs.onUpdated.addListener(HandleUpdate);
chrome.tabs.onRemoved.addListener(HandleRemove);
chrome.tabs.onReplaced.addListener(HandleReplace);
<commit_msg>Skip no-URL updates with early return<commit_after>/*
 * Copyright 2013 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var History = {};

chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#777" });

function Update(tabId, url) {
  if (!url) {
    return;
  }
  var now = new Date();
  if (!(tabId in History)) {
    History[tabId] = [];
  }
  History[tabId].unshift([now, url]);

  var history_limit = parseInt(localStorage["history_size"]);
  if (! history_limit) {
    history_limit = 23;
  }
  while (History[tabId].length > history_limit) {
    History[tabId].pop();
  }

  chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0m'});
  chrome.browserAction.setPopup({ 'tabId': tabId, 'popup': "popup.html#tabId=" + tabId});
}

function HandleUpdate(tabId, changeInfo, tab) {
  Update(tabId, changeInfo.url);
}

function HandleRemove(tabId, removeInfo) {
  delete History[tabId];
}

function HandleReplace(addedTabId, removedTabId) {
  delete History[removedTabId];
}

function UpdateBadges() {
  var now = new Date();
  for (tabId in History) {
    var description = FormatDuration(now - History[tabId][0][0]);
    chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
  }
}

setInterval(UpdateBadges, 3000);

chrome.tabs.onUpdated.addListener(HandleUpdate);
chrome.tabs.onRemoved.addListener(HandleRemove);
chrome.tabs.onReplaced.addListener(HandleReplace);
<|endoftext|>


<commit_before>/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage',
        'Magento_Checkout/js/model/error-processor',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/full-screen-loader'
    ],
    function ($, quote, urlBuilder, storage, errorProcessor, customer, fullScreenLoader) {
        'use strict';

        return function (messageContainer) {
            var serviceUrl,
                payload,
                paymentData = quote.paymentMethod();

            /**
             * Checkout for guest and registered customer.
             */
            if (!customer.isLoggedIn()) {
                serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/selected-payment-method', {
                    cartId: quote.getQuoteId()
                });
                payload = {
                    cartId: quote.getQuoteId(),
                    method: paymentData,
                    billingAddress: quote.billingAddress()
                };
            } else {
                serviceUrl = urlBuilder.createUrl('/carts/mine/selected-payment-method', {});
                payload = {
                    cartId: quote.getQuoteId(),
                    method: paymentData,
                    billingAddress: quote.billingAddress()
                };
            }

            fullScreenLoader.startLoader();

            return storage.put(
                serviceUrl, JSON.stringify(payload)
            ).done(
                function () {
                    $.mage.redirect('/pbxep/payment/redirect');
                }
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageContainer);
                    fullScreenLoader.stopLoader();
                }
            );
        };
    }
);
<commit_msg>[~] FO Payment: use of Mage URL helper for use of subfolders, subdomains...<commit_after>/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage',
        'Magento_Checkout/js/model/error-processor',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/full-screen-loader',
        'mage/url',
    ],
    function ($, quote, urlBuilder, storage, errorProcessor, customer, fullScreenLoader, url) {
        'use strict';

        return function (messageContainer) {
            var serviceUrl,
                payload,
                paymentData = quote.paymentMethod();

            /**
             * Checkout for guest and registered customer.
             */
            if (!customer.isLoggedIn()) {
                serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/selected-payment-method', {
                    cartId: quote.getQuoteId()
                });
                payload = {
                    cartId: quote.getQuoteId(),
                    method: paymentData,
                    billingAddress: quote.billingAddress()
                };
            } else {
                serviceUrl = urlBuilder.createUrl('/carts/mine/selected-payment-method', {});
                payload = {
                    cartId: quote.getQuoteId(),
                    method: paymentData,
                    billingAddress: quote.billingAddress()
                };
            }

            fullScreenLoader.startLoader();

            return storage.put(
                serviceUrl, JSON.stringify(payload)
            ).done(
                function () {
                    $.mage.redirect(url.build('pbxep/payment/redirect/'));
                }
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageContainer);
                    fullScreenLoader.stopLoader();
                }
            );
        };
    }
);
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.test = function(req, res, next) {

  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");
            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    assignmentID: assignmentID
                  })
                  .exec(function(err, result){
                      if(err) return next(err)
                      numDeleted++;
                  })
                } else {

                //Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)

                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set: {assignmentNumber: assignmentNumber, subAssignment: subAssignment}
                      }
                    ).exec(function(err, result) {
                      if(err) return next(err)
                      //console.log("updated assignment ", assignmentID)
                      numUpdated++;

                    })

                }

          }
        }

        return next("Started with " + numTotal + ", Num to modify: " + numToModify + ", Num deleted " + numDeleted + ", Number updated " + numUpdated)
      });

}
<commit_msg>attempting to test updates<commit_after>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.test = function(req, res, next) {

  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        return next(assignmentResult.length);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");
            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    assignmentID: assignmentID
                  })
                  .exec(function(err, result){
                      if(err) return next(err)
                      numDeleted++;
                  })
                } else {

                //Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)

                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set: {assignmentNumber: assignmentNumber, subAssignment: subAssignment}
                      }
                    ).exec(function(err, result) {
                      if(err) return next(err)
                      //console.log("updated assignment ", assignmentID)
                      numUpdated++;

                    })

                }

          }
        }

        return next("Started with " + numTotal + ", Num to modify: " + numToModify + ", Num deleted " + numDeleted + ", Number updated " + numUpdated)
      });

}
<|endoftext|>


<commit_before>import createVirtualAudioGraph from 'virtual-audio-graph';

export default ({audioContext = new AudioContext(),
                 output = audioContext.destination} = {}) => {
  const virtualAudioGraph = createVirtualAudioGraph({audioContext, output});
  return nodeParams$ => nodeParams$.subscribe(nodeParams => virtualAudioGraph.update(nodeParams));
};
<commit_msg>remove semi-colons<commit_after>import createVirtualAudioGraph from 'virtual-audio-graph'

export default ({audioContext = new AudioContext(),
                 output = audioContext.destination} = {}) => {
  const virtualAudioGraph = createVirtualAudioGraph({audioContext, output})
  return nodeParams$ => nodeParams$.subscribe(nodeParams => virtualAudioGraph.update(nodeParams))
}
<|endoftext|>


<commit_before>"use strict";
const XU = require("@sembiance/xu"),
	fileUtil = require("./fileUtil.js"),
	fs = require("fs"),
	path = require("path"),
	runUtil = require("./runUtil.js"),
	tiptoe = require("tiptoe");

// Returns a bunch of info about the given image
exports.getInfo = function getInfo(imageFilePath, _options, _cb)
{
	const {options, cb} = XU.optionscb(_options, _cb);

	// Available properties: https://imagemagick.org/script/escape.php
	const PROPS =
	{
		height             : "%h",
		colorCount         : "%k",
		format             : "%[magick]",
		width              : "%w",
		canvasHeight       : "%H",
		canvasWidth        : "%W",
		size               : "%B",
		compressionType    : "%C",
		//compressionQuality : "%Q",	// Often is just '92' for most images and formats
		opaque             : "%[opaque]"
	};

	const NUMS = ["width", "height", "canvasWidth", "canvasHeight", "colorCount", "size", "compressionQuality", "entropy"];
	const BOOLS = ["opaque"];

	tiptoe(
		function runIdentifiers()
		{
			// Calculating colorCount takes FOREVER but is a useful metric, so we try it, but only give it a small amount of time to calculate
			const RUN_OPTIONS = {timeout : XU.MINUTE*5, silent : true, killSignal : "SIGTERM", cwd : path.dirname(imageFilePath)};	// imageMagick needs a TERM to kill when identifying an image, otherwise it runs like, forever on huge images
			runUtil.run("identify", ["-format", Object.entries(PROPS).map(([k, v]) => `${k}:${v}`).join("\\n"), path.basename(imageFilePath)], {...RUN_OPTIONS, timeout : (options.timeout || RUN_OPTIONS.timeout)}, this.parallel());
			runUtil.run("identify", ["-format", "width:%w\\nheight:%h", path.basename(imageFilePath)], RUN_OPTIONS, this.parallel());
		},
		function parseResults(imResultsRaw, whRaw)
		{
			let imResults = (imResultsRaw || "").trim();
			if(imResults.length===0 || imResults.includes("corrupt image") || imResults.toLowerCase().startsWith("error: command failed"))
				imResults = (whRaw || "").trim();

			const imLines = imResults.split("\n");
			if(imLines.length===0)
				return this();

			const imageInfo = {};
			imLines.forEach(imgLine =>
			{
				const lineProps = (imgLine.match(/(?<propName>[^:]+):(?<propValue>.*)$/) || {}).groups;
				if(!lineProps || !Object.keys(PROPS).includes(lineProps.propName))
					return;

				const propValue = NUMS.includes(lineProps.propName) ? +lineProps.propValue : (BOOLS.includes(lineProps.propName) ? lineProps.propValue.toLowerCase()==="true" : lineProps.propValue);
				if(propValue==="Undefined")
					return;

				imageInfo[lineProps.propName] = propValue;
			});

			this(undefined, Object.keys(imageInfo).length===0 ? undefined : imageInfo);
		},
		cb
	);
};

// Will return [width, height] of the image at imageFilePath
exports.getWidthHeight = function getWidthHeight(imageFilePath, cb)
{
	tiptoe(
		function getSize()
		{
			runUtil.run("identify", ["-quiet", imageFilePath], runUtil.SILENT, this);
		},
		function processSizes(err, result)
		{
			if(err)
				return cb(err);

			const matches = result.trim().match(/[^ ]+ [^ ]+ (?<width>\d+)x(?<height>\d+) .*/);
			if(!matches || matches.length<3 || !matches.groups)
				return cb(new Error(`Invalid image: ${imageFilePath}`));

			cb(null, [+matches.groups.width, +matches.groups.height]);
		}
	);
};

// Will crop the given image at inputFilePath randomly to targetWidth x targetHeight
exports.randomCrop = function randomCrop(inputFilePath, outputFilePath, targetWidth, targetHeight, cb)
{
	tiptoe(
		function measure()
		{
			exports.getWidthHeight(inputFilePath, this);
		},
		function calcOffsetsAndCrop(dimensions)
		{
			if(targetWidth===dimensions[0] && targetHeight===dimensions[1])
				return fs.copyFile(inputFilePath, outputFilePath, this), undefined;

			const xOffset = (targetWidth<dimensions[0]) ? Math.randomInt(0, (dimensions[0]-targetWidth)) : 0;
			const yOffset = (targetHeight<dimensions[1]) ? Math.randomInt(0, (dimensions[1]-targetHeight)) : 0;

			runUtil.run("convert", [inputFilePath, "-crop", `${targetWidth}x${targetHeight}+${xOffset}+${yOffset}`, "+repage", outputFilePath], runUtil.SILENT, this);
		},
		cb
	);
};

// Will try and auto-detect what the crop dimensions are and return {w, h, x, y}. Options:
// cropColor	What color to crop. (default: black)
// fuzz			How much variance from the cropColor to be considered a match (default: 0)
exports.getAutoCropDimensions = function getAutoCropDimensions(inputFilePath, _options, _cb)
{
	const {options, cb} = XU.optionscb(_options, _cb, {cropColor : "#000000"});

	tiptoe(
		function runTrim()
		{
			const convertArgs = [inputFilePath, "-bordercolor", options.cropColor, "-border", "1x1"];
			if(options.fuzz)
				convertArgs.push("-fuzz", options.fuzz);
			convertArgs.push("-trim", "info:-");
			runUtil.run("convert", convertArgs, runUtil.SILENT, this);
		},
		function returnResults(cropInfoRaw)
		{
			if(cropInfoRaw.trim().includes("geometry does not contain image"))
				return {trimAll : true};

			const cropInfoMatch = cropInfoRaw.trim().match(/(?<w>\d+)x(?<h>\d+) \d+x\d+\+(?<x>\d+)\+(?<y>\d+)/);
			if(!cropInfoMatch)
				return this.finish();

			this(undefined, Object.map(cropInfoMatch.groups, (k, v) => ((+v)-(["x", "y"].includes(k) ? 1 : 0))));
		},
		cb
	);
};

// Will compress the given image at inputFilePath to outputFilePath. If lossy is true then it will reduce image quality as needed to achieve higher compression
exports.compress = function compress(inputFilePath, outputFilePath, fileType, lossy, cb)
{
	if(!(["jpg", "png", "gif"]).includes(fileType))
		throw new Error(`Unsupported image type: ${fileType}`);

	const tmpInputFilePath = fileUtil.generateTempFilePath(undefined, `.${fileType}`);
	const tmpOutputFilePath = fileUtil.generateTempFilePath(undefined, `.${fileType}`);

	tiptoe(
		function prepare()
		{
			fs.copyFile(inputFilePath, tmpInputFilePath, this);
		},
		function performCompression()
		{
			if(fileType==="png")
			{
				if(lossy)
					runUtil.run("pngquant", ["--speed=1", "--strip", "--output", tmpOutputFilePath, tmpInputFilePath], runUtil.SILENT, this);
				else
					runUtil.run("zopflipng", ["-m", tmpInputFilePath, tmpOutputFilePath], runUtil.SILENT, this);
			}
			else if(fileType==="jpg")
			{
				if(lossy)
					runUtil.run("guetzli", ["--quality", "90", tmpInputFilePath, tmpOutputFilePath], runUtil.SILENT, this);
				else
					runUtil.run("jpegtran", ["-progressive", "-copy", "none", "-optimize", "-perfect", "-outfile", tmpOutputFilePath, tmpInputFilePath], runUtil.SILENT, this);
			}
			else if(fileType==="gif")
			{
				runUtil.run("gifsicle", ["--optimize=3", tmpInputFilePath, "-o", tmpOutputFilePath], runUtil.SILENT, this);
			}
		},
		function cleanup()
		{
			if(fileUtil.existsSync(tmpOutputFilePath))
				fileUtil.move(tmpOutputFilePath, outputFilePath, this.parallel());
			fileUtil.unlink(tmpInputFilePath, this.parallel());
		},
		cb
	);
};
<commit_msg>Fixed bug when image started with a hypen<commit_after>"use strict";
const XU = require("@sembiance/xu"),
	fileUtil = require("./fileUtil.js"),
	fs = require("fs"),
	path = require("path"),
	runUtil = require("./runUtil.js"),
	tiptoe = require("tiptoe");

// Returns a bunch of info about the given image
exports.getInfo = function getInfo(imageFilePath, _options, _cb)
{
	const {options, cb} = XU.optionscb(_options, _cb);

	// Available properties: https://imagemagick.org/script/escape.php
	const PROPS =
	{
		height             : "%h",
		colorCount         : "%k",
		format             : "%[magick]",
		width              : "%w",
		canvasHeight       : "%H",
		canvasWidth        : "%W",
		size               : "%B",
		compressionType    : "%C",
		//compressionQuality : "%Q",	// Often is just '92' for most images and formats
		opaque             : "%[opaque]"
	};

	const NUMS = ["width", "height", "canvasWidth", "canvasHeight", "colorCount", "size", "compressionQuality", "entropy"];
	const BOOLS = ["opaque"];

	tiptoe(
		function runIdentifiers()
		{
			// Calculating colorCount takes FOREVER but is a useful metric, so we try it, but only give it a small amount of time to calculate
			const RUN_OPTIONS = {timeout : XU.MINUTE*5, silent : true, killSignal : "SIGTERM", cwd : path.dirname(imageFilePath)};	// imageMagick needs a TERM to kill when identifying an image, otherwise it runs like, forever on huge images
			runUtil.run("identify", ["-format", Object.entries(PROPS).map(([k, v]) => `${k}:${v}`).join("\\n"), `./${path.basename(imageFilePath)}`], {...RUN_OPTIONS, timeout : (options.timeout || RUN_OPTIONS.timeout)}, this.parallel());
			runUtil.run("identify", ["-format", "width:%w\\nheight:%h", `./${path.basename(imageFilePath)}`], RUN_OPTIONS, this.parallel());
		},
		function parseResults(imResultsRaw, whRaw)
		{
			let imResults = (imResultsRaw || "").trim();
			if(imResults.length===0 || imResults.includes("corrupt image") || imResults.toLowerCase().startsWith("error: command failed"))
				imResults = (whRaw || "").trim();

			const imLines = imResults.split("\n");
			if(imLines.length===0)
				return this();

			const imageInfo = {};
			imLines.forEach(imgLine =>
			{
				const lineProps = (imgLine.match(/(?<propName>[^:]+):(?<propValue>.*)$/) || {}).groups;
				if(!lineProps || !Object.keys(PROPS).includes(lineProps.propName))
					return;

				const propValue = NUMS.includes(lineProps.propName) ? +lineProps.propValue : (BOOLS.includes(lineProps.propName) ? lineProps.propValue.toLowerCase()==="true" : lineProps.propValue);
				if(propValue==="Undefined")
					return;

				imageInfo[lineProps.propName] = propValue;
			});

			this(undefined, Object.keys(imageInfo).length===0 ? undefined : imageInfo);
		},
		cb
	);
};

// Will return [width, height] of the image at imageFilePath
exports.getWidthHeight = function getWidthHeight(imageFilePath, cb)
{
	tiptoe(
		function getSize()
		{
			runUtil.run("identify", ["-quiet", imageFilePath], runUtil.SILENT, this);
		},
		function processSizes(err, result)
		{
			if(err)
				return cb(err);

			const matches = result.trim().match(/[^ ]+ [^ ]+ (?<width>\d+)x(?<height>\d+) .*/);
			if(!matches || matches.length<3 || !matches.groups)
				return cb(new Error(`Invalid image: ${imageFilePath}`));

			cb(null, [+matches.groups.width, +matches.groups.height]);
		}
	);
};

// Will crop the given image at inputFilePath randomly to targetWidth x targetHeight
exports.randomCrop = function randomCrop(inputFilePath, outputFilePath, targetWidth, targetHeight, cb)
{
	tiptoe(
		function measure()
		{
			exports.getWidthHeight(inputFilePath, this);
		},
		function calcOffsetsAndCrop(dimensions)
		{
			if(targetWidth===dimensions[0] && targetHeight===dimensions[1])
				return fs.copyFile(inputFilePath, outputFilePath, this), undefined;

			const xOffset = (targetWidth<dimensions[0]) ? Math.randomInt(0, (dimensions[0]-targetWidth)) : 0;
			const yOffset = (targetHeight<dimensions[1]) ? Math.randomInt(0, (dimensions[1]-targetHeight)) : 0;

			runUtil.run("convert", [inputFilePath, "-crop", `${targetWidth}x${targetHeight}+${xOffset}+${yOffset}`, "+repage", outputFilePath], runUtil.SILENT, this);
		},
		cb
	);
};

// Will try and auto-detect what the crop dimensions are and return {w, h, x, y}. Options:
// cropColor	What color to crop. (default: black)
// fuzz			How much variance from the cropColor to be considered a match (default: 0)
exports.getAutoCropDimensions = function getAutoCropDimensions(inputFilePath, _options, _cb)
{
	const {options, cb} = XU.optionscb(_options, _cb, {cropColor : "#000000"});

	tiptoe(
		function runTrim()
		{
			const convertArgs = [inputFilePath, "-bordercolor", options.cropColor, "-border", "1x1"];
			if(options.fuzz)
				convertArgs.push("-fuzz", options.fuzz);
			convertArgs.push("-trim", "info:-");
			runUtil.run("convert", convertArgs, runUtil.SILENT, this);
		},
		function returnResults(cropInfoRaw)
		{
			if(cropInfoRaw.trim().includes("geometry does not contain image"))
				return {trimAll : true};

			const cropInfoMatch = cropInfoRaw.trim().match(/(?<w>\d+)x(?<h>\d+) \d+x\d+\+(?<x>\d+)\+(?<y>\d+)/);
			if(!cropInfoMatch)
				return this.finish();

			this(undefined, Object.map(cropInfoMatch.groups, (k, v) => ((+v)-(["x", "y"].includes(k) ? 1 : 0))));
		},
		cb
	);
};

// Will compress the given image at inputFilePath to outputFilePath. If lossy is true then it will reduce image quality as needed to achieve higher compression
exports.compress = function compress(inputFilePath, outputFilePath, fileType, lossy, cb)
{
	if(!(["jpg", "png", "gif"]).includes(fileType))
		throw new Error(`Unsupported image type: ${fileType}`);

	const tmpInputFilePath = fileUtil.generateTempFilePath(undefined, `.${fileType}`);
	const tmpOutputFilePath = fileUtil.generateTempFilePath(undefined, `.${fileType}`);

	tiptoe(
		function prepare()
		{
			fs.copyFile(inputFilePath, tmpInputFilePath, this);
		},
		function performCompression()
		{
			if(fileType==="png")
			{
				if(lossy)
					runUtil.run("pngquant", ["--speed=1", "--strip", "--output", tmpOutputFilePath, tmpInputFilePath], runUtil.SILENT, this);
				else
					runUtil.run("zopflipng", ["-m", tmpInputFilePath, tmpOutputFilePath], runUtil.SILENT, this);
			}
			else if(fileType==="jpg")
			{
				if(lossy)
					runUtil.run("guetzli", ["--quality", "90", tmpInputFilePath, tmpOutputFilePath], runUtil.SILENT, this);
				else
					runUtil.run("jpegtran", ["-progressive", "-copy", "none", "-optimize", "-perfect", "-outfile", tmpOutputFilePath, tmpInputFilePath], runUtil.SILENT, this);
			}
			else if(fileType==="gif")
			{
				runUtil.run("gifsicle", ["--optimize=3", tmpInputFilePath, "-o", tmpOutputFilePath], runUtil.SILENT, this);
			}
		},
		function cleanup()
		{
			if(fileUtil.existsSync(tmpOutputFilePath))
				fileUtil.move(tmpOutputFilePath, outputFilePath, this.parallel());
			fileUtil.unlink(tmpInputFilePath, this.parallel());
		},
		cb
	);
};
<|endoftext|>


<commit_before>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');

function sendSubstitutions(senderID, message){
	var body = {
		'mode': 'classList',
		'param': 'today'
	};
	message = message.toLowerCase();
	var opt = message[0];
	var help = 'Dostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';
	var messageData = {
		recipient: {
		  id: senderID
		},
		message: {
		  text: help
		}
	};
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
	reqClass += message[4];};
	switch(opt){
		case '0':
			break;
		case '1':
			body['param']='tomorrow'; //masz else, więc jak dam dobrze to przejdzie, chociaż ty piszesz źle
			break;
		case '2':
			body['mode']='NO';
			var messageData = {
				recipient: {
				  id: senderID
				},
				message: {
				  text: 'Skontaktujemy się aby odpowiedzieć na pytanie.'
				}
			};
			callSendAPI(messageData);
			break;
		default:
			body['mode']='NO';
			callSendAPI(messageData);
			break;
	};
	if(body['mode'] != 'NO'){
		manageUsers.postCall('0000', body, function(classes){
			var is = 0;
			for(var i = 0; i < classes.length; i++){
				if(classes[i] == reqClass){
					is++;
				}
			}
			if(is > 0){
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'Zastępstwa'
					}
				};
			} else {
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'brak zastępstw'
					}
				};
			}
			callSendAPI(messageData);
		});
	}
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  //sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID, messageText);
  //sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<commit_msg>Inform admin about unread questions<commit_after>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');
var adm1 = config.adm1;
var adm2 = config.adm2;

function sendSubstitutions(senderID, message){
	var admMessage1 = {
		recipient: {
		  id: adm1
		},
		message: {
		  text: 'nowa wiadomość:\n' + message
		}
	};
	var admMessage2 = {
		recipient: {
		  id: adm2
		},
		message: {
		  text: 'nowa wiadomość:\n' + message
		}
	};
	var body = {
		'mode': 'classList',
		'param': 'today'
	};
	message = message.toLowerCase();
	var opt = message[0];
	var help = 'Dostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';
	var messageData = {
		recipient: {
		  id: senderID
		},
		message: {
		  text: help
		}
	};
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
	reqClass += message[4];};
	switch(opt){
		case '0':
			break;
		case '1':
			body['param']='tomorrow'; //masz else, więc jak dam dobrze to przejdzie, chociaż ty piszesz źle
			break;
		case '2':
			body['mode']='NO';
			var messageData = {
				recipient: {
				  id: senderID
				},
				message: {
				  text: 'Skontaktujemy się aby odpowiedzieć na pytanie.'
				}
			};
			callSendAPI(messageData);
			callSendAPI(admMessage1);
			callSendAPI(admMessage2);
			break;
		default:
			body['mode']='NO';
			callSendAPI(messageData);
			break;
	};
	if(body['mode'] != 'NO'){
		manageUsers.postCall('0000', body, function(classes){
			var is = 0;
			for(var i = 0; i < classes.length; i++){
				if(classes[i] == reqClass){
					is++;
				}
			}
			if(is > 0){
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'Zastępstwa'
					}
				};
			} else {
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'brak zastępstw'
					}
				};
			}
			callSendAPI(messageData);
		});
	}
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  //sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID, messageText);
  //sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';

import _ from 'lodash';

import TimeItems from '../_TimeItems/_TimeItems';

export default class _TimeList extends Component {

    constructor(props) {

        super(props);

        this.state = {
            hour: this.props.hour,
            minute: this.props.minute,
            second: this.props.second,
            hoursData:[],
            minutesData:[],
            secondData:[]
        };

        this.hourChangeHandle = this::this.hourChangeHandle;
        this.minuteChangeHandle = this::this.minuteChangeHandle;
        this.secondChangeHandle = this::this.secondChangeHandle;

    }

    rangeData(range,minValue,maxValue) {
        const {isRequired}=this.props;
        let arr = [];
        for (let i = 0; i < range; i++) {
            if (i < 10) {
                i = '0' + i
            }
            let obj;
            if(isRequired){
                (+i > +maxValue) || (+i <+minValue) ?
                    obj = {text: i, value: false}
                    :
                    obj = {text: i, value: true}
            }else{
                obj = {text: i, value: true}
            }
            arr.push(obj)
        }
        return arr;
    }

    hourChangeHandle(value) {
        let state = _.cloneDeep(this.state);
        const {minValue,maxValue} = this.props;
        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }
        state.hour = value ;
        if(minHour == value || maxHour == value){
            state.minutesData = this.rangeData(60,minMinute,maxMinute);
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.minutesData = this.rangeData(60);
            state.secondsData = this.rangeData(60);
        }
        this.setState(state, ()=> {
            this.props.onChange && this.props.onChange({hour: value, minute: state.minute, second: state.second})
        })
    }

    minuteChangeHandle(value) {
        let state = _.cloneDeep(this.state);
        const {minValue,maxValue} = this.props;
        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }
        state.minute = value ;
        if(minHour == state.hour && minMinute == value || maxHour == state.hour && maxMinute == value){
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.secondsData = this.rangeData(60);
        }

        this.setState(state, ()=> {
            this.props.onChange && this.props.onChange({hour: state.hour, minute: value, second: state.second})
        })

    }

    secondChangeHandle(value) {
        let {hour, minute}=this.state;
        this.setState({
            second: value
        }, ()=> {
            this.props.onChange && this.props.onChange({hour: hour, minute: minute, second: value})
        })
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.hour !== this.props.hour || nextProps.minute !== this.props.minute || nextProps.second !== this.props.second) {
            this.setState({
                hour: nextProps.hour,
                minute: nextProps.minute,
                second: nextProps.second
            });
        }
    }
    componentDidMount() {
        const {minValue,maxValue} = this.props;
        let state = _.cloneDeep(this.state);

        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }

        state.hoursData = this.rangeData(24,minHour,maxHour);

        if(minHour == state.hour || maxHour == state.hour){
            state.minutesData = this.rangeData(60,minMinute,maxMinute);
        }else{
            state.minutesData = this.rangeData(60);
        }

        if(minHour == state.hour && minMinute == state.minute || maxHour == state.hour && maxMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.secondsData = this.rangeData(60);
        }

        this.setState(state)

    }

    render() {
        const {className, popupVisible} = this.props;
        const {hour, minute, second, hoursData, minutesData, secondsData} = this.state;

        return (
            <div className={`calendar ${className}`}>
                <TimeItems className="hours"
                           data={hoursData}
                           value={hour}
                           popupVisible={popupVisible}
                           onChange={this.hourChangeHandle}
                />
                <TimeItems className="minutes"
                           data={minutesData}
                           value={minute}
                           popupVisible={popupVisible}
                           onChange={this.minuteChangeHandle}
                />
                <TimeItems className="seconds"
                           data={secondsData}
                           value={second}
                           popupVisible={popupVisible}
                           onChange={this.secondChangeHandle}
                />

        );
    }
};

_TimeList.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,
    popupVisible: PropTypes.bool,
    hour: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    minute: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    second: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    isRequired:PropTypes.bool,
    maxValue:PropTypes.string,//'11:20:39'
    minValue:PropTypes.string
};
<commit_msg>timePicker<commit_after>import React, {Component, PropTypes} from 'react';

import _ from 'lodash';

import TimeItems from '../_TimeItems/_TimeItems';

export default class _TimeList extends Component {

    constructor(props) {

        super(props);

        this.state = {
            hour: this.props.hour,
            minute: this.props.minute,
            second: this.props.second,
            hoursData:[],
            minutesData:[],
            secondData:[]
        };

        this.hourChangeHandle = this::this.hourChangeHandle;
        this.minuteChangeHandle = this::this.minuteChangeHandle;
        this.secondChangeHandle = this::this.secondChangeHandle;

    }

    rangeData(range,minValue,maxValue) {
        const {isRequired}=this.props;
        let arr = [];
        for (let i = 0; i < range; i++) {
            if (i < 10) {
                i = '0' + i
            }
            let obj;
            if(isRequired){
                (+i > +maxValue) || (+i <+minValue) ?
                    obj = {text: i, value: false}
                    :
                    obj = {text: i, value: true}
            }else{
                obj = {text: i, value: true}
            }
            arr.push(obj)
        }
        return arr;
    }

    hourChangeHandle(value) {
        let state = _.cloneDeep(this.state);
        const {minValue,maxValue} = this.props;
        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }
        state.hour = value ;

        if(minHour == state.hour){
            state.minutesData = this.rangeData(60,minMinute,60);
        }else if(maxHour == state.hour){
            state.minutesData = this.rangeData(60,0,maxMinute);
        }else if(maxHour == minHour && minHour == state.hour){
            state.minutesData = this.rangeData(60,minMinute,maxMinute);
        }else{
            state.minutesData = this.rangeData(60);
        }

        if(minHour == state.hour && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,60);
        }else if(maxHour == state.hour && maxMinute == state.minute){
            state.secondsData = this.rangeData(60,0,maxSecond);
        }else if(maxHour == minHour && minHour == state.hour && minMinute ==maxMinute && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.secondsData = this.rangeData(60);
        }
        this.setState(state, ()=> {
            this.props.onChange && this.props.onChange({hour: value, minute: state.minute, second: state.second})
        })
    }

    minuteChangeHandle(value) {
        let state = _.cloneDeep(this.state);
        const {minValue,maxValue} = this.props;
        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }
        state.minute = value ;
        if(minHour == state.hour && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,60);
        }else if(maxHour == state.hour && maxMinute == state.minute){
            state.secondsData = this.rangeData(60,0,maxSecond);
        }else if(maxHour == minHour && minHour == state.hour && minMinute ==maxMinute && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.secondsData = this.rangeData(60);
        }

        this.setState(state, ()=> {
            this.props.onChange && this.props.onChange({hour: state.hour, minute: value, second: state.second})
        })

    }

    secondChangeHandle(value) {
        let {hour, minute}=this.state;
        this.setState({
            second: value
        }, ()=> {
            this.props.onChange && this.props.onChange({hour: hour, minute: minute, second: value})
        })
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.hour !== this.props.hour || nextProps.minute !== this.props.minute || nextProps.second !== this.props.second) {
            this.setState({
                hour: nextProps.hour,
                minute: nextProps.minute,
                second: nextProps.second
            });
        }
    }
    componentDidMount() {
        const {minValue,maxValue} = this.props;
        let state = _.cloneDeep(this.state);

        let minHour,minMinute,minSecond,maxHour,maxMinute,maxSecond;
        if(minValue){
            minHour = minValue.split(':')[0];
            minMinute = minValue.split(':')[1];
            minSecond = minValue.split(':')[2];
        }
        if(maxValue){
            maxHour = maxValue.split(':')[0];
            maxMinute = maxValue.split(':')[1];
            maxSecond = maxValue.split(':')[2];
        }

        state.hoursData = this.rangeData(24,minHour,maxHour);

        if(minHour == state.hour){
            state.minutesData = this.rangeData(60,minMinute,60);
        }else if(maxHour == state.hour){
            state.minutesData = this.rangeData(60,0,maxMinute);
        }else if(maxHour == minHour && minHour == state.hour){
            state.minutesData = this.rangeData(60,minMinute,maxMinute);
        }else{
            state.minutesData = this.rangeData(60);
        }

        if(minHour == state.hour && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,60);
        }else if(maxHour == state.hour && maxMinute == state.minute){
            state.secondsData = this.rangeData(60,0,maxSecond);
        }else if(maxHour == minHour && minHour == state.hour && minMinute ==maxMinute && minMinute == state.minute){
            state.secondsData = this.rangeData(60,minSecond,maxSecond);
        }else{
            state.secondsData = this.rangeData(60);
        }

        this.setState(state)

    }

    render() {
        const {className, popupVisible} = this.props;
        const {hour, minute, second, hoursData, minutesData, secondsData} = this.state;

        return (
            <div className={`calendar ${className}`}>
                <TimeItems className="hours"
                           data={hoursData}
                           value={hour}
                           popupVisible={popupVisible}
                           onChange={this.hourChangeHandle}
                />
                <TimeItems className="minutes"
                           data={minutesData}
                           value={minute}
                           popupVisible={popupVisible}
                           onChange={this.minuteChangeHandle}
                />
                <TimeItems className="seconds"
                           data={secondsData}
                           value={second}
                           popupVisible={popupVisible}
                           onChange={this.secondChangeHandle}
                />

        );
    }
};

_TimeList.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,
    popupVisible: PropTypes.bool,
    hour: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    minute: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    second: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    isRequired:PropTypes.bool,
    maxValue:PropTypes.string,//'11:20:39'
    minValue:PropTypes.string
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    header = require('gulp-header'),
    include = require('gulp-include'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify');

var pkg = require('./bower.json')
    fs = require('fs');

var dev = {
  mangle: false,
  compress: true,
  preserveComments: 'some',
  output: {
    beautify: true,
    indent_level: 2,
    ascii_only: true,
    comments: false,
    width: 80
  }
};

var prod = {
  mangle: true,
  preserveComments: 'some',
  compress: {
    global_defs: 'angular'
  }
};

function min(path) {
  path.basename += ".min";
}

function banner() {
  var today = new Date();
  var license = fs.readFileSync('./LICENSE.md').toString()
    .split('\n').splice(3).join('\n');
  var banner = [
    '/**!',
    ' * <%= pkg.title %> v<%= pkg.version %>',
    ' * <%= pkg.homepage %>',
    ' * Copyright (c) <%= today.getFullYear() %> <%= pkg.author %>',
    ' * <%= license.replace(/\\n/gm, "\\n * ") %>',
    ' */',
    ''].join('\n');

  return header(banner, {pkg: pkg, today: today, license: license});
}

gulp.task('build', function() {
  gulp.src('src/*.js')
    .pipe(include())
    // Dev file
    .pipe(uglify(dev))
    .pipe(banner())
    .pipe(gulp.dest('dist/'))
    // Prod file
    .pipe(rename(min))
    .pipe(uglify(prod))
    .pipe(banner())
    .pipe(gulp.dest('dist/'));
});
<commit_msg>Update gulp pipe to br more semantic<commit_after>var gulp = require('gulp'),
    header = require('gulp-header'),
    include = require('gulp-include'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify');

var pkg = require('./bower.json')
    fs = require('fs');

function dev() {
  return uglify({
    mangle: false,
    compress: true,
    preserveComments: 'some',
    output: {
      beautify: true,
      indent_level: 2,
      ascii_only: true,
      comments: false,
      width: 80
    }
  });
}

function prod() {
  return uglify({
    mangle: true,
    preserveComments: 'some',
    compress: {
      global_defs: 'angular'
    }
  });
}

function min(path) {
  path.basename += ".min";
}

function banner() {
  var today = new Date();
  var license = fs.readFileSync('./LICENSE.md').toString()
    .split('\n').splice(3).join('\n');
  var banner = [
    '/**!',
    ' * <%= pkg.title %> v<%= pkg.version %>',
    ' * <%= pkg.homepage %>',
    ' * Copyright (c) <%= today.getFullYear() %> <%= pkg.author %>',
    ' * <%= license.replace(/\\n/gm, "\\n * ") %>',
    ' */',
    ''].join('\n');

  return header(banner, {pkg: pkg, today: today, license: license});
}

gulp.task('build', function() {
  gulp.src('src/*.js')
    .pipe(include())
    // Dev file
    .pipe(dev())
    .pipe(banner())
    .pipe(gulp.dest('dist/'))
    // Prod file
    .pipe(rename(min))
    .pipe(prod())
    .pipe(banner())
    .pipe(gulp.dest('dist/'));
});
<|endoftext|>