<commit_before>var I2c = require('i2c'),
  cmds = require('./commands');

var DS2482 = function(address, options) {
  options = options || {};

  this.i2c = new I2c(0x18 | (address & 0x03), {
    device: options.device || '/dev/i2c-1',
    debug: options.debug || false
  });
};

DS2482.prototype.init =
DS2482.prototype.reset = function(callback) {
  var that = this;

  this.resetBridge(function(err) {
    if (err) { return callback(err); }

    that.resetWire(callback);
  });
};

DS2482.prototype.resetWire = function(callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeByte(cmds.ONE_WIRE_RESET, function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err, resp) {
        if (err) { return callback(err); }

        if (resp & cmds.STATUS.SHORT) {
          callback(new Error('Detected onewire short'));

        } else if ((resp & cmds.STATUS.PRESENCE) === 0) {
          callback(new Error('Failed to detected any onewire devices'));

        } else {
          callback(null, resp);
        }
      });
    });
  });
};

DS2482.prototype.writeByte = function(data, callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_WRITE_BYTE, [data], function(err) {
      if (err) { return callback(err); }

      that.wait(false, callback);
    });
  });
};

DS2482.prototype.readByte = function(callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeByte(cmds.ONE_WIRE_READ_BYTE, function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err) {
        if (err) { return callback(err); }

        that.readBridge(cmds.REGISTERS.DATA, callback);
      });
    });
  });
};

DS2482.prototype.bit = function(setHigh, callback) {
  var that = this;

  if (typeof setHight === 'function') {
    callback = setHigh;
    setHigh = true;
  }

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_SINGLE_BIT, [setHigh ? 0x80 : 0], function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err, resp) {
        if (err) { return callback(err); }

        callback(null, resp & cmds.STATUS.SINGLE_BIT ? 1 : 0);
      });
    });
  });
};

DS2482.prototype.triplet = function(direction, callback) {
  var that = this;

  if (typeof direction === 'function') {
    callback = direction;
    direction = 0;
  }

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_TRIPLET, [direction ? 0x80 : 0], function(err) {
      if (err) { return callback(err); }

      that.wait(false, callback);
    });
  });
};

DS2482.prototype.resetBridge = function(callback) {
  var that = this;

  this.i2c.writeByte(cmds.DEVICE_RESET, function(err) {
    if (err) { return callback(err); }

    that.wait(false, function(err, resp) {
      if (err) { return callback(err); }

      that.channel = 0;

      callback(null, resp);
    });
  });
};

DS2482.prototype.configureBridge = function(config, callback) {
  var data = ((~config & 0x0F) << 4) | (config & 0x0F),
    that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.WRITE_CONFIG, [data], function(err) {
      if (err) { return callback(err); }

      that.i2c.readByte(function(err, resp) {
        if (err) { return callback(err); }

        if (resp !== config) {
          callback(new Error('Failed to configure bridge'));

        } else {
          callback(null, resp);
        }
      });
    });
  });
};

DS2482.prototype.readBridge = function(reg, callback) {
  var that = this;

  if (typeof reg === 'function') {
    callback = reg;
    reg = null;
  }

  if (reg) {
    this.i2c.writeBytes(cmds.SET_READ_POINTER, [reg], function(err) {
      if (err) { return callback(err); }

      that.i2c.readByte(callback);
    });

  } else {
    this.i2c.readByte(callback);
  }
};

DS2482.prototype.wait = function(setPointer, callback) {
  var start = Date.now(),
    that = this;

  if (typeof setPointer === 'function') {
    callback = setPointer;
    setPointer = true;
  }

  function check(err, resp) {
    if (err) { return callback(err); }

    if ((resp & cmds.STATUS.BUSY) === 0) {
      callback(null, resp);

    } else if (Date.now() - start < 20) {
      setTimeout(function() {
        that.readBridge(check);
      }, 0);

    } else {
      callback(new Error('Timeout'));
    }
  }

  this.readBridge(setPointer ? cmds.REGISTERS.STATUS : null, check);
};

module.exports = DS2482;
<commit_msg>Fixed read to return unsigned int<commit_after>var I2c = require('i2c'),
  cmds = require('./commands');

var DS2482 = function(address, options) {
  options = options || {};

  this.i2c = new I2c(0x18 | (address & 0x03), {
    device: options.device || '/dev/i2c-1',
    debug: options.debug || false
  });
};

DS2482.prototype.init =
DS2482.prototype.reset = function(callback) {
  var that = this;

  this.resetBridge(function(err) {
    if (err) { return callback(err); }

    that.resetWire(callback);
  });
};

DS2482.prototype.resetWire = function(callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeByte(cmds.ONE_WIRE_RESET, function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err, resp) {
        if (err) { return callback(err); }

        if (resp & cmds.STATUS.SHORT) {
          callback(new Error('Detected onewire short'));

        } else if ((resp & cmds.STATUS.PRESENCE) === 0) {
          callback(new Error('Failed to detected any onewire devices'));

        } else {
          callback(null, resp);
        }
      });
    });
  });
};

DS2482.prototype.writeByte = function(data, callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_WRITE_BYTE, [data], function(err) {
      if (err) { return callback(err); }

      that.wait(false, callback);
    });
  });
};

DS2482.prototype.readByte = function(callback) {
  var that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeByte(cmds.ONE_WIRE_READ_BYTE, function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err) {
        if (err) { return callback(err); }

        that.readBridge(cmds.REGISTERS.DATA, callback);
      });
    });
  });
};

DS2482.prototype.bit = function(setHigh, callback) {
  var that = this;

  if (typeof setHight === 'function') {
    callback = setHigh;
    setHigh = true;
  }

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_SINGLE_BIT, [setHigh ? 0x80 : 0], function(err) {
      if (err) { return callback(err); }

      that.wait(false, function(err, resp) {
        if (err) { return callback(err); }

        callback(null, resp & cmds.STATUS.SINGLE_BIT ? 1 : 0);
      });
    });
  });
};

DS2482.prototype.triplet = function(direction, callback) {
  var that = this;

  if (typeof direction === 'function') {
    callback = direction;
    direction = 0;
  }

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.ONE_WIRE_TRIPLET, [direction ? 0x80 : 0], function(err) {
      if (err) { return callback(err); }

      that.wait(false, callback);
    });
  });
};

DS2482.prototype.resetBridge = function(callback) {
  var that = this;

  this.i2c.writeByte(cmds.DEVICE_RESET, function(err) {
    if (err) { return callback(err); }

    that.wait(false, function(err, resp) {
      if (err) { return callback(err); }

      that.channel = 0;

      callback(null, resp);
    });
  });
};

DS2482.prototype.configureBridge = function(config, callback) {
  var data = ((~config & 0x0F) << 4) | (config & 0x0F),
    that = this;

  this.wait(true, function(err) {
    if (err) { return callback(err); }

    that.i2c.writeBytes(cmds.WRITE_CONFIG, [data], function(err) {
      if (err) { return callback(err); }

      that.readBridge(function(err, resp) {
        if (err) { return callback(err); }

        if (resp !== config) {
          callback(new Error('Failed to configure bridge'));

        } else {
          callback(null, resp);
        }
      });
    });
  });
};

DS2482.prototype.readBridge = function(reg, callback) {
  var that = this;

  if (typeof reg === 'function') {
    callback = reg;
    reg = null;
  }

  function read(err, resp) {
    if (err) { return callback(err); }

    callback(null, (resp >>> 0) & 0xFF);
  }

  if (reg) {
    this.i2c.writeBytes(cmds.SET_READ_POINTER, [reg], function(err) {
      if (err) { return callback(err); }

      that.i2c.readByte(read);
    });

  } else {
    this.i2c.readByte(read);
  }
};

DS2482.prototype.wait = function(setPointer, callback) {
  var start = Date.now(),
    that = this;

  if (typeof setPointer === 'function') {
    callback = setPointer;
    setPointer = true;
  }

  function check(err, resp) {
    if (err) { return callback(err); }

    if ((resp & cmds.STATUS.BUSY) === 0) {
      callback(null, resp);

    } else if (Date.now() - start < 20) {
      setTimeout(function() {
        that.readBridge(check);
      }, 0);

    } else {
      callback(new Error('Timeout'));
    }
  }

  this.readBridge(setPointer ? cmds.REGISTERS.STATUS : null, check);
};

module.exports = DS2482;
<|endoftext|>


<commit_before>"use strict";

const chalk = require("chalk");
const util = require("util");

function write(stream, color, messages) {
	let output = "";
	let prefix = "";

	// If there is more than one message, treat the first as a tag.
	if (messages.length > 1) {
		output = `[${messages.shift()}]`;
		prefix = " ";
	}

	for (let message of messages) {
		if (typeof message === "object") {
			try {
				message = JSON.stringify(message, null, 4);
			} catch (e) {
				// If JSON.stringify() fails, the object has circural references.
				// Replaces circural referenced objects with [Circural] so we can print them.
				message = util.inspect(message);
			}
		}

		output += prefix + message;
	}

	let timestamp = getTimestamp();

	if (color === null) {
		stream(`${timestamp} | ${output}`);
	} else {
		stream(color(`${timestamp} | ${output}`));
	}
}

function getTimestamp() {
	let date = new Date();

	let year = date.getFullYear();
	let month = pad(date.getMonth() + 1);
	let day = pad(date.getDate());
	let hour = pad(date.getHours());
	let minute = pad(date.getMinutes());
	let second = pad(date.getSeconds());

	return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

function pad(number) {
	return (number < 10) ? ("0" + number) : number;
}

function success(...args) {
	write(console.log, chalk.green, [...args]);
}

function info(...args) {
	// Handle light and dark terminal backgrounds by not specifying a color.
	write(console.info, null, [...args]);
}

function warn(...args) {
	write(console.warn, chalk.yellow, [...args]);
}

function error(...args) {
	write(console.error, chalk.red, [...args]);
}

module.exports = {
	getTimestamp,
	success,
	info,
	warn,
	error,
};
<commit_msg>Support multiple tags (#2)<commit_after>"use strict";

const chalk = require("chalk");
const util = require("util");

function write(stream, color, messages) {
	let output = "";
	let prefix = "";

	// If there is more than one message, treat the first as a tag.
	if (messages.length > 1) {
		let first = messages.shift();
		let tags = [];

		if (Array.isArray(first) === true) {
			tags = first;
		} else {
			tags.push(first);
		}

		output += tags.map((t) => `[${t}] `).join("");
		prefix = " ";
	}

	for (let message of messages) {
		if (typeof message === "object") {
			try {
				message = JSON.stringify(message, null, 4);
			} catch (e) {
				// If JSON.stringify() fails, the object has circural references.
				// Replaces circural referenced objects with [Circural] so we can print them.
				message = util.inspect(message);
			}
		}

		output += prefix + message;
	}

	let timestamp = getTimestamp();

	if (color === null) {
		stream(`${timestamp} | ${output}`);
	} else {
		stream(color(`${timestamp} | ${output}`));
	}
}

function getTimestamp() {
	let date = new Date();

	let year = date.getFullYear();
	let month = pad(date.getMonth() + 1);
	let day = pad(date.getDate());
	let hour = pad(date.getHours());
	let minute = pad(date.getMinutes());
	let second = pad(date.getSeconds());

	return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

function pad(number) {
	return (number < 10) ? ("0" + number) : number;
}

function success(...args) {
	write(console.log, chalk.green, [...args]);
}

function info(...args) {
	// Handle light and dark terminal backgrounds by not specifying a color.
	write(console.info, null, [...args]);
}

function warn(...args) {
	write(console.warn, chalk.yellow, [...args]);
}

function error(...args) {
	write(console.error, chalk.red, [...args]);
}

module.exports = {
	getTimestamp,
	success,
	info,
	warn,
	error,
};
<|endoftext|>


<commit_before>var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition

var SpeedySpeech = function( settings, callBack ) {

	if( !( this instanceof SpeedySpeech ) )
		return new SpeedySpeech( settings, callBack );

	var keywords = settings.keywords;

	if( !keywords ) {

		throw new Error( 'you must pass in keywords' );
	}

	if( !SpeechRecognition ) {

		callBack( new Error( 'speech recognition is not available' ) );
		return;
	}

	this.isRecognizing = false;
	this.keyWordConfidence = settings.keyWordConfidence || 0.7;
	this.autoRestart = settings.autoRestart || false;
	this.onTimeOut = settings.onTimeOut || null;
	this.setKeywords( keywords );

	this.callBack = callBack;

	this.onRResult = this.onRResult.bind( this );
	this.onREnd = this.onREnd.bind( this );
	this.onRError = this.onRError.bind( this );

	this.recognition = new SpeechRecognition();

	if( settings.language )
		this.recognition.lang = settings.language;

	this.recognition.onstart = this.onRStart;
	this.recognition.onresult = this.onRResult;
	this.recognition.onend = this.onREnd;
	this.recognition.onerror = this.onRError;

	this.result = null;
	this.confidence = null;
	this.foundWord = null;

	this.recognition.interimResults = true;
};

SpeedySpeech.isAvailable = Boolean( SpeechRecognition );

SpeedySpeech.prototype = {

	start: function() {

		if( !this.isRecognizing ) {

			this.isRecognizing = true;
			this.recognition.start();
		}
	},

	stop: function() {

		if( this.isRecognizing ) {

			this.recognition.abort();
		}
	},

	setKeywords: function( keywords ) {

		this.keyLookup = {};

		for( var i = 0, len = keywords.length; i < len; i++ ) {

			this.keyLookup[ keywords[ i ].toLowerCase() ] = true;
		}
	},

	onRResult: function( ev ) {

		var results = ev.results,
			result = [],
			resultPart, words, result, foundWord, confidence, isFinal;

		for( var i = 0, len = results.length; i < len; i++ ) {

			if( !results[ i ].isFinal ) {

				for( var j = 0, lenJ = results[ i ].length; j < lenJ; j++ ) {

					resultPart = results[ i ][ j ];
					words = resultPart.transcript.toLowerCase().split( ' ' );

					for( var k = 0, lenK = words.length; k < lenK; k++ ) {

						if( this.keyLookup[ words[ k ] ] ) {

							if( resultPart.confidence > this.keyWordConfidence &&
								( confidence === undefined || resultPart.confidence > confidence ) ) {

								foundWord = words[ k ];
								confidence = resultPart.confidence;
							}
						}
					}

					result.push( resultPart.transcript );
				}
			} else {

				isFinal = true;
				result = [ results[ i ][ 0 ].transcript ];
				confidence = results[ i ][ 0 ].confidence;

				break; //since this is final we'll break out
			}
		}

		if( foundWord || isFinal ) {

			this.stop();

			this.result = result.join( '' );
			this.confidence = confidence;
			this.foundWord = foundWord;

			console.log( 'got something' );
		}
	},

	onREnd: function() {

		this.isRecognizing = false;

		// if speech recognition has stopped and we don't have a result
		// then we'll auto restart
		if( !this.result ) {

			if( this.autoRestart ) {

				this.start();
			}

			if( this.onTimeOut )
				this.onTimeOut();
		// since we have a result we'll just return it
		} else {

			this.callBack( undefined, this.result, this.confidence, this.foundWord );

			this.result = null;
			this.confidence = null;
			this.foundWord = null;
		}
	},

	onRError: function( err ) {

		if( err.error == 'not-allowed' ) {

			this.callBack( new Error( 'user denied speech recognition' ) );

		//aborted is when the stop has been called
		} else if( err.error != 'aborted' ) {

			this.callBack( err );
		}
	}
};

module.exports = SpeedySpeech;<commit_msg>Differianted how user stop and recognition stop are handled<commit_after>var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition

var SpeedySpeech = function( settings, callBack ) {

	if( !( this instanceof SpeedySpeech ) )
		return new SpeedySpeech( settings, callBack );

	var keywords = settings.keywords;

	if( !keywords ) {

		throw new Error( 'you must pass in keywords' );
	}

	if( !SpeechRecognition ) {

		callBack( new Error( 'speech recognition is not available' ) );
		return;
	}

	this.isRecognizing = false;
	this.keyWordConfidence = settings.keyWordConfidence || 0.7;
	this.autoRestart = settings.autoRestart || false;
	this.onTimeOut = settings.onTimeOut || null;
	this.setKeywords( keywords );

	this.callBack = callBack;

	this.onRResult = this.onRResult.bind( this );
	this.onREnd = this.onREnd.bind( this );
	this.onRError = this.onRError.bind( this );

	this.recognition = new SpeechRecognition();

	if( settings.language )
		this.recognition.lang = settings.language;

	this.recognition.onstart = this.onRStart;
	this.recognition.onresult = this.onRResult;
	this.recognition.onend = this.onREnd;
	this.recognition.onerror = this.onRError;

	this.result = null;
	this.confidence = null;
	this.foundWord = null;

	this.recognition.interimResults = true;
};

SpeedySpeech.isAvailable = Boolean( SpeechRecognition );

SpeedySpeech.prototype = {

	start: function() {

		if( !this.isRecognizing ) {

			this.isRecognizing = true;
			this.recognition.start();
		}
	},

	stop: function() {

		this.recognition.onend = null;

		if( this.isRecognizing ) {

			this.recognition.abort();
		}

		this.isRecognizing = false;
	},

	setKeywords: function( keywords ) {

		this.keyLookup = {};

		for( var i = 0, len = keywords.length; i < len; i++ ) {

			this.keyLookup[ keywords[ i ].toLowerCase() ] = true;
		}
	},

	onRResult: function( ev ) {

		var results = ev.results,
			result = [],
			resultPart, words, result, foundWord, confidence, isFinal;

		for( var i = 0, len = results.length; i < len; i++ ) {

			if( !results[ i ].isFinal ) {

				for( var j = 0, lenJ = results[ i ].length; j < lenJ; j++ ) {

					resultPart = results[ i ][ j ];
					words = resultPart.transcript.toLowerCase().split( ' ' );

					for( var k = 0, lenK = words.length; k < lenK; k++ ) {

						if( this.keyLookup[ words[ k ] ] ) {

							if( resultPart.confidence > this.keyWordConfidence &&
								( confidence === undefined || resultPart.confidence > confidence ) ) {

								foundWord = words[ k ];
								confidence = resultPart.confidence;
							}
						}
					}

					result.push( resultPart.transcript );
				}
			} else {

				isFinal = true;
				result = [ results[ i ][ 0 ].transcript ];
				confidence = results[ i ][ 0 ].confidence;

				break; //since this is final we'll break out
			}
		}

		if( foundWord || isFinal ) {

			// this will cause the speech recognition to end
			// and for recognition callback to be sent out
			this.recognition.abort();

			this.result = result.join( '' );
			this.confidence = confidence;
			this.foundWord = foundWord;
		}
	},

	onREnd: function() {

		this.isRecognizing = false;

		// if speech recognition has stopped and we don't have a result
		// then we'll auto restart
		if( !this.result ) {

			if( this.autoRestart ) {

				this.start();
			}

			if( this.onTimeOut )
				this.onTimeOut();
		// since we have a result we'll just return it
		} else {

			this.callBack( undefined, this.result, this.confidence, this.foundWord );

			this.result = null;
			this.confidence = null;
			this.foundWord = null;
		}
	},

	onRError: function( err ) {

		if( err.error == 'not-allowed' ) {

			this.callBack( new Error( 'user denied speech recognition' ) );

		//aborted is when the stop has been called
		} else if( err.error != 'aborted' ) {

			this.callBack( err );
		}
	}
};

module.exports = SpeedySpeech;<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
$(function() {
  var word_score;
  $("#password").keyup(function() {
    var crack_time, display, passtext, result, word;
    passtext = $(this).val();
    result = zxcvbn(passtext);
    if (passtext.length < 6) {
      $("#password_strength").html('');
      return $("#password_alert").fadeOut();
    } else {
      word = word_score(result.score);
      crack_time = result.crack_time_display;
      if (crack_time === "instant") {
        crack_time = "a second";
      }
      display = "This is " + word + " password. It can be cracked in " + crack_time + ".";
      $("#password_strength").html(display);
      return $("#password_alert").fadeIn();
    }
  });
  return word_score = function(num_score) {
    var mapping, result;
    num_score = parseInt(num_score);
    console.log("num_score is:", num_score);
    mapping = {
      0: "a terrible",
      1: "a bad",
      2: "a mediocre",
      3: "a good",
      4: "an excellent"
    };
    console.log("mapping is:", mapping);
    result = mapping[num_score];
    console.log("result is:", result);
    return result;
  };
});
<commit_msg>modify check for password strength<commit_after>// Generated by CoffeeScript 1.8.0
// edited by alex date on 28/01/2021

$(function() {
  var word_score;
  $("#password").keyup(function() {
    var crack_time, display, passtext, result, word;
    passtext = $(this).val();
    result = zxcvbn(passtext);
    if (passtext.length < 6) {
      let error_message = `<strong style="color:red;">the password must have a length greater than six characters</strong>`
      $("#password_strength").html(error_message);
      return $("#password_alert").fadeIn();
    } else {
      word = word_score(result.score);
      crack_time = result.crack_times_display.online_throttling_100_per_hour;
      if (crack_time === "instant") {
        crack_time = "a second";
      }
      display = `This is ${word} password.`
      $("#password_strength").html(display);
      return $("#password_alert").fadeIn();
    }
  });
  return word_score = function(num_score) {
    num_score = parseInt(num_score);
    console.log("num_score is:", num_score);

    let passwordFeedback = {
      0:{
        color:"#cc1818",
        feedback:"a weak"
      },

      1:{
        color:"#cc1818",
        feedback:"a bad"
      },

      2:{
        color:"#f59105",
        feedback:"a mediocre"
      },

      3:{
        color:"#44ba34",
        feedback:"a strong"
      },
      4:{
        color:"green",
        feedback:"a stronger"
      }
    }

    mappingResult = `<strong style="color:${passwordFeedback[num_score].color};">${passwordFeedback[num_score].feedback}</strong>`
    return mappingResult;
  };
});
<|endoftext|>


<commit_before>const Promise = require('bluebird')
const rabbot = require('rabbot')
const transformConfig = require('./lib/transformConfig')
const errors = require('./lib/errors')

const request = require('./lib/request')
const respond = require('./lib/respond')

const send = require('./lib/send')
const receive = require('./lib/receive')

const publish = require('./lib/pub')
const subscribe = require('./lib/sub')

const RabRPC = {
  configure (config, transform = true) {
    const rabbotConfig = transform ? transformConfig(config) : config
    return Promise.resolve(rabbot.configure(rabbotConfig))
    .tap(() => { this.initialized = true })
    .catch(error => {
      this.initialized = false
      if (typeof error === 'string') {
        throw new errors.RabRPCError(error)
      } else {
        throw error
      }
    })
  },
  closeAll (reset) {
    if (this.initialized) {
      this.initialized = false
      return rabbot.closeAll(reset)
    }
    return Promise.resolve()
  },
  shutdown () {
    if (this.initialized) {
      this.initialized = false
      return rabbot.shutdown()
    }
    return Promise.resolve()
  },
  request,
  respond,
  send,
  receive,
  publish,
  subscribe
}

module.exports = RabRPC
module.exports.errors = errors
<commit_msg>debug added<commit_after>const Promise = require('bluebird')
const rabbot = require('rabbot')
const transformConfig = require('./lib/transformConfig')
const errors = require('./lib/errors')

const debug = require('debug')('rabrpc')

const request = require('./lib/request')
const respond = require('./lib/respond')

const send = require('./lib/send')
const receive = require('./lib/receive')

const publish = require('./lib/pub')
const subscribe = require('./lib/sub')

const RabRPC = {
  configure (config, transform = true) {
    debug('rabrpc config: %j', config)
    const rabbotConfig = transform ? transformConfig(config) : config
    debug('rabbot config: %j', rabbotConfig)
    return Promise.resolve(rabbot.configure(rabbotConfig))
    .tap(() => { this.initialized = true })
    .catch(error => {
      this.initialized = false
      debug('initialization error:', error)
      if (typeof error === 'string') {
        throw new errors.RabRPCError(error)
      } else {
        throw error
      }
    })
  },
  closeAll (reset) {
    if (this.initialized) {
      debug('closeAll: rabrpc was initialized, call rabbot.closeAll')
      this.initialized = false
      return rabbot.closeAll(reset)
    }
    debug('closeAll: rabrpc was NOT initialized, skip')
    return Promise.resolve()
  },
  shutdown () {
    if (this.initialized) {
      debug('shutdown: rabrpc was initialized, call rabbot.shutdown')
      this.initialized = false
      return rabbot.shutdown()
    }
    debug('shutdown: rabrpc was NOT initialized, skip')
    return Promise.resolve()
  },
  request,
  respond,
  send,
  receive,
  publish,
  subscribe
}

module.exports = RabRPC
module.exports.errors = errors
<|endoftext|>


<commit_before>module.exports = {
    'plugins': [
        'jsdoc'
    ],
    'rules': {
        'curly': [2, 'all'],
        'eqeqeq': 2,
        'wrap-iife': 2,
        'no-use-before-define': [2, {
            'functions': false
        }],
        'no-caller': 2,
        'no-irregular-whitespace': 2,
        'no-undef': 2,
        'no-unused-vars': 2,
        'linebreak-style': [2, 'unix'],
        'comma-style': [2, 'last'],
        'dot-notation': 2,
        'no-empty': 2,
        'no-spaced-func': 2,
        'array-bracket-spacing': [2, 'never'],
        'space-in-parens': [2, 'never'],
        'key-spacing': [2, {
            'beforeColon': false,
            'afterColon': true
        }],
        'object-curly-spacing': [2, 'always'],
        'space-unary-ops': [2, {
            'words': false,
            'nonwords': false
        }],
        'one-var': [2, {
            'uninitialized': 'always',
            'initialized': 'never'
        }],
        'no-mixed-spaces-and-tabs': 2,
        'no-trailing-spaces': 2,
        'no-with': 2,
        'brace-style': 2,
        'no-multiple-empty-lines': 2,
        'no-multi-str': 2,
        'space-before-blocks': [2, 'always'],
        'space-infix-ops': 2,
        'camelcase': [2, {
            'properties': 'never'
        }],
        'eol-last': 2,
        'keyword-spacing': [2, {
            'overrides': {
                'if': {
                    'after': true
                },
                'else': {
                    'after': true
                },
                'for': {
                    'after': true
                },
                'while': {
                    'after': true
                },
                'do': {
                    'after': true
                },
                'switch': {
                    'after': true
                },
                'case': {
                    'after': true
                },
                'return': {
                    'after': true
                },
                'try': {
                    'after': true
                },
                'catch': {
                    'after': true
                },
                'typeof': {
                    'after': true
                }
            }
        }],
        'lines-around-comment': [2, {
            'beforeBlockComment': true,
            'afterBlockComment': false,
            'beforeLineComment': false,
            'afterLineComment': false,
            'allowBlockStart': true,
            'allowObjectStart': true,
            'allowArrayStart': true
        }],
        'semi': [2, 'always'],
        'consistent-this': [2, 'self'],
        'quotes': [2, 'single', {
            'avoidEscape': true,
            'allowTemplateLiterals': true
        }],
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'valid-jsdoc': [1, {
            'prefer': {
                'return': 'returns'
            },
            'requireReturn': false
        }],
        'jsdoc/require-hyphen-before-param-description': 1
    }
};
<commit_msg>Add no-var and prefer-const rules<commit_after>module.exports = {
    'plugins': [
        'jsdoc'
    ],
    'rules': {
        'curly': [2, 'all'],
        'eqeqeq': 2,
        'wrap-iife': 2,
        'no-use-before-define': [2, {
            'functions': false
        }],
        'no-caller': 2,
        'no-irregular-whitespace': 2,
        'no-undef': 2,
        'no-unused-vars': 2,
        'prefer-const': 2,
        'no-var': 2,
        'linebreak-style': [2, 'unix'],
        'comma-style': [2, 'last'],
        'dot-notation': 2,
        'no-empty': 2,
        'no-spaced-func': 2,
        'array-bracket-spacing': [2, 'never'],
        'space-in-parens': [2, 'never'],
        'key-spacing': [2, {
            'beforeColon': false,
            'afterColon': true
        }],
        'object-curly-spacing': [2, 'always'],
        'space-unary-ops': [2, {
            'words': false,
            'nonwords': false
        }],
        'one-var': [2, {
            'uninitialized': 'always',
            'initialized': 'never'
        }],
        'no-mixed-spaces-and-tabs': 2,
        'no-trailing-spaces': 2,
        'no-with': 2,
        'brace-style': 2,
        'no-multiple-empty-lines': 2,
        'no-multi-str': 2,
        'space-before-blocks': [2, 'always'],
        'space-infix-ops': 2,
        'camelcase': [2, {
            'properties': 'never'
        }],
        'eol-last': 2,
        'keyword-spacing': [2, {
            'overrides': {
                'if': {
                    'after': true
                },
                'else': {
                    'after': true
                },
                'for': {
                    'after': true
                },
                'while': {
                    'after': true
                },
                'do': {
                    'after': true
                },
                'switch': {
                    'after': true
                },
                'case': {
                    'after': true
                },
                'return': {
                    'after': true
                },
                'try': {
                    'after': true
                },
                'catch': {
                    'after': true
                },
                'typeof': {
                    'after': true
                }
            }
        }],
        'lines-around-comment': [2, {
            'beforeBlockComment': true,
            'afterBlockComment': false,
            'beforeLineComment': false,
            'afterLineComment': false,
            'allowBlockStart': true,
            'allowObjectStart': true,
            'allowArrayStart': true
        }],
        'semi': [2, 'always'],
        'consistent-this': [2, 'self'],
        'quotes': [2, 'single', {
            'avoidEscape': true,
            'allowTemplateLiterals': true
        }],
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'valid-jsdoc': [1, {
            'prefer': {
                'return': 'returns'
            },
            'requireReturn': false
        }],
        'jsdoc/require-hyphen-before-param-description': 1
    }
};
<|endoftext|>


<commit_before>/* jshint node:true */

var _ = require('lodash');

module.exports = aposPreferences;

function aposPreferences(options, callback) {
  return new aposPreferences.Construct(options, callback);
}

aposPreferences.Construct = function(options, callback) {
  var self = this;

  // you need a schema since there isn't one by default!
  if(!options.schema) {
    throw new Error('apos-preferences: You need to specify a schema in order to use this module.');
  }

  // =================================================================
  // CONFIGURATION
  // =================================================================

  self._app = options.app;
  self._apos = options.apos;
  self._schemas = options.schemas;
  self._schema = self._schemas.compose(options.schema);

  self._preferences = self._apos.db.collection('aposPreferences');

  self._apos.mixinModuleAssets(self, 'aposPreferences', __dirname, options);
  self.pushAsset('script', 'editor', { when: 'user' });
  self.pushAsset('template', 'manage', { when: 'user', data: { fields: self._schema } });

  self._apos.addLocal('aposPreferencesMenu', function(permissions) {
    if (!permissions.admin) {
      // Oh heck no
      return '';
    }
    return self.render(__dirname + '/views/preferencesMenu', {});
  });

  self._apos.pushGlobalData({
    aposPreferences: {
      schema: self._schema
    }
  });

  options.modules = (options.modules || []).concat([ { dir: __dirname, name: 'events' } ]);

  // =================================================================
  // ROUTES
  // =================================================================

  self._app.get('/apos-preferences', function(req, res) {
    if((!req.user) || (!req.user.permissions.admin)) {
      res.statusCode = 403;
      return res.send();
    }
    self._preferences.find().toArray( function(err, results) {
      if (results.length) {
        return res.json( _.omit(results[0], '_id') );
      } else {
        return res.send({ status: 'ok', errors: 'No Preferences Results' });
      }
    });
  });

  self._app.post('/apos-preferences', function(req, res) {
    if((!req.user) || (!req.user.permissions.admin)) {
      res.statusCode = 403;
      return res.send();
    }
    var values = {};
    return self._schemas.convertFields(req, self._schema, 'form', req.body, values, function(err) {
      if (err) {
        return res.send({ status: 'Error', errors: err });
      } else {

        self._preferences.find().toArray( function(err, results) {
          var newPrefs = _.merge((results.length ? results[0] : {}), values );
          self._preferences.save(newPrefs, function(err) {
            return res.send({
              status: err ? 'Error' : 'ok',
              errors: err
            });
          });
        });
      }
    });
  });

  // Put the preferences in req.extras. If req.extras does not exist
  // it is created. This way the method can be called directly when
  // you're not generating an A2 page response, for instance from
  // an AJAX action.
  //
  // For bc reasons this method must be called self.loader, which makes
  // it a page loader. But we now also invoke it from middleware, to make
  // the data available in contexts like the notfound template. So there is
  // a built-in guard against loading twice.

  self.loader = function(req, callback) {
    if (req._aposPreferencesLoaded) {
      return setImmediate(callback);
    }
    req.extras = req.extras || {};
    self._preferences.find().toArray( function(err, results) {
      req._aposPreferencesLoaded = true;
      req.extras.preferences = {};
      if (err) {
        return callback(err);
      }
      if (results.length) {
        req.extras.preferences = _.omit(results[0], '_id');
      }
      return callback(null);
    });
  };

  self.middleware = [
    function(req, res, next) {
      return self.loader(req, function(err) {
        if (err) {
          res.statusCode = 500;
          req.template = 'serverError';
          return res.send(self.renderPage(req, 'pages/serverError.html', {}, 'always'));
        }
        return next();
      });
    }
  ];

  // Must wait at least until next tick to invoke callback!
  if (callback) {
    process.nextTick(function() { return callback(null); });
  }
};
<commit_msg>render the serverError template on a preferences error<commit_after>/* jshint node:true */

var _ = require('lodash');

module.exports = aposPreferences;

function aposPreferences(options, callback) {
  return new aposPreferences.Construct(options, callback);
}

aposPreferences.Construct = function(options, callback) {
  var self = this;

  // you need a schema since there isn't one by default!
  if(!options.schema) {
    throw new Error('apos-preferences: You need to specify a schema in order to use this module.');
  }

  // =================================================================
  // CONFIGURATION
  // =================================================================

  self._app = options.app;
  self._apos = options.apos;
  self._schemas = options.schemas;
  self._schema = self._schemas.compose(options.schema);

  self._preferences = self._apos.db.collection('aposPreferences');

  self._apos.mixinModuleAssets(self, 'aposPreferences', __dirname, options);
  self.pushAsset('script', 'editor', { when: 'user' });
  self.pushAsset('template', 'manage', { when: 'user', data: { fields: self._schema } });

  self._apos.addLocal('aposPreferencesMenu', function(permissions) {
    if (!permissions.admin) {
      // Oh heck no
      return '';
    }
    return self.render(__dirname + '/views/preferencesMenu', {});
  });

  self._apos.pushGlobalData({
    aposPreferences: {
      schema: self._schema
    }
  });

  options.modules = (options.modules || []).concat([ { dir: __dirname, name: 'events' } ]);

  // =================================================================
  // ROUTES
  // =================================================================

  self._app.get('/apos-preferences', function(req, res) {
    if((!req.user) || (!req.user.permissions.admin)) {
      res.statusCode = 403;
      return res.send();
    }
    self._preferences.find().toArray( function(err, results) {
      if (results.length) {
        return res.json( _.omit(results[0], '_id') );
      } else {
        return res.send({ status: 'ok', errors: 'No Preferences Results' });
      }
    });
  });

  self._app.post('/apos-preferences', function(req, res) {
    if((!req.user) || (!req.user.permissions.admin)) {
      res.statusCode = 403;
      return res.send();
    }
    var values = {};
    return self._schemas.convertFields(req, self._schema, 'form', req.body, values, function(err) {
      if (err) {
        return res.send({ status: 'Error', errors: err });
      } else {

        self._preferences.find().toArray( function(err, results) {
          var newPrefs = _.merge((results.length ? results[0] : {}), values );
          self._preferences.save(newPrefs, function(err) {
            return res.send({
              status: err ? 'Error' : 'ok',
              errors: err
            });
          });
        });
      }
    });
  });

  // Put the preferences in req.extras. If req.extras does not exist
  // it is created. This way the method can be called directly when
  // you're not generating an A2 page response, for instance from
  // an AJAX action.
  //
  // For bc reasons this method must be called self.loader, which makes
  // it a page loader. But we now also invoke it from middleware, to make
  // the data available in contexts like the notfound template. So there is
  // a built-in guard against loading twice.

  self.loader = function(req, callback) {
    if (req._aposPreferencesLoaded) {
      return setImmediate(callback);
    }
    req.extras = req.extras || {};
    self._preferences.find().toArray( function(err, results) {
      req._aposPreferencesLoaded = true;
      req.extras.preferences = {};
      if (err) {
        return callback(err);
      }
      if (results.length) {
        req.extras.preferences = _.omit(results[0], '_id');
      }
      return callback(null);
    });
  };

  self.middleware = [
    function(req, res, next) {
      return self.loader(req, function(err) {
        if (err) {
          res.statusCode = 500;
          req.template = 'serverError';
          return res.send(options.pages.renderPage(req, options.apos.options.rootDir + '/views/pages/serverError', {}, 'anon'));
        }
        return next();
      });
    }
  ];

  // Must wait at least until next tick to invoke callback!
  if (callback) {
    process.nextTick(function() { return callback(null); });
  }
};
<|endoftext|>


<commit_before>var INDENT = '    ';

var type = function(doc) {
	if (doc === null) return 'null';
	if (Array.isArray(doc)) return 'array';
	if (typeof doc === 'string' && /https?:/.test(doc)) return 'link';

	return typeof doc;
};

var escape = function(str) {
	return str.replace(/</g, '<').replace(/>/g, '>');
};

module.exports = function(doc) {
	var indent = '';

	var forEach = function(list, start, end, fn) {
		if (!list.length) return start+' '+end;

		var out = start+'\n';

		indent += INDENT;
		list.forEach(function(key, i) {
			out += indent+fn(key)+(i < list.length-1 ? ',' : '')+'\n';
		});
		indent = indent.slice(0, -INDENT.length);

		return out + indent+end;
	};

	var visit = function(obj) {
		if (obj === undefined) return '';

		switch (type(obj)) {
			case 'boolean':
			return ''+obj+'';

			case 'number':
			return ''+obj+'';

			case 'null':
			return 'null\n';

			case 'string':
			return '"'+escape(obj.replace(/\n/g, '\n'+indent))+'"';

			case 'link':
			return '"'+escape(obj)+'"';

			case 'array':
			return forEach(obj, '[', ']', visit);

			case 'object':
			var keys = Object.keys(obj).filter(function(key) {
				return obj[key] !== undefined;
			});

			return forEach(keys, '{', '}', function(key) {
				return ''+key + ': '+visit(obj[key]);
			});
		}

		return '';
	};

	return '
'+visit(doc)+'
';
};
<commit_msg>fixed link parsing<commit_after>var INDENT = '    ';

var type = function(doc) {
	if (doc === null) return 'null';
	if (Array.isArray(doc)) return 'array';
	if (typeof doc === 'string' && /^https?:/.test(doc)) return 'link';

	return typeof doc;
};

var escape = function(str) {
	return str.replace(/</g, '<').replace(/>/g, '>');
};

module.exports = function(doc) {
	var indent = '';

	var forEach = function(list, start, end, fn) {
		if (!list.length) return start+' '+end;

		var out = start+'\n';

		indent += INDENT;
		list.forEach(function(key, i) {
			out += indent+fn(key)+(i < list.length-1 ? ',' : '')+'\n';
		});
		indent = indent.slice(0, -INDENT.length);

		return out + indent+end;
	};

	var visit = function(obj) {
		if (obj === undefined) return '';

		switch (type(obj)) {
			case 'boolean':
			return ''+obj+'';

			case 'number':
			return ''+obj+'';

			case 'null':
			return 'null\n';

			case 'string':
			return '"'+escape(obj.replace(/\n/g, '\n'+indent))+'"';

			case 'link':
			return '"'+escape(obj)+'"';

			case 'array':
			return forEach(obj, '[', ']', visit);

			case 'object':
			var keys = Object.keys(obj).filter(function(key) {
				return obj[key] !== undefined;
			});

			return forEach(keys, '{', '}', function(key) {
				return ''+key + ': '+visit(obj[key]);
			});
		}

		return '';
	};

	return '
'+visit(doc)+'
';
};
<|endoftext|>


<commit_before>// Main file

var art = require('ascii-art'),
    ntpClient = require('ntp-client');

/*
art.font('Demo!', 'Doom', function(rendered){
    console.log(art.style(rendered, 'blue_bg+red+blink+inverse'));
});

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    console.log("Current time : ");
    console.log(date);
});

*/

function pad(i) {
  if (i < 10) {
    return "0" + i;
  }

  return i;
}

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

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    var sysdate = new Date();

    console.log("Current time : ", date);
    console.log("System Time : ", sysdate);

    console.log("Skew: ", Math.abs(sysdate - date));

  art.font(formatDate(date), 'Doom', function(rendered) {
    if (Math.abs(sysdate - date) < 1 * 60 * 1000) { // If skew is bigger than 1000
      console.log(art.style(rendered, 'blue_bg+red'));
    }
    else {
      console.log(rendered);
    }
  });
});<commit_msg>Updated index.js<commit_after>// Main file

var art = require('ascii-art'),
    ntpClient = require('ntp-client');

function pad(i) {
  if (i < 10) {
    return "0" + i;
  }

  return i;
}

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

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    var sysdate = new Date();

    console.log("Current time : ", date);
    console.log("System Time : ", sysdate);

    console.log("Skew: ", Math.abs(sysdate - date));

  art.font(formatDate(date), 'Doom', function(rendered) {
    if (Math.abs(sysdate - date) < 1 * 60 * 1000) { // If skew is bigger than 1000
      console.log(art.style(rendered, 'blue_bg+red'));
    }
    else {
      console.log(rendered);
    }
  });
});<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const mongodb = require("mongodb");
const moment = require('moment');

const settings = JSON.parse(fs.readFileSync('data/settings.json', 'utf8'));
const departments = JSON.parse(fs.readFileSync('data/departments.json', 'utf8'));
const doctors = JSON.parse(fs.readFileSync('data/doctors.json', 'utf8'));
var ObjectID = mongodb.ObjectID;
const MEETING_COLLECTION = 'meeting_default';

//var apiai = require("./module/apiai");
//var app = apiai(settings.accessToken);

const app = express();

app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(settings.mongoURI, function (err, database) {
    if (err) {
        console.log(err);
        process.exit(1);
    }

    // Save database object from the callback for reuse.
    db = database;
    console.log("Database connection ready");

    // Initialize the app.

    app.listen((process.env.PORT || 5000), function () {
        console.log("Server listening");
    });

});

app.post('/hook', function (req, res) {

    console.log('HOOK REQUEST');
    console.log('++++++++++++++');

    try {
        var speech = 'empty speech';
        var returnContext = [];

        if (req.body) {
            var requestBody = req.body;

            var sessionId = requestBody.sessionId;

            switch(requestBody.result.action){

                case 'search.doctorsByDepartment':

                    /*  searching doctors by department */

                    console.log('Fired: search.doctorsByDepartment');

                    speech = '';
                    returnContext = [];

                    var requestedDepartment = departments.filter(function(dept){
                        return (dept.value === requestBody.result.parameters.department);
                    });

                    var doctorForDept = doctors.filter(function(doc){
                        return (doc.department === requestBody.result.parameters.department);
                    });

                    var doctorNames = [];
                    doctorForDept.forEach(function(doc){
                        doctorNames.push(doc.title);

                    });

                    if(doctorNames){

                        speech = 'Available doctors from ' + requestedDepartment[0].title + ' department are: ' + doctorNames.join(',');

                    } else {
                        speech = 'No doctors are available for ' + requestedDepartment[0].title;
                    }

                    callback(res,speech,returnContext);

                    break;

                case 'choose.doctor':

                    /*  choosing doctor from selected department */

                    console.log('Fired: choose.doctor');
                    speech = '';
                    returnContext = [];

                    var preselectedDepartmentContext = requestBody.result.contexts.filter(function(context){
                        return context.name === 'getdoctorsbydepartment-followup';
                    })[0];

                    chooseDoctor(preselectedDepartmentContext,res);

                    break;

                case 'choose.doctor.confirm':

                    console.log('Fired: choose.doctor.confirm');
                    speech = '';
                    returnContext = [];

                    var preselectedDepartmentContext = requestBody.result.contexts.filter(function(context){
                        return context.name === 'getdoctorsbydepartment-followup';
                    })[0];

                    insertMeeting(preselectedDepartmentContext,res);

                    break;

            }   //end of switch
        }

    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

app.post('/getDoctors', function (req, res) {

    try{

        var payload ={};

        doctors.forEach(function(doc){

            var docObj ={
                'value':doc.value,
                'name':doc.title
            }

            payload[doc.department] = payload[doc.department]||[];
            payload[doc.department].push(docObj);

        });

         return res.json({
            status: {
                code: 200,
                type: 'success'
            },
            data: payload
        });

    } catch(err) {

        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });

    }

});

app.post('/getMeetingForDoctor', function (req, res) {

    try{

        var query = {"doctor_name": req.body.name};

          db.collection(MEETING_COLLECTION).find(query).toArray(function(err, meetings) {
            if (err) {
              handleError(res, err.message, "Failed to get contact");
            } else {

                var meetingList = [];

                meetings.forEach(function(meet){

                var meeting = {
                    title :"Appintment",
                    start: meet.start_date_time,
                    end: meet.end_date_time
                }

                    meetingList.push(meeting);

                });

                 return res.json({
                    status: {
                        code: 200,
                        type: 'success'
                    },
                    data: meetingList
                });

            }
          });

    } catch(err) {

        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });

    }

});

function chooseDoctor(preselectedDepartmentContext, res){

    var speech = '';
    var returnContext = [];

    var doctorCode = preselectedDepartmentContext.parameters['dept-doctors'];

    var preselectedDeptValue = preselectedDepartmentContext.parameters.department;

    var departmentWiseDoctorList = doctors.filter( function(doc) {
        return doc.department === preselectedDeptValue;
    });

    var docTitles = [];

    var selectedDoctorList = doctors.filter( function(doc) {
        return (doc.value === doctorCode);
    });

    if ( Object.keys(selectedDoctorList).length > 0) {
        var selectedDoctor = selectedDoctorList[0];
        var departmentOfDoctorCode = selectedDoctor.department;

        if (departmentOfDoctorCode === preselectedDepartmentContext.parameters.department) {

            var selectedDate = preselectedDepartmentContext.parameters.date || preselectedDepartmentContext.parameters.deptDate;
            var selectedTime = preselectedDepartmentContext.parameters.time || preselectedDepartmentContext.parameters.deptTime;

            if(selectedDate && selectedTime){

                returnContext = [{
                    "name":"has-date-time",
                    "lifespan":2,
                    "parameters":{}
                }];

		var meetingStartDateTime = moment(selectedDate + " " + selectedTime);
		var meetingStartDateTimeISO = meetingStartDateTime.toISOString();

		var condition = {
					"start_date_time": {
						"$lte":
							 new Date(meetingStartDateTimeISO)
					} ,
					  "end_date_time": {
						"$gte":
							 new Date(meetingStartDateTimeISO)
					} ,
					"doctor_name": doctorCode
				};

		db.collection('meeting_default').find(condition).count().then(function(numOfConfictMeetings) {
		  console.log('numOfConfictMeetings:'+numOfConfictMeetings);
		  if(numOfConfictMeetings === 0) {
			speech = 'Booking appointment with ' + selectedDoctor.title + ' on '+selectedDate + ' at ' + selectedTime + '. Do you confirm?';
			callback(res,speech,returnContext);

		  }
		  else {
			 speech = selectedDoctor.title + ' already booked on ' + selectedDate + ' at ' + selectedTime + ' Please choose a different time';
			 callback(res,speech,returnContext);

		  }
		});

            } else if(selectedDate) {
                returnContext = [{
                    "name":"has-date",
                    "lifespan":2,
                    "parameters":{}
                }];

                speech = 'Thanks for choosing ' + selectedDoctor.title + '. What is the best time that will work for you?';

            } else if(selectedTime) {
                returnContext = [{
                    "name":"has-time",
                    "lifespan":2,
                    "parameters":{}
                }];

                speech = 'Thanks for choosing ' + selectedDoctor.title + '. On which date should I book the appointment?';

            } else {
                returnContext = [{
                    "name":"has-nothing",
                    "lifespan":2,
                    "parameters":{}
                }];

                 speech = 'Thanks for choosing ' + selectedDoctor.title + '. When do you want to book the appointment?';
            }

        }  else {
            speech = 'Please choose from following list of doctors: ';

            for (var doc of departmentWiseDoctorList) {
                docTitles.push[doc.title];
                speech += ' '+ doc.title + ',';
            }

        }

    } else {
        speech = 'Please choose from following list of doctors:';

        for (var doc of departmentWiseDoctorList) {
            docTitles.push[doc.title];
            speech += ' '+ doc.title + ',';
        }

    }

    callback(res,speech,returnContext);

}

function insertMeeting(preselectedDepartmentContext, res){

    var speech = '';
    var returnContext = [];

    var selectedDate = preselectedDepartmentContext.parameters.date || preselectedDepartmentContext.parameters.deptDate;
    var selectedTime = preselectedDepartmentContext.parameters.time || preselectedDepartmentContext.parameters.deptTime;

    var timeArr = selectedTime.split(':');
    var dateTime = moment(selectedDate);
    dateTime = dateTime.set({
       'hour' : timeArr[0],
       'minute'  : timeArr[1],
       'second' : timeArr[2]
    });

    var newMeeting = {
        "doctor_name": preselectedDepartmentContext.parameters['dept-doctors'],
        "start_date_time": dateTime.toDate(),
        "end_date_time": dateTime.add(30, 'm').toDate(),
        "department": preselectedDepartmentContext.parameters.department
    }

    /* insert data to mongo*/

    db.collection(MEETING_COLLECTION).insertOne(newMeeting, function(err, doc) {

        if (err) {
            speech = 'Failed to book meeting!';

        } else {
            speech = 'BOOM!! booking done!';

        }

        callback(res,speech,returnContext);
    });

}

function callback(res,speech,returnContext){

    console.log('Speech');
    console.log('==================');
    console.log(speech);
    console.log('Context');
    console.log('==================');
    console.log(returnContext);

    return res.json({
        speech: speech,
        displayText: speech,
        contextOut:returnContext,
        source: 'bookjent'
    });

}

<commit_msg>indentation of same time appointment check<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const mongodb = require("mongodb");
const moment = require('moment');

const settings = JSON.parse(fs.readFileSync('data/settings.json', 'utf8'));
const departments = JSON.parse(fs.readFileSync('data/departments.json', 'utf8'));
const doctors = JSON.parse(fs.readFileSync('data/doctors.json', 'utf8'));
var ObjectID = mongodb.ObjectID;
const MEETING_COLLECTION = 'meeting_default';

//var apiai = require("./module/apiai");
//var app = apiai(settings.accessToken);

const app = express();

app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(settings.mongoURI, function (err, database) {
    if (err) {
        console.log(err);
        process.exit(1);
    }

    // Save database object from the callback for reuse.
    db = database;
    console.log("Database connection ready");

    // Initialize the app.

    app.listen((process.env.PORT || 5000), function () {
        console.log("Server listening");
    });

});

app.post('/hook', function (req, res) {

    console.log('HOOK REQUEST');
    console.log('++++++++++++++');

    try {
        var speech = 'empty speech';
        var returnContext = [];

        if (req.body) {
            var requestBody = req.body;

            var sessionId = requestBody.sessionId;

            switch(requestBody.result.action){

                case 'search.doctorsByDepartment':

                    /*  searching doctors by department */

                    console.log('Fired: search.doctorsByDepartment');

                    speech = '';
                    returnContext = [];

                    var requestedDepartment = departments.filter(function(dept){
                        return (dept.value === requestBody.result.parameters.department);
                    });

                    var doctorForDept = doctors.filter(function(doc){
                        return (doc.department === requestBody.result.parameters.department);
                    });

                    var doctorNames = [];
                    doctorForDept.forEach(function(doc){
                        doctorNames.push(doc.title);

                    });

                    if(doctorNames){

                        speech = 'Available doctors from ' + requestedDepartment[0].title + ' department are: ' + doctorNames.join(',');

                    } else {
                        speech = 'No doctors are available for ' + requestedDepartment[0].title;
                    }

                    callback(res,speech,returnContext);

                    break;

                case 'choose.doctor':

                    /*  choosing doctor from selected department */

                    console.log('Fired: choose.doctor');
                    speech = '';
                    returnContext = [];

                    var preselectedDepartmentContext = requestBody.result.contexts.filter(function(context){
                        return context.name === 'getdoctorsbydepartment-followup';
                    })[0];

                    chooseDoctor(preselectedDepartmentContext,res);

                    break;

                case 'choose.doctor.confirm':

                    console.log('Fired: choose.doctor.confirm');
                    speech = '';
                    returnContext = [];

                    var preselectedDepartmentContext = requestBody.result.contexts.filter(function(context){
                        return context.name === 'getdoctorsbydepartment-followup';
                    })[0];

                    insertMeeting(preselectedDepartmentContext,res);

                    break;

            }   //end of switch
        }

    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

app.post('/getDoctors', function (req, res) {

    try{

        var payload ={};

        doctors.forEach(function(doc){

            var docObj ={
                'value':doc.value,
                'name':doc.title
            }

            payload[doc.department] = payload[doc.department]||[];
            payload[doc.department].push(docObj);

        });

         return res.json({
            status: {
                code: 200,
                type: 'success'
            },
            data: payload
        });

    } catch(err) {

        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });

    }

});

app.post('/getMeetingForDoctor', function (req, res) {

    try{

        var query = {"doctor_name": req.body.name};

          db.collection(MEETING_COLLECTION).find(query).toArray(function(err, meetings) {
            if (err) {
              handleError(res, err.message, "Failed to get contact");
            } else {

                var meetingList = [];

                meetings.forEach(function(meet){

                var meeting = {
                    title :"Appintment",
                    start: meet.start_date_time,
                    end: meet.end_date_time
                }

                    meetingList.push(meeting);

                });

                 return res.json({
                    status: {
                        code: 200,
                        type: 'success'
                    },
                    data: meetingList
                });

            }
          });

    } catch(err) {

        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });

    }

});

function chooseDoctor(preselectedDepartmentContext, res){

    var speech = '';
    var returnContext = [];

    var doctorCode = preselectedDepartmentContext.parameters['dept-doctors'];

    var preselectedDeptValue = preselectedDepartmentContext.parameters.department;

    var departmentWiseDoctorList = doctors.filter( function(doc) {
        return doc.department === preselectedDeptValue;
    });

    var docTitles = [];

    var selectedDoctorList = doctors.filter( function(doc) {
        return (doc.value === doctorCode);
    });

    if ( Object.keys(selectedDoctorList).length > 0) {
        var selectedDoctor = selectedDoctorList[0];
        var departmentOfDoctorCode = selectedDoctor.department;

        if (departmentOfDoctorCode === preselectedDepartmentContext.parameters.department) {

            var selectedDate = preselectedDepartmentContext.parameters.date || preselectedDepartmentContext.parameters.deptDate;
            var selectedTime = preselectedDepartmentContext.parameters.time || preselectedDepartmentContext.parameters.deptTime;

            if(selectedDate && selectedTime){

                returnContext = [{
                    "name":"has-date-time",
                    "lifespan":2,
                    "parameters":{}
                }];

		var meetingStartDateTime = moment(selectedDate + " " + selectedTime);
		var meetingStartDateTimeISO = meetingStartDateTime.toISOString();

		var condition = {
					"start_date_time": {
						"$lte":
							 new Date(meetingStartDateTimeISO)
					} ,
					  "end_date_time": {
						"$gte":
							 new Date(meetingStartDateTimeISO)
					} ,
					"doctor_name": doctorCode
				};

		db.collection('meeting_default').find(condition).count().then(function(numOfConfictMeetings) {
		  console.log('numOfConfictMeetings:'+numOfConfictMeetings);
		  if(numOfConfictMeetings === 0) {
			speech = 'Booking appointment with ' + selectedDoctor.title + ' on '+selectedDate + ' at ' + selectedTime + '. Do you confirm?';
			callback(res,speech,returnContext);
		  }
		  else {
			 speech = selectedDoctor.title + ' already booked on ' + selectedDate + ' at ' + selectedTime + ' Please choose a different time';
			 callback(res,speech,returnContext);
		  }
		});

            } else if(selectedDate) {
                returnContext = [{
                    "name":"has-date",
                    "lifespan":2,
                    "parameters":{}
                }];

                speech = 'Thanks for choosing ' + selectedDoctor.title + '. What is the best time that will work for you?';

            } else if(selectedTime) {
                returnContext = [{
                    "name":"has-time",
                    "lifespan":2,
                    "parameters":{}
                }];

                speech = 'Thanks for choosing ' + selectedDoctor.title + '. On which date should I book the appointment?';

            } else {
                returnContext = [{
                    "name":"has-nothing",
                    "lifespan":2,
                    "parameters":{}
                }];

                 speech = 'Thanks for choosing ' + selectedDoctor.title + '. When do you want to book the appointment?';
            }

        }  else {
            speech = 'Please choose from following list of doctors: ';

            for (var doc of departmentWiseDoctorList) {
                docTitles.push[doc.title];
                speech += ' '+ doc.title + ',';
            }

        }

    } else {
        speech = 'Please choose from following list of doctors:';

        for (var doc of departmentWiseDoctorList) {
            docTitles.push[doc.title];
            speech += ' '+ doc.title + ',';
        }

    }

    callback(res,speech,returnContext);

}

function insertMeeting(preselectedDepartmentContext, res){

    var speech = '';
    var returnContext = [];

    var selectedDate = preselectedDepartmentContext.parameters.date || preselectedDepartmentContext.parameters.deptDate;
    var selectedTime = preselectedDepartmentContext.parameters.time || preselectedDepartmentContext.parameters.deptTime;

    var timeArr = selectedTime.split(':');
    var dateTime = moment(selectedDate);
    dateTime = dateTime.set({
       'hour' : timeArr[0],
       'minute'  : timeArr[1],
       'second' : timeArr[2]
    });

    var newMeeting = {
        "doctor_name": preselectedDepartmentContext.parameters['dept-doctors'],
        "start_date_time": dateTime.toDate(),
        "end_date_time": dateTime.add(30, 'm').toDate(),
        "department": preselectedDepartmentContext.parameters.department
    }

    /* insert data to mongo*/

    db.collection(MEETING_COLLECTION).insertOne(newMeeting, function(err, doc) {

        if (err) {
            speech = 'Failed to book meeting!';

        } else {
            speech = 'BOOM!! booking done!';

        }

        callback(res,speech,returnContext);
    });

}

function callback(res,speech,returnContext){

    console.log('Speech');
    console.log('==================');
    console.log(speech);
    console.log('Context');
    console.log('==================');
    console.log(returnContext);

    return res.json({
        speech: speech,
        displayText: speech,
        contextOut:returnContext,
        source: 'bookjent'
    });

}

<|endoftext|>


<commit_before>var nunjucks = require("nunjucks");

module.exports = function(env, callback) {
  var NunjucksTemplate = function(template) {
    this.template = template;
  };

  NunjucksTemplate.prototype.render = function render(locals, callback) {
    try {
      callback(null, new Buffer(this.template.render(locals)));
    } catch (error) {
      callback(error);
    }
  };

  NunjucksTemplate.fromFile = function fromFile(filepath, callback) {
    var nenv = new nunjucks.Environment(new nunjucks.FileSystemLoader(env.templatesPath));
    callback(null, new NunjucksTemplate(nenv.getTemplate(filepath.relative)));
  };

  env.registerTemplatePlugin("**/*.*(html|nunjucks)", NunjucksTemplate);

  callback();
};
<commit_msg>Added the option to use customer filters<commit_after>var nunjucks = require("nunjucks");
var path = require("path");

module.exports = function(env, callback) {
  var NunjucksTemplate = function(template) {
    this.template = template;
  };

  NunjucksTemplate.prototype.render = function render(locals, callback) {
    try {
      callback(null, new Buffer(this.template.render(locals)));
    } catch (error) {
      callback(error);
    }
  };

  loadFilters = function(nenv) {
    if(env.config.nunjucks) {
      if(env.config.nunjucks.filterdir) {
        env.config.nunjucks.filters.map( function (name) {
          file = path.join(env.config.nunjucks.filterdir, name + ".js");
          filter = env.loadModule(env.resolvePath(file), true);
          nenv.addFilter(name, filter);
        });
      }
    }
  };

  NunjucksTemplate.fromFile = function fromFile(filepath, callback) {
    var nenv = new nunjucks.Environment(new nunjucks.FileSystemLoader(env.templatesPath));
    loadFilters(nenv);
    callback(null, new NunjucksTemplate(nenv.getTemplate(filepath.relative)));
  };

  env.registerTemplatePlugin("**/*.*(html|nunjucks)", NunjucksTemplate);

  callback();
};
<|endoftext|>


<commit_before>"use strict";
var vueElementDialogDraggable = {}
vueElementDialogDraggable.install = function(Vue, options){

	Vue.directive('draggable', {

		bind : function(el, binding, vnode) {

			var dlg = el.getElementsByClassName("el-dialog")[0];
			var title = el.getElementsByClassName("el-dialog__title")[0];
			title.style.userSelect="none";
			title.style["-ms-user-select"] = "none";
			title.style["-moz-user-select"] = "none";
			title.style.cursor="default";

			dlg.offsetX = 0;
			dlg.offsetY = 0;

			var move = function(e){
				dlg.style.left = (e.pageX - dlg.offsetX) + 'px';
				dlg.style.top = (e.pageY - dlg.offsetY) + 'px';
			}

			var up = function() {
				removeEventListener('mousemove', move);
				removeEventListener('mouseup', up);
			}

			var down = function(e){
				dlg.offsetX = (e.pageX - dlg.offsetLeft);
				dlg.offsetY = (e.pageY - dlg.offsetTop );

				addEventListener('mousemove', move);
				addEventListener('mouseup', up);
			}

			var header = el.getElementsByClassName("el-dialog__header")[0];
			header.addEventListener('mousedown', down);
               }
	});
}

module.exports = vueElementDialogDraggable;
<commit_msg>fixed #1<commit_after>"use strict";
var vueElementDialogDraggable = {}
vueElementDialogDraggable.install = function(Vue, options){

	Vue.directive('draggable', {

		bind : function(el, binding, vnode) {

			var dlg = el.getElementsByClassName("el-dialog")[0];
			var title = el.getElementsByClassName("el-dialog__title")[0];
			title.style.userSelect="none";
			title.style["-ms-user-select"] = "none";
			title.style["-moz-user-select"] = "none";
			title.style.cursor="default";

			dlg.offsetX = 0;
			dlg.offsetY = 0;

			var move = function(e){
				dlg.style.marginLeft = '0px';
				dlg.style.marginTop = '0px';
				dlg.style.left = (e.pageX - dlg.offsetX) + 'px';
				dlg.style.top = (e.pageY - dlg.offsetY) + 'px';
			}

			var up = function() {
				removeEventListener('mousemove', move);
				removeEventListener('mouseup', up);
			}

			var down = function(e){
				dlg.offsetX = (e.pageX - dlg.offsetLeft);
				dlg.offsetY = (e.pageY - dlg.offsetTop );

				addEventListener('mousemove', move);
				addEventListener('mouseup', up);
			}

			var header = el.getElementsByClassName("el-dialog__header")[0];
			header.addEventListener('mousedown', down);
               }
	});
}

module.exports = vueElementDialogDraggable;
<|endoftext|>


<commit_before>const fs = require('fs');
const glob = require('glob');
const path = require('path');
const moment = require('moment');
const Parser = require('markdown-parser');
const TreeModel = require('tree-model');
const parser = new Parser();
const tree = new TreeModel();
const treeLevels = ['year', 'month', 'day'];

// Globals

let rootPath = '';

// For testing purposes
global.pluginRoot = path.resolve(__dirname);

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, result) => {
      if (err) return reject(err);
      resolve({contents: result, filePath});
    });
  });
};

function parse({contents, filePath}) {
  return new Promise((resolve, reject) => {
    parser.parse(contents, (err, parsed) => {
      if (err) return reject(err);
      resolve({parsed, filePath});
    });
  });
};

function getTitle({parsed, filePath}) {
  let title = '';
  if ( parsed.headings.length ) {
    title = parsed.headings[0].trim();
  }
  return Promise.resolve({title, filePath});
};

function twoDigitize(i) {
  return ('0' + i).slice(-2);
};

function getEntry({title, filePath}) {
  let fileName = path.parse(filePath).name;
  let date = moment(fileName);
  console.log(`DATE: ${date}`);
  const entry = {
    year: date.year(),
    month: date.month() + 1,
    day: date.date(),
    title,
    filePath
  };
  return Promise.resolve(entry);
};

function processFile(filePath) {
  return readFile(`${rootPath}/${filePath}`)
    .then(parse)
    .then(getTitle)
    .then(getEntry)
    .catch((reason) => {
      console.error(reason);
      throw reason;
    });
};

function insert(root, entry) {
  const {year, month} = entry;
  const strategy = {strategy: 'breadth'};
  let yearNode = root.first(strategy, (n) => n.model.year === year);
  if (!yearNode) yearNode = root.addChild(tree.parse({year}));
  let monthNode = yearNode.first(strategy, (n) => n.model.month === month);
  if (!monthNode) monthNode = yearNode.addChild(tree.parse({month}));
  monthNode.addChild(tree.parse(entry));
  return root;
};

// function insert(parent, entry, l = 0) {
//   if (l>2) return;
//   const level = treeLevels[l];
//   const strategy = {strategy: 'breadth'};
//   let node = parent.first(strategy, (n) => n.model[level] === entry[level]);
//   if (!node) {
//     node = tree.parse({[level]: entry[level]});
//     parent.addChild(node);
//   }
//   insert(node, entry, l++);
//   return parent;
// };

function buildTree(prev, curr) {
  return prev.then((root) =>
    curr.then((entry) =>
      insert(root, entry)
    )
  );
};

function generateSummaryTree() {
  return new Promise((resolve, reject) => {
    glob(
      `*/**/*.md`,
      {cwd: rootPath, ignore: ['node_modules/**']},
      (err, files) => {
        if (err) return reject(err);
        const root = tree.parse({name: 'root', children: []});
        return files.map(processFile)
          .reduce(buildTree, Promise.resolve(root))
          .then(resolve, (reason) => {
            console.error(reason);
            throw reason;
          });
    });
  });
};

function printTree(summaryTree, depth = 1) {
  // const node = Object.entries(summaryTree)[0]; // unwrap outer array
  // const root = node.shift(); // get first element of the array
  // const res = `${Array(depth).join('  ')}- [${root.title}](${root.filePath || ''})\n`;
  // node.forEach((children) => { // for each children of the node, we repeat
  //   res += printTree(children, res, depth + 1);
  // });
  console.log(`Is root? ${summaryTree.isRoot()}`);
  console.log(`Has Children? ${summaryTree.hasChildren()}`);
  res = '555';
  return res;
};

async function init() {
  const bookTitle = this.config.get('title');
  const summaryFilename = this.config.get('structure.summary');
  rootPath = this.resolve('');
  // readmeFilename = this.config.get('structure.readme');

  summaryTree = await generateSummaryTree();
  console.log(`SUMMARY TREE: \n\n${JSON.stringify(summaryTree, null, 2)}`);
  const summary = ( bookTitle ? `# ${bookTitle}\n\n` : '' ) + printTree(summaryTree);
  fs.writeFileSync( `${rootPath}/${summaryFilename}`, summary, 'utf8');
  console.log(`\x1b[36mgitbook-plugin-journal-summary: \x1b[32m${summaryFilename} generated successfully.`);
  return 0;
};

module.exports = {hooks: {'init': init}};
<commit_msg>it works!<commit_after>const fs = require('fs');
const glob = require('glob');
const path = require('path');
const moment = require('moment');
const Parser = require('markdown-parser');
const TreeModel = require('tree-model');
const parser = new Parser();
const tree = new TreeModel();
const treeLevels = ['year', 'month', 'day'];

// Globals

let rootPath = '';

// For testing purposes
global.pluginRoot = path.resolve(__dirname);

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, result) => {
      if (err) return reject(err);
      resolve({contents: result, filePath});
    });
  });
};

function parse({contents, filePath}) {
  return new Promise((resolve, reject) => {
    parser.parse(contents, (err, parsed) => {
      if (err) return reject(err);
      resolve({parsed, filePath});
    });
  });
};

function getTitle({parsed, filePath}) {
  let title = '';
  if ( parsed.headings.length ) {
    title = parsed.headings[0].trim();
  }
  return Promise.resolve({title, filePath});
};

function generateName(entry) {
  // TODO: Allow config for more title formats
  return `${entry.day} - ${entry.title}`
};

function getEntry({title, filePath}) {
  let fileName = path.parse(filePath).name;
  let date = moment(fileName);
  console.log(`DATE: ${date}`);
  const entry = {
    year: date.format('YYYY'),
    month: date.format('MMMM'), // TODO: Make customizable
    day: date.format('Do'),
    filePath: filePath.replace(rootPath, ''),
    title
  };
  entry.name = generateName(entry);
  return Promise.resolve(entry);
};

function processFile(filePath) {
  return readFile(`${rootPath}/${filePath}`)
    .then(parse)
    .then(getTitle)
    .then(getEntry)
    .catch((reason) => {
      console.error(reason);
      throw reason;
    });
};

function insert(root, entry) {
  const {year, month} = entry;
  entry.level = 2;
  entry.name = entry.title;
  const strategy = {strategy: 'breadth'};
  let yearNode = root.first(strategy, (n) => n.model.year === year);
  if (!yearNode) yearNode = root.addChild(tree.parse({name: year, level: 0}));
  let monthNode = yearNode.first(strategy, (n) => n.model.month === month);
  if (!monthNode) monthNode = yearNode.addChild(tree.parse({name: month, level: 1}));
  monthNode.addChild(tree.parse(entry));
  return root;
};

function buildTree(prev, curr) {
  return prev.then((root) =>
    curr.then((entry) =>
      insert(root, entry)
    )
  );
};

function generateSummaryTree() {
  return new Promise((resolve, reject) => {
    glob(
      `*/**/*.md`,
      {cwd: rootPath, ignore: ['node_modules/**']},
      (err, files) => {
        if (err) return reject(err);
        const root = tree.parse({name: 'root', children: []});
        return files.map(processFile)
          .reduce(buildTree, Promise.resolve(root))
          .then(resolve, (reason) => {
            console.error(reason);
            throw reason;
          });
    });
  });
};

function printTree(root) {
  let res = '';
  root.walk((node) => {
    if (!node.isRoot()) {
      node = node.model;
      const indentation = '  '.repeat(node.level);
      res += `- ${indentation}[${node.name}](${node.filePath || ''})\n`;
    }
  });
  return res;
};

async function init() {
  const bookTitle = this.config.get('title');
  const summaryFilename = this.config.get('structure.summary');
  rootPath = this.resolve('');

  const rootNode = await generateSummaryTree();
  let summary = ( bookTitle ? `# ${bookTitle}\n\n` : '' );
  summary += printTree(rootNode);
  fs.writeFileSync( `${rootPath}/${summaryFilename}`, summary, 'utf8');
  console.log(`\x1b[36mgitbook-plugin-journal-summary: \x1b[32m${summaryFilename} generated successfully.`);
  return 0;
};

module.exports = {hooks: {'init': init}};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import AppBar from 'material-ui/AppBar'
import Drawer from 'material-ui/Drawer'
import MenuItem from 'material-ui/MenuItem'
import { Link } from 'react-router'

class Menu extends Component {
  constructor(props) {
    super(props)
    this.state = {open: false}
  }

  handleToggle = () => this.setState({open: !this.state.open});
  handleClose = () => this.setState({open: false});

  render() {
    const styles = {
      title: {
        cursor: 'pointer',
        color: this.context.muiTheme.palette.alternateTextColor,
      },
    }

    return (

        <AppBar
          title={<Link to={'/'} style={styles.title}>inspire.data.gouv.fr</Link>}
          onLeftIconButtonTouchTap={this.handleToggle}
          />

        <Drawer
          docked={false}
          open={this.state.open}
          onRequestChange={(open) => this.setState({open})}
          >
          <AppBar title="inspire" />
          <Link to="/"><MenuItem onTouchTap={this.handleClose}>Home</MenuItem></Link>
          <Link to="/catalogs"><MenuItem onTouchTap={this.handleClose}>Catalogs</MenuItem></Link>
        </Drawer>

    )
  }
}

Menu.contextTypes = {
  muiTheme: React.PropTypes.object.isRequired,
}

export default Menu
<commit_msg>Improve menu<commit_after>import React, { Component } from 'react'
import AppBar from 'material-ui/AppBar'
import Drawer from 'material-ui/Drawer'
import Subheader from 'material-ui/Subheader'
import MenuItem from 'material-ui/MenuItem'
import Divider from 'material-ui/Divider'
import LinkIcon from 'material-ui/svg-icons/editor/insert-link'
import SyncIcon from 'material-ui/svg-icons/action/autorenew'
import BookIcon from 'material-ui/svg-icons/action/book'
import { Link } from 'react-router'

class Menu extends Component {
  constructor(props) {
    super(props)
    this.state = {open: false}
  }

  handleToggle = () => this.setState({open: !this.state.open});
  handleClose = () => this.setState({open: false});

  render() {
    const styles = {
      title: {
        cursor: 'pointer',
        color: this.context.muiTheme.palette.alternateTextColor,
      },
    }

    return (

        <AppBar
          title={<Link to={'/'} style={styles.title}>inspire.beta.gouv.fr</Link>}
          onLeftIconButtonTouchTap={this.handleToggle}
          />

        <Drawer
          docked={false}
          open={this.state.open}
          onRequestChange={(open) => this.setState({open})}
          desktop={true}
          >
          <AppBar title="inspire" showMenuIconButton={false}/>
          <Subheader>Explore</Subheader>
          <Link to="/catalogs"><MenuItem rightIcon={<BookIcon/>} onTouchTap={this.handleClose}>Catalogs</MenuItem></Link>
          <Divider/>
          <Subheader>Tools</Subheader>
          <MenuItem disabled={true} rightIcon={<LinkIcon/>}>Analyze a link</MenuItem>
          <MenuItem disabled={true} rightIcon={<SyncIcon/>}>Harvest a CSW</MenuItem>
          <MenuItem disabled={true} rightIcon={<SyncIcon/>}>Analyze a WFS</MenuItem>
        </Drawer>

    )
  }
}

Menu.contextTypes = {
  muiTheme: React.PropTypes.object.isRequired,
}

export default Menu
<|endoftext|>


<commit_before>var liveStream = require('level-live-stream')
var through = require('through')

module.exports = function (db, viewer) {
  liveStream(db)

  return function (opts, start, end) {
    opts = 'string' === typeof opts ? {name: opts} : opts
    var view = viewer.views[opts.name]

    if(!view)
      throw new Error('view: ' +opts.name+ ' does not exist')

    if(start) opts.start = start
    if(end)   opts.end = end

    var range = view.bucket.range(opts.start, opts.end)

    opts.start = range.start; opts.end = range.end

    var ls = opts.tail === false ? db.readStream(opts) : db.liveStream(opts)

    return ls.pipe(through(function (data) {
        var _data = {key: view.bucket.parse(data.key).key, value: data.value}
        this.queue(_data)
      })).once('close', ls.destroy.bind(ls))
  }
}
<commit_msg>emit sync event from live-stream<commit_after>var liveStream = require('level-live-stream')
var through = require('through')

module.exports = function (db, viewer) {
  liveStream(db)

  return function (opts, start, end) {
    opts = 'string' === typeof opts ? {name: opts} : opts
    var view = viewer.views[opts.name]

    if(!view)
      throw new Error('view: ' +opts.name+ ' does not exist')

    if(start) opts.start = start
    if(end)   opts.end = end

    var range = view.bucket.range(opts.start, opts.end)

    opts.start = range.start; opts.end = range.end

    var ls = opts.tail === false ? db.readStream(opts) : db.liveStream(opts)

    var ts = ls.pipe(through(function (data) {
      var _data = {key: view.bucket.parse(data.key).key, value: data.value}
      this.queue(_data)
    })).once('close', ls.destroy.bind(ls))

    if (opts.tail !== false){
      ls.once('sync', function () {
        ts.emit('sync')
      })
    }

    return ts
  }
}
<|endoftext|>


<commit_before>var osa = require('osa2')

function play(uri) {
    if (uri)
        return playTrack(uri)
    return osa(() => Application('Spotify').play())()
}

function playTrack(uri) {
    return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}

function pause() {
    return osa(() => Application('Spotify').pause())()
}

function toggle() {
    return osa(() => Application('Spotify').playpause())()
}

function next() {
    return osa(() => Application('Spotify').nextTrack())()
}

function prev() {
    return osa(() => Application('Spotify').previousTrack())()
}

function getCurrentTrack() {
    return osa(() => {
        var track = Application('Spotify').currentTrack
        return {
            id: track.id(),
            name: track.name(),
            album: track.album(),
            artist: track.artist(),
            duration: track.duration(),
            artwork: track.artworkUrl(),
            popularity: track.popularity()
        }
    })()
}

function getPlayerState() {
    return osa(() => {
        var s = Application('Spotify')
        return {
            state: s.playerState(),
            volume: s.soundVolume(),
            repeating: s.repeating(),
            shuffling: s.shuffling(),
        }
    })()
}

module.exports = {
    play, pause, toggle, next, prev,
    getCurrentTrack, getPlayerState
}
<commit_msg>Include player position in `getCurrentState`<commit_after>var osa = require('osa2')

function play(uri) {
    if (uri)
        return playTrack(uri)
    return osa(() => Application('Spotify').play())()
}

function playTrack(uri) {
    return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}

function pause() {
    return osa(() => Application('Spotify').pause())()
}

function toggle() {
    return osa(() => Application('Spotify').playpause())()
}

function next() {
    return osa(() => Application('Spotify').nextTrack())()
}

function prev() {
    return osa(() => Application('Spotify').previousTrack())()
}

function getCurrentTrack() {
    return osa(() => {
        var track = Application('Spotify').currentTrack
        return {
            id: track.id(),
            name: track.name(),
            album: track.album(),
            artist: track.artist(),
            duration: track.duration(),
            artwork: track.artworkUrl(),
            popularity: track.popularity()
        }
    })()
}

function getPlayerState() {
    return osa(() => {
        var s = Application('Spotify')
        return {
            state: s.playerState(),
            volume: s.soundVolume(),
            position: s.playerPosition(),
            repeating: s.repeating(),
            shuffling: s.shuffling(),
        }
    })()
}

module.exports = {
    play, pause, toggle, next, prev,
    getCurrentTrack, getPlayerState
}
<|endoftext|>


<commit_before>/*jslint node: true*/
"use strict";

/*
* ##########################################
* # LIBRARY IMPORTS                        #
* ##########################################
*/
var http  = require("http"),
    https = require("https"),
    route = require("./includes/route"),
    endpoint = require("./includes/endpoint");

var config = {
  port: 80,
  sslPort: 443
};

/*
* ##########################################
* # CORE SERVER                            #
* ##########################################
*/

// Starts the server on the specified port.
function server() {
  http.createServer(route.find).listen(config.port);
  console.log("Started HTTP Server On " + config.port.toString());
}

function secureServer(options) {
  https.createServer(options, function(request, response) {
    route.find(request, response);
  }).listen(config.sslPort);
  console.log("Started HTTPS Server On " + config.sslPort.toString());
}

/*
* ##########################################
* # EXPORTS                                #
* ##########################################
*/
exports.config = config;

exports.get = endpoint.get;
exports.put = endpoint.put;
exports.post = endpoint.post;
exports.delete = endpoint.delete;
exports.response = require("./includes/response");
exports.database = require("./includes/database");
exports.server = server;
exports.secureServer = secureServer;
<commit_msg>Refactored https.creatServer to a one liner<commit_after>/*jslint node: true*/
"use strict";

/*
* ##########################################
* # LIBRARY IMPORTS                        #
* ##########################################
*/
var http  = require("http"),
    https = require("https"),
    route = require("./includes/route"),
    endpoint = require("./includes/endpoint");

var config = {
  port: 80,
  sslPort: 443
};

/*
* ##########################################
* # CORE SERVER                            #
* ##########################################
*/

// Starts the server on the specified port.
function server() {
  http.createServer(route.find).listen(config.port);
  console.log("Started HTTP Server On " + config.port.toString());
}

function secureServer(options) {
  https.createServer(options, route.find).listen(config.sslPort);
  console.log("Started HTTPS Server On " + config.sslPort.toString());
}

/*
* ##########################################
* # EXPORTS                                #
* ##########################################
*/
exports.config = config;

exports.get = endpoint.get;
exports.put = endpoint.put;
exports.post = endpoint.post;
exports.delete = endpoint.delete;
exports.response = require("./includes/response");
exports.database = require("./includes/database");
exports.server = server;
exports.secureServer = secureServer;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var assert = require('assert')

/**
 * Expose `serverUrl`.
 */
module.exports = serverUrl

/**
 * Get the server url.
 *
 * @param {Object} server
 * @return {String}
 * @api public
 */
function serverUrl(server) {
  assert.equal(typeof server, 'object')
  assert(server.address, 'server.address should exist');

  var address = server.address();
  var port = address.port;
  return 'http://' + address.address + ':' + port
}
<commit_msg>Support HTTPS servers (#2)<commit_after>/**
 * Module dependencies
 */
var assert = require('assert')
var https = require('https')

/**
 * Expose `serverUrl`.
 */
module.exports = serverUrl

/**
 * Get the server url.
 *
 * @param {Object} server
 * @return {String}
 * @api public
 */
function serverUrl(server) {
  assert.equal(typeof server, 'object')
  assert(server.address, 'server.address should exist');

  var protocol = 'http' + (server instanceof https.Server ? 's' : '')
  var address = server.address();
  var port = address.port;
  return protocol + '://' + address.address + ':' + port
}
<|endoftext|>


<commit_before>var ws = io.connect('//' + document.domain + ':' + location.port);

$('#widgets').hide();
$('#update').hide();
nextbus();
setInterval(nextbus, 30000);
setInterval(presence, 30000);

function nextbus() {
    ws.emit('next bus');
}

function presence() {
    ws.emit('get presence');
}

function nicetime(date) {
    return date.getHours() + ":" + pad2(date.getMinutes());
}

function pad2(number) {
    // https://www.electrictoolbox.com/pad-number-two-digits-javascript/
    return (number < 10 ? '0' : '') + number
}

ws.on('next bus data', function(data) {
    var nbd = $('#nextbusdata');
    nbd.html('');
    data.forEach(function (a) {
        nbd.append('
' + a[0] + '
');
        a[1].forEach(function (b) {
            var d = new Date(0);
            d.setUTCMilliseconds(b);
            var delta = d - new Date();
            nbd.append('
' + Math.floor(delta / 60000) + " minutes (" + nicetime(d) + ')
');
        });
    });
});

ws.on('presence data', function(data) {
    alert(data);
});

ws.on('display refresh', function () {
    location.reload();
});

$('#dashboard').click(showWidgets);
$('#dashboard').on("tap", showWidgets);
$('#note').click(showWidgets);
$('#note').on("tap", showWidgets);

var intervalid;
function showWidgets() {
    clearInterval(intervalid);
    $('#dashboard').fadeToggle();
    $('#widgets').fadeToggle();
    intervalid = setInterval(showDash, 60000);
}

function showDash() {
    $('#widgets').fadeOut("slow", function() {});
    $('#dashboard').fadeIn();
    clearInterval(intervalid);
}

var update = false;
ws.on('update', function (data) {
    update = true;
    $('#widgets').hide();
    $('#dashboard').hide();
    $('#update').show();

});

ws.on('connect', function () {
    if (update) {
        location.reload(true);
    }
});

$(".widget").click(function () {
    ws.emit('widget', {id: this.id});
});
<commit_msg>Test performance<commit_after>var ws = io.connect('//' + document.domain + ':' + location.port);

$('#widgets').hide();
$('#update').hide();
nextbus();
setInterval(nextbus, 30000);
setInterval(presence, 30000);

function nextbus() {
    ws.emit('next bus');
}

function presence() {
    ws.emit('get presence');
}

function nicetime(date) {
    return date.getHours() + ":" + pad2(date.getMinutes());
}

function pad2(number) {
    // https://www.electrictoolbox.com/pad-number-two-digits-javascript/
    return (number < 10 ? '0' : '') + number
}

ws.on('next bus data', function(data) {
    var nbd = $('#nextbusdata');
    nbd.html('');
    data.forEach(function (a) {
        nbd.append('
' + a[0] + '
');
        a[1].forEach(function (b) {
            var d = new Date(0);
            d.setUTCMilliseconds(b);
            var delta = d - new Date();
            nbd.append('
' + Math.floor(delta / 60000) + " minutes (" + nicetime(d) + ')
');
        });
    });
});

ws.on('presence data', function(data) {
    alert(data);
});

ws.on('display refresh', function () {
    location.reload();
});

$('#dashboard').click(showWidgets);
$('#dashboard').on("tap", showWidgets);
$('#note').click(showWidgets);
$('#note').on("tap", showWidgets);

var intervalid;
function showWidgets() {
    clearInterval(intervalid);
    $('#dashboard').toggle();
    $('#widgets').toggle();
    intervalid = setInterval(showDash, 60000);
}

function showDash() {
    $('#widgets').hide();
    $('#dashboard').show();
    clearInterval(intervalid);
}

function resetTimer() {
    clearInterval(intervalid);
}

$('body').click(resetTimer);
$('body').on("tap", resetTimer);

var update = false;
ws.on('update', function (data) {
    update = true;
    $('#widgets').hide();
    $('#dashboard').hide();
    $('#update').show();

});

ws.on('connect', function () {
    if (update) {
        location.reload(true);
    }
});

$(".widget").click(function () {
    ws.emit('widget', {id: this.id});
});
<|endoftext|>