<commit_before>
/*!
 * Express - View
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var extname = require('path').extname
  , dirname = require('path').dirname
  , basename = require('path').basename
  , utils = require('connect').utils
  , clone = require('./utils').clone
  , merge = utils.merge
  , http = require('http')
  , fs = require('fs')
  , mime = utils.mime;

/**
 * Memory cache.
 *
 * @type Object
 */

var cache = {};

/**
 * Cache view contents to prevent I/O hits.
 *
 * @type Object
 */

var viewCache = {};

/**
 * Cache view path derived names.
 *
 * @type Object
 */

var viewNameCache = {};

/**
 * Initialize a new `View` with the given `view` path and `options`.
 *
 * @param {String} view
 * @param {Object} options
 * @api private
 */

var View = exports = module.exports = function View(view, options) {
  options = options || {};
  // TODO: memoize basename etc
  this.view = view;
  this.root = options.root;
  this.defaultEngine = options.defaultEngine;
  this.parent = options.parentView;
  this.basename = basename(view);
  this.engine = this.resolveEngine();
  this.extension = '.' + this.engine;
  this.path = this.resolvePath();
  this.dirname = dirname(this.path);
};

/**
 * Resolve view engine.
 *
 * @return {String}
 * @api private
 */

View.prototype.resolveEngine = function(){
  // Explicit
  if (~this.basename.indexOf('.')) return extname(this.basename).substr(1);
  // Inherit from parent
  if (this.parent) return this.parent.engine;
  // Default
  return this.defaultEngine;
};

/**
 * Resolve view path.
 *
 * @return {String}
 * @api private
 */

View.prototype.resolvePath = function(){
  var path = this.view;
  // Implicit engine
  if (!~this.basename.indexOf('.')) path += this.extension;
  // Absolute
  if ('/' == path[0]) return path;
  // Relative to parent
  if (this.parent) return this.parent.dirname + '/' + path;
  // Relative to root
  return this.root
    ? this.root + '/' + path
    : path;
};

/**
 * Get view contents. This is a one-time hit, so we
 * can afford to be sync.
 *
 * @return {String}
 * @api public
 */

View.prototype.__defineGetter__('contents', function(){
  return fs.readFileSync(this.path, 'utf8');
});

/**
 * Get template engine api, cache exports to reduce
 * require() calls.
 *
 * @return {Object}
 * @api public
 */

View.prototype.__defineGetter__('templateEngine', function(){
  var ext = this.extension;
  return cache[ext]
    || (cache[ext] = require(this.engine));
});

/**
 * Initialize a new `Partial` for the given `view` and `options`.
 *
 * @param {String} view
 * @param {Object} options
 * @api private
 */

var Partial = exports.Partial = function Partial(view, options) {
  options = options || {};
  View.call(this, view, options);
  this.objectName = options.as || this.resolveObjectName();
  this.path = this.dirname + '/_' + basename(this.path);
};

/**
 * Inherit from `View.prototype`.
 */

Partial.prototype.__proto__ = View.prototype;

/**
 * Resolve partial object name from the view path.
 *
 * Examples:
 *
 *   "user.ejs" becomes "user"
 *   "forum thread.ejs" becomes "forumThread"
 *   "forum/thread/post.ejs" becomes "post"
 *   "blog-post.ejs" becomes "blogPost"
 *
 * @return {String}
 * @api private
 */

Partial.prototype.resolveObjectName = function(){
  // TODO: cache
  return this.view
    .split('/')
    .slice(-1)[0]
    .split('.')[0]
    .replace(/[^a-zA-Z0-9 ]+/g, ' ')
    .split(/ +/).map(function(word, i){
      return i
        ? word[0].toUpperCase() + word.substr(1)
        : word;
    }).join('');
};

/**
 * Synchronously cache view at the given `path`.
 *
 * @param {String} path
 * @return {String}
 * @api private
 */

function cacheViewSync(path) {
  return viewCache[path] = fs.readFileSync(path, 'utf8');
}

/**
 * Return view root path for the given `app`.
 *
 * @param {express.Server} app
 * @return {String}
 * @api private
 */

function viewRoot(app) {
  return app.set('views') || process.cwd() + '/views';
}

/**
 * Return object name deduced from the given `view` path.
 *
 * Examples:
 *
 *    "movie/director" -> director
 *    "movie.director" -> director
 *    "forum/thread/post" -> post
 *    "forum/thread.post" -> post
 *
 * @param {String} view
 * @return {String}
 * @api private
 */

function objectName(view) {
  return view.split('/').slice(-1)[0].split('.')[0];
}

/**
 * Register the given template engine `exports`
 * as `ext`. For example we may wish to map ".html"
 * files to jade:
 *
 *    app.register('.html', require('jade'));
 *
 * This is also useful for libraries that may not
 * match extensions correctly. For example my haml.js
 * library is installed from npm as "hamljs" so instead
 * of layout.hamljs, we can register the engine as ".haml":
 *
 *    app.register('.haml', require('haml-js'));
 *
 * For engines that do not comply with the Express
 * specification, we can also wrap their api this way.
 *
 *    app.register('.foo', {
 *        render: function(str, options) {
 *            // perhaps their api is
 *            // return foo.toHTML(str, options);
 *        }
 *    });
 *
 * @param {String} ext
 * @param {Object} obj
 * @api public
 */

exports.register = function(ext, exports) {
  cache[ext] = exports;
};

/**
 * Render `view` partial with the given `options`.
 *
 * Options:
 *   - `object` Single object with name derived from the view (unless `as` is present)
 *
 *   - `as` Variable name for each `collection` value, defaults to the view name.
 *     * as: 'something' will add the `something` local variable
 *     * as: this will use the collection value as the template context
 *     * as: global will merge the collection value's properties with `locals`
 *
 *   - `collection` Array of objects, the name is derived from the view name itself.
 *     For example _video.html_ will have a object _video_ available to it.
 *
 * @param  {String} view
 * @param  {Object|Array} options, collection, or object
 * @return {String}
 * @api public
 */

http.ServerResponse.prototype.partial = function(view, options, locals, parent){
  locals = locals || {};

  // Inherit parent view extension when not present
  if (parent && !~view.indexOf('.')) {
    view += parent.extension;
  }

  // Allow collection to be passed as second param
  if (options) {
    if ('length' in options) {
      options = { collection: options };
    } else if (!options.collection && !options.locals && !options.object) {
      options = { object: options };
    }
  } else {
    options = {};
  }

  // Inherit locals from parent
  options.locals = options.locals
    ? merge(locals, options.locals)
    : locals;

  // Partials dont need layouts
  options.renderPartial = true;
  options.layout = false;

  // Deduce name from view path
  var name = options.as
    || viewNameCache[view]
    || (viewNameCache[view] = objectName(view));

  // Collection support
  var collection = options.collection;
  if (collection) {
    var len = collection.length
      , buf = '';
    delete options.collection;
    options.locals.collectionLength = len;
    for (var i = 0; i < len; ++i) {
      var val = collection[i];
      options.locals.firstInCollection = i === 0;
      options.locals.indexInCollection = i;
      options.locals.lastInCollection = i === len - 1;
      options.object = val;
      buf += this.partial(view, options);
    }
    return buf;
  } else {
    if (options.object) {
      if ('string' == typeof name) {
        options.locals[name] = options.object;
      } else if (name === global) {
        merge(options.locals, options.object);
      } else {
        options.scope = options.object;
      }
    }
    return this.render(view, options);
  }
};

/**
 * Render `view` with the given `options` and optional callback `fn`.
 * When a callback function is given a response will _not_ be made
 * automatically, however otherwise a response of _200_ and _text/html_ is given.
 *
 * Options:
 *
 *  Most engines accept one or more of the following options,
 *  both _haml_ and _jade_ accept all:
 *
 *  - `scope`     Template evaluation context (the value of `this`)
 *  - `debug`     Output debugging information
 *  - `status`    Response status code, defaults to 200
 *  - `headers`   Response headers object
 *
 * @param  {String} view
 * @param  {Object|Function} options or callback function
 * @param  {Function} fn
 * @api public
 */

http.ServerResponse.prototype.render = function(view, options, fn, parent){
  // Support callback function as second arg
  if (typeof options === 'function') {
    fn = options, options = {};
  }

  var self = this
    , app = this.app
    , options = options || {}
    , helpers = app.viewHelpers
    , dynamicHelpers = app.dynamicViewHelpers
    , viewOptions = app.settings['view options'];

  // Mixin "view options"
  if (viewOptions) options.__proto__ = viewOptions;

  // Defaults
  var self = this
    , root = viewRoot(this.app)
    , partial = options.renderPartial
    , layout = options.layout;

  // Layout support
  if (true === layout || undefined === layout) {
    layout = 'layout';
  }

  // Default execution scope to the response
  options.scope = options.scope || this.req;

  // Pass filename to the engine and view
  var locals = options.locals = options.locals || {};

  // Populate view
  options.parentView = parent;

  // "views" setting
  options.root = app.settings.views || process.cwd() + '/views';

  // "view engine" setting
  options.defaultEngine = app.settings['view engine'];

  // Populate view
  view = partial
    ? new Partial(view, options)
    : new View(view, options);

  // Dynamic helper support
  if (false !== options.dynamicHelpers) {
    // cache
    if (!this.__dynamicHelpers) {
      this.__dynamicHelpers = {};
      var keys = Object.keys(dynamicHelpers);
      for (var i = 0, len = keys.length; i < len; ++i) {
        var key = keys[i]
          , val = dynamicHelpers[key];
        if (typeof val === 'function') {
          this.__dynamicHelpers[key] = val.call(
                this.app
              , this.req
              , this);
        }
      }
    }

    // apply
    merge(options.locals, this.__dynamicHelpers);
  }

  // Merge view helpers
  options.locals = merge(clone(helpers), options.locals);

  // Always expose partial() as a local
  options.locals.partial = function(path, options){
    return self.partial(path, options, locals, view);
  };

  function error(err) {
    if (fn) {
      fn(err);
    } else {
      self.req.next(err);
    }
  }

  // Attempt render
  try {
    var template = view.templateEngine.compile(view.contents, options);
    str = template.call(options.scope, options.locals);
  } catch (err) {
    return error(err);
  }

  // Layout support
  if (layout) {
    options.layout = false;
    options.locals.body = str;
    self.render(layout, options, fn, view);
  } else if (partial) {
    return str;
  } else if (fn) {
    fn(null, str);
  } else {
    this.send(str, options.headers, options.status);
  }
};
<commit_msg>indentation<commit_after>
/*!
 * Express - View
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var extname = require('path').extname
  , dirname = require('path').dirname
  , basename = require('path').basename
  , utils = require('connect').utils
  , clone = require('./utils').clone
  , merge = utils.merge
  , http = require('http')
  , fs = require('fs')
  , mime = utils.mime;

/**
 * Memory cache.
 *
 * @type Object
 */

var cache = {};

/**
 * Cache view contents to prevent I/O hits.
 *
 * @type Object
 */

var viewCache = {};

/**
 * Cache view path derived names.
 *
 * @type Object
 */

var viewNameCache = {};

/**
 * Initialize a new `View` with the given `view` path and `options`.
 *
 * @param {String} view
 * @param {Object} options
 * @api private
 */

var View = exports = module.exports = function View(view, options) {
  options = options || {};
  // TODO: memoize basename etc
  this.view = view;
  this.root = options.root;
  this.defaultEngine = options.defaultEngine;
  this.parent = options.parentView;
  this.basename = basename(view);
  this.engine = this.resolveEngine();
  this.extension = '.' + this.engine;
  this.path = this.resolvePath();
  this.dirname = dirname(this.path);
};

/**
 * Resolve view engine.
 *
 * @return {String}
 * @api private
 */

View.prototype.resolveEngine = function(){
  // Explicit
  if (~this.basename.indexOf('.')) return extname(this.basename).substr(1);
  // Inherit from parent
  if (this.parent) return this.parent.engine;
  // Default
  return this.defaultEngine;
};

/**
 * Resolve view path.
 *
 * @return {String}
 * @api private
 */

View.prototype.resolvePath = function(){
  var path = this.view;
  // Implicit engine
  if (!~this.basename.indexOf('.')) path += this.extension;
  // Absolute
  if ('/' == path[0]) return path;
  // Relative to parent
  if (this.parent) return this.parent.dirname + '/' + path;
  // Relative to root
  return this.root
    ? this.root + '/' + path
    : path;
};

/**
 * Get view contents. This is a one-time hit, so we
 * can afford to be sync.
 *
 * @return {String}
 * @api public
 */

View.prototype.__defineGetter__('contents', function(){
  return fs.readFileSync(this.path, 'utf8');
});

/**
 * Get template engine api, cache exports to reduce
 * require() calls.
 *
 * @return {Object}
 * @api public
 */

View.prototype.__defineGetter__('templateEngine', function(){
  var ext = this.extension;
  return cache[ext]
    || (cache[ext] = require(this.engine));
});

/**
 * Initialize a new `Partial` for the given `view` and `options`.
 *
 * @param {String} view
 * @param {Object} options
 * @api private
 */

var Partial = exports.Partial = function Partial(view, options) {
  options = options || {};
  View.call(this, view, options);
  this.objectName = options.as || this.resolveObjectName();
  this.path = this.dirname + '/_' + basename(this.path);
};

/**
 * Inherit from `View.prototype`.
 */

Partial.prototype.__proto__ = View.prototype;

/**
 * Resolve partial object name from the view path.
 *
 * Examples:
 *
 *   "user.ejs" becomes "user"
 *   "forum thread.ejs" becomes "forumThread"
 *   "forum/thread/post.ejs" becomes "post"
 *   "blog-post.ejs" becomes "blogPost"
 *
 * @return {String}
 * @api private
 */

Partial.prototype.resolveObjectName = function(){
  // TODO: cache
  return this.view
    .split('/')
    .slice(-1)[0]
    .split('.')[0]
    .replace(/[^a-zA-Z0-9 ]+/g, ' ')
    .split(/ +/).map(function(word, i){
      return i
        ? word[0].toUpperCase() + word.substr(1)
        : word;
    }).join('');
};

/**
 * Synchronously cache view at the given `path`.
 *
 * @param {String} path
 * @return {String}
 * @api private
 */

function cacheViewSync(path) {
  return viewCache[path] = fs.readFileSync(path, 'utf8');
}

/**
 * Return view root path for the given `app`.
 *
 * @param {express.Server} app
 * @return {String}
 * @api private
 */

function viewRoot(app) {
  return app.set('views') || process.cwd() + '/views';
}

/**
 * Return object name deduced from the given `view` path.
 *
 * Examples:
 *
 *    "movie/director" -> director
 *    "movie.director" -> director
 *    "forum/thread/post" -> post
 *    "forum/thread.post" -> post
 *
 * @param {String} view
 * @return {String}
 * @api private
 */

function objectName(view) {
  return view.split('/').slice(-1)[0].split('.')[0];
}

/**
 * Register the given template engine `exports`
 * as `ext`. For example we may wish to map ".html"
 * files to jade:
 *
 *    app.register('.html', require('jade'));
 *
 * This is also useful for libraries that may not
 * match extensions correctly. For example my haml.js
 * library is installed from npm as "hamljs" so instead
 * of layout.hamljs, we can register the engine as ".haml":
 *
 *    app.register('.haml', require('haml-js'));
 *
 * For engines that do not comply with the Express
 * specification, we can also wrap their api this way.
 *
 *    app.register('.foo', {
 *        render: function(str, options) {
 *            // perhaps their api is
 *            // return foo.toHTML(str, options);
 *        }
 *    });
 *
 * @param {String} ext
 * @param {Object} obj
 * @api public
 */

exports.register = function(ext, exports) {
  cache[ext] = exports;
};

/**
 * Render `view` partial with the given `options`.
 *
 * Options:
 *   - `object` Single object with name derived from the view (unless `as` is present)
 *
 *   - `as` Variable name for each `collection` value, defaults to the view name.
 *     * as: 'something' will add the `something` local variable
 *     * as: this will use the collection value as the template context
 *     * as: global will merge the collection value's properties with `locals`
 *
 *   - `collection` Array of objects, the name is derived from the view name itself.
 *     For example _video.html_ will have a object _video_ available to it.
 *
 * @param  {String} view
 * @param  {Object|Array} options, collection, or object
 * @return {String}
 * @api public
 */

http.ServerResponse.prototype.partial = function(view, options, locals, parent){
  locals = locals || {};

  // Inherit parent view extension when not present
  if (parent && !~view.indexOf('.')) {
    view += parent.extension;
  }

  // Allow collection to be passed as second param
  if (options) {
    if ('length' in options) {
      options = { collection: options };
    } else if (!options.collection && !options.locals && !options.object) {
      options = { object: options };
    }
  } else {
    options = {};
  }

  // Inherit locals from parent
  options.locals = options.locals
    ? merge(locals, options.locals)
    : locals;

  // Partials dont need layouts
  options.renderPartial = true;
  options.layout = false;

  // Deduce name from view path
  var name = options.as
    || viewNameCache[view]
    || (viewNameCache[view] = objectName(view));

  // Collection support
  var collection = options.collection;
  if (collection) {
    var len = collection.length
      , buf = '';
    delete options.collection;
    options.locals.collectionLength = len;
    for (var i = 0; i < len; ++i) {
      var val = collection[i];
      options.locals.firstInCollection = i === 0;
      options.locals.indexInCollection = i;
      options.locals.lastInCollection = i === len - 1;
      options.object = val;
      buf += this.partial(view, options);
    }
    return buf;
  } else {
    if (options.object) {
      if ('string' == typeof name) {
        options.locals[name] = options.object;
      } else if (name === global) {
        merge(options.locals, options.object);
      } else {
        options.scope = options.object;
      }
    }
    return this.render(view, options);
  }
};

/**
 * Render `view` with the given `options` and optional callback `fn`.
 * When a callback function is given a response will _not_ be made
 * automatically, however otherwise a response of _200_ and _text/html_ is given.
 *
 * Options:
 *
 *  Most engines accept one or more of the following options,
 *  both _haml_ and _jade_ accept all:
 *
 *  - `scope`     Template evaluation context (the value of `this`)
 *  - `debug`     Output debugging information
 *  - `status`    Response status code, defaults to 200
 *  - `headers`   Response headers object
 *
 * @param  {String} view
 * @param  {Object|Function} options or callback function
 * @param  {Function} fn
 * @api public
 */

http.ServerResponse.prototype.render = function(view, options, fn, parent){
  // Support callback function as second arg
  if (typeof options === 'function') {
    fn = options, options = {};
  }

  var self = this
    , app = this.app
    , options = options || {}
    , helpers = app.viewHelpers
    , dynamicHelpers = app.dynamicViewHelpers
    , viewOptions = app.settings['view options'];

  // Mixin "view options"
  if (viewOptions) options.__proto__ = viewOptions;

  // Defaults
  var self = this
    , root = viewRoot(this.app)
    , partial = options.renderPartial
    , layout = options.layout;

  // Layout support
  if (true === layout || undefined === layout) {
    layout = 'layout';
  }

  // Default execution scope to the response
  options.scope = options.scope || this.req;

  // Pass filename to the engine and view
  var locals = options.locals = options.locals || {};

  // Populate view
  options.parentView = parent;

  // "views" setting
  options.root = app.settings.views || process.cwd() + '/views';

  // "view engine" setting
  options.defaultEngine = app.settings['view engine'];

  // Populate view
  view = partial
    ? new Partial(view, options)
    : new View(view, options);

  // Dynamic helper support
  if (false !== options.dynamicHelpers) {
    // cache
    if (!this.__dynamicHelpers) {
      this.__dynamicHelpers = {};
      var keys = Object.keys(dynamicHelpers);
      for (var i = 0, len = keys.length; i < len; ++i) {
        var key = keys[i]
          , val = dynamicHelpers[key];
        if (typeof val === 'function') {
          this.__dynamicHelpers[key] = val.call(
              this.app
            , this.req
            , this);
        }
      }
    }

    // apply
    merge(options.locals, this.__dynamicHelpers);
  }

  // Merge view helpers
  options.locals = merge(clone(helpers), options.locals);

  // Always expose partial() as a local
  options.locals.partial = function(path, options){
    return self.partial(path, options, locals, view);
  };

  function error(err) {
    if (fn) {
      fn(err);
    } else {
      self.req.next(err);
    }
  }

  // Attempt render
  try {
    var template = view.templateEngine.compile(view.contents, options);
    str = template.call(options.scope, options.locals);
  } catch (err) {
    return error(err);
  }

  // Layout support
  if (layout) {
    options.layout = false;
    options.locals.body = str;
    self.render(layout, options, fn, view);
  } else if (partial) {
    return str;
  } else if (fn) {
    fn(null, str);
  } else {
    this.send(str, options.headers, options.status);
  }
};
<|endoftext|>


<commit_before>"use strict";

var filename = 'blank.txt';
var fontsize = '14';
var state = true;
var editor = ace.edit('editor');
var scriptPath = "/opt/ignsdk/";
//var fs = ign.filesystem();
//var sys = ign.sys();
var pathProject;
var index_file;

$(function() {
  //shortcut
  $("textarea").bind('keydown', 'Ctrl+s',function(){
    window["saveProject"]();
  });
  // dropdown menu handler
  $('.bar').on('click', function() {
    $('.menu ul').hide();
    $(this).next().css('display', 'block');
    $(this).next().css('z-index', '1000');
    $(this).next().on('mouseleave', '', function() {
      $(this).hide();
    });
  });
  // action handler
  $('.action').on('click', function() {
    var action = $(this).data('action');
    $(this).parent().parent().hide();
    window[action]();
  });

  // popup handler
  $('[data-popup-target]').on('click', function () {
    $('html').addClass('overlay');
    var popup = $(this).data('popup-target');
    $(popup).addClass('visible');
    switch(popup){
      case "#openproject-popup" :
        loadProject();
      break;
    }
  });
  $('.popup-exit').click(function () {
    closepopup();
  });
  // get font size
  fontsize = parseInt($('.editor').css('font-size'));
  // line number
  editor.setTheme('ace/theme/twilight');
  editor.setShowPrintMargin(false);
  $('#editor').css('font-size', '14px');
  // trigger file state
  $('.editor').keyup(function() {
    state = false;
  });
  // status bar
  var statusbar = ace.require('ace/ext/statusbar').StatusBar;
  var status = new statusbar(editor, document.getElementById('statusbar'));
});

var closepopup = function() {
  $('.popup.visible').addClass('transitioning').removeClass('visible');
  $('html').removeClass('overlay');
  setTimeout(function() {
    $('.popup').removeClass('transitioning');
  }, 200);
}

var blank = function() {
  var save = true;
  if (!state) {
    save = confirm('The file is not saved. Are you sure want to create a new file?');
  }
  if (save) {
    editor.setValue('', 1);
    state = true;
  }
}

var open = function() {
  var save = true;
  if (!state) {
    save = confirm('The file is not saved. Are you sure want to open a new file?');
  }
  if (save) {
    $('.file').click();
    $('.file').change(function() {
      var filetemp = $('.file')[0].files[0];
      filename = filetemp.name;
      var filereader = new FileReader();
      filereader.onload = function(evt) {
        var filebuffer = evt.target.result;
        // write content to editor
        editor.setValue(filebuffer, 1);
        $('.file').replaceWith($('.file').val('').clone(true));
        // set file mode
        var modelist = ace.require('ace/ext/modelist');
        var mode = modelist.getModeForPath(filename).mode;
        editor.session.setMode(mode);
      };
      filereader.readAsText(filetemp, 'UTF-8');
    });
    state = true;
  }
}

var download = function() {
  filename = prompt('Download as', filename);
  if (filename) {
    var text = $('.ace_text').text();
    var textfile = new Blob([text], {type:'text/plain'});
    var downloadlink = document.createElement('a');
    downloadlink.download = filename;
    downloadlink.innerHTML = 'Download File';
    downloadlink.href = window.webkitURL.createObjectURL(textfile);
    downloadlink.click();
    state = true;
  }
};

var openProject = function(file){
  console.log(file);
  closepopup();
  /*pathProject = fs.openDirDialog();
  index_file = pathProject+"/index.html"
  if(fs.info(index_file).exists){
    var fileBuffer = fs.fileRead(index_file);
    editor.setValue(fileBuffer, 1);
    var modelist = ace.require('ace/ext/modelist');
    var mode = modelist.getModeForPath("index.html").mode;
    editor.session.setMode(mode);
  }
  else{
    alert("ERR : index.html not found!");
  }*/

  fs.fileRead(scriptPath+file,function(data){
    var fileBuffer = data;
    editor.setValue(fileBuffer, 1);
    var modelist = ace.require('ace/ext/modelist');
    var mode = modelist.getModeForPath(file).mode;
    editor.session.setMode(mode);
  })
}

var undo = function() {
  editor.undo();
}

var redo = function() {
  editor.redo();
}

var all = function() {
  editor.selectAll();
}

var plus = function() {
  fontsize = fontsize + 2;
  $('.editor').css('font-size', fontsize + 'px');
}

var minus = function() {
  fontsize = fontsize - 2;
  $('.editor').css('font-size', fontsize + 'px');
}

var normal = function() {
  $('.editor').css('font-size', '14px');
}

var about = function() {
  alert('IDE5' + "\n" + 'Simple, pure HTML5 IDE' + "\n" + 'Author: fitra@gpl' + "\n" + 'License: GPL Version 3');
}

var run = function(){
  sys.exec("ignsdk -p "+pathProject);
}

var saveProject = function(){
  var text = editor.getSession().getValue();
  fs.fileWrite(index_file,text);
}

var loadProject = function(){
  fs.list(scriptPath,function(data){
    var html = "";
    data.forEach(function(file){
      var nameFile = file.replace(scriptPath,"");
      if(!((nameFile == ".") || (nameFile == ".."))){
        html += "
"+nameFile+"
";
      }
    });
    $(".loadProject").html(html);
  });
}<commit_msg>ADD: new file, savefile<commit_after>"use strict";

var filename = '';
var fontsize = '14';
var state = true;
var editor = ace.edit('editor');
var scriptPath = "/opt/ignsdk/";
//var fs = ign.filesystem();
//var sys = ign.sys();
var pathProject;
var index_file;

$(function() {
  //shortcut
  $("textarea").bind('keydown', 'Ctrl+s',function(){
    window["saveProject"]();
  });
  // dropdown menu handler
  $('.bar').on('click', function() {
    $('.menu ul').hide();
    $(this).next().css('display', 'block');
    $(this).next().css('z-index', '1000');
    $(this).next().on('mouseleave', '', function() {
      $(this).hide();
    });
  });
  // action handler
  $('.action').on('click', function() {
    var action = $(this).data('action');
    $(this).parent().parent().hide();
    window[action]();
  });

  // popup handler
  $('[data-popup-target]').on('click', function () {
    $('html').addClass('overlay');
    var popup = $(this).data('popup-target');
    $(popup).addClass('visible');
    switch(popup){
      case "#openproject-popup" :
        loadProject();
      break;
    }
  });
  $('.popup-exit').click(function () {
    closepopup();
  });
  // get font size
  fontsize = parseInt($('.editor').css('font-size'));
  // line number
  editor.setTheme('ace/theme/twilight');
  editor.setShowPrintMargin(false);
  $('#editor').css('font-size', '14px');
  // trigger file state
  $('.editor').keyup(function() {
    state = false;
  });
  // status bar
  var statusbar = ace.require('ace/ext/statusbar').StatusBar;
  var status = new statusbar(editor, document.getElementById('statusbar'));
});

var closepopup = function() {
  $('.popup.visible').addClass('transitioning').removeClass('visible');
  $('html').removeClass('overlay');
  setTimeout(function() {
    $('.popup').removeClass('transitioning');
  }, 200);
}

var blank = function() {
  filename = "";
  var save = true;
  if (!state) {
    save = confirm('The file is not saved. Are you sure want to create a new file?');
  }
  if (save) {
    editor.setValue('', 1);
    state = true;
  }
}

var open = function() {
  var save = true;
  if (!state) {
    save = confirm('The file is not saved. Are you sure want to open a new file?');
  }
  if (save) {
    $('.file').click();
    $('.file').change(function() {
      var filetemp = $('.file')[0].files[0];
      filename = filetemp.name;
      var filereader = new FileReader();
      filereader.onload = function(evt) {
        var filebuffer = evt.target.result;
        // write content to editor
        editor.setValue(filebuffer, 1);
        $('.file').replaceWith($('.file').val('').clone(true));
        // set file mode
        var modelist = ace.require('ace/ext/modelist');
        var mode = modelist.getModeForPath(filename).mode;
        editor.session.setMode(mode);
      };
      filereader.readAsText(filetemp, 'UTF-8');
    });
    state = true;
  }
}

var download = function() {
  filename = prompt('Download as', filename);
  if (filename) {
    var text = $('.ace_text').text();
    var textfile = new Blob([text], {type:'text/plain'});
    var downloadlink = document.createElement('a');
    downloadlink.download = filename;
    downloadlink.innerHTML = 'Download File';
    downloadlink.href = window.webkitURL.createObjectURL(textfile);
    downloadlink.click();
    state = true;
  }
};

var openProject = function(file){
  filename = file;
  closepopup();
  fs.fileRead(scriptPath+file,function(data){
    var fileBuffer = data;
    editor.setValue(fileBuffer, 1);
    var modelist = ace.require('ace/ext/modelist');
    var mode = modelist.getModeForPath(file).mode;
    editor.session.setMode(mode);
  })
}

var undo = function() {
  editor.undo();
}

var redo = function() {
  editor.redo();
}

var all = function() {
  editor.selectAll();
}

var plus = function() {
  fontsize = fontsize + 2;
  $('.editor').css('font-size', fontsize + 'px');
}

var minus = function() {
  fontsize = fontsize - 2;
  $('.editor').css('font-size', fontsize + 'px');
}

var normal = function() {
  $('.editor').css('font-size', '14px');
}

var about = function() {
  alert('IDE5' + "\n" + 'Simple, pure HTML5 IDE' + "\n" + 'Author: fitra@gpl' + "\n" + 'License: GPL Version 3');
}

var run = function(){
  sys.exec("ignsdk -p "+pathProject);
}

var saveProject = function(){
  if(filename == ""){
    filename = prompt("Project name, ex: tesproject");
    filename += ".js";
  }
  var text = editor.getSession().getValue();
  fs.fileWrite(scriptPath+filename,text);
}

var loadProject = function(){
  fs.list(scriptPath,function(data){
    var html = "";
    data.forEach(function(file){
      var nameFile = file.replace(scriptPath,"");
      if(!((nameFile == ".") || (nameFile == ".."))){
        html += "
"+nameFile+"
";
      }
    });
    $(".loadProject").html(html);
  });
}<|endoftext|>


<commit_before>function initializeList() {
    $('body').on('click', '.preview', null, function() {
        var button = this;
        if ($(button).hasClass('open')) {
            $(button).parents('td').find('section').each(function () {
                $(this).slideUp('fast', function () {
                    $(button).removeClass('open');
                });
            });
        } else {
            $(button).parents('td').find('section').each(function () {
                $(this).slideDown('fast', function () {
                    $(button).addClass('open');
                });
            });
        }
    });
    $('#sortings').on('change', '#add-sort', null, function() {
        if ($(this).find(':selected').val()) {
            window.location.href = addQueryStringParameter(document.URL, 'sort[]', $(this).find(':selected').val());
        }
    });
    $('#perpage').change(function () {
        window.location.href = updateQueryStringParameter(document.URL, 'perpage', $(this).find(':selected').val());
    });
    $('.add-bookmark').click(function() {
        addBookmark($(this).parents('tr').attr('data-id'));
        return false;
    });
    $('body').on('click', '.explore-links', null, function() {
        var row = $(this).parents('tr');
        $.ajax({
            url: '/record/' + $(row).attr('data-id') + '/links'
        }).done(function (data) {
            if ($(row).parents('.leftPane').length > 0) {
                $('tr.browsing').removeClass('browsing');
                $('.rightPane').remove();
            } else {
                window.scrollTo(0, 0);
                $('.leftPane').remove();
                $('.rightPane').removeClass('rightPane').addClass('leftPane').css('margin-top', '0');
            }
            $(row).addClass('browsing');
            $('.search-scroller').append('
' + data + '
');
        });
    });
}
<commit_msg>Use an object for search paging<commit_after>function initializeList() {
    $('body').on('click', '.preview', null, function() {
        var button = this;
        if ($(button).hasClass('open')) {
            $(button).parents('td').find('section').each(function () {
                $(this).slideUp('fast', function () {
                    $(button).removeClass('open');
                });
            });
        } else {
            $(button).parents('td').find('section').each(function () {
                $(this).slideDown('fast', function () {
                    $(button).addClass('open');
                });
            });
        }
    });
    $('#sortings').on('change', '#add-sort', null, function() {
        if ($(this).find(':selected').val()) {
            window.location.href = addQueryStringParameter(document.URL, 'sort[]', $(this).find(':selected').val());
        }
    });
    $('#perpage').change(function () {
        window.location.href = updateQueryStringParameter(document.URL, 'perpage', $(this).find(':selected').val());
    });
    $('.add-bookmark').click(function() {
        addBookmark($(this).parents('tr').attr('data-id'));
        return false;
    });
    $('body').on('click', '.explore-links', null, function() {
        var row = $(this).parents('tr');
        window.bnpanes.next('/record/' + $(row).attr('data-id') + '/links', row);
    });
}

/* The built-in caching from the web browser will almost certainly be sufficient,
   but implementing our own history/garbage collection is useful for tracking
   what the system is doing while we're trying to refactor search panes. */
(function( bnpanes, $, undefined ) {
    var panes = { };
    var current;
    var previous = [ ];
    var next = [ ];
    var history = [ ];

    bnpanes.historysize = 4;
    bnpanes.viewportwidth = 2;

    bnpanes.previous = function (url, reference) {
        if (url) {
            previous = bnpanes.gc(previous, 0);
        } else {
            url = previous.shift;
        }
        me.load(url);
    };

    bnpanes.next = function (url, reference) {
        if (url) {
            next = bnpanes.gc(next, 0);
        } else {
            url = next.shift;
        }
        bnpanes.load(url, function (data) {
            if ($(reference).parents('.leftPane').length > 0) {
                $('tr.browsing').removeClass('browsing');
                $('.rightPane').remove();
            } else {
                window.scrollTo(0, 0);
                $('.leftPane').remove();
                $('.rightPane').removeClass('rightPane').addClass('leftPane').css('margin-top', '0');
            }
            $(reference).addClass('browsing');
            $('.search-scroller').append('
' + data + '
');
        });
    };

    bnpanes.load = function (url, render) {
        if (panes[url]) {
            render(panes[url]);
        } else {
            $.ajax({
                url: url,
                success: function (data) {
                    panes[url] = data;
                    history.unshift(url);
                    bnpanes.gc();
                    render(data);
                },
                failure: function (data) {
                }
            });
        }
    };

    bnpanes.gc = function (list, length) {
        list = list || history;
        length = length || bnpanes.historysize;
        var url;
        while (list.length > length) {
            url = list.pop();
            delete panes[url];
        }
        return list;
    };
}( window.bnpanes = window.bnpanes || {}, jQuery ));
<|endoftext|>


<commit_before>$(document).ready(function() {
  // Set title preview
  $("#title").on('keyup', function(e) {
    $("#title-preview").text($("#title").val());
    $("#title-preview").attr("href", $("#url").val());
  })
  // Set image preview
  $("#url").on('keyup', function(e) {
    $("#img-preview").attr("src", $("#url").val());
  })
  // Replace broken images
  $("#img-preview").error(function() {
    $(this).attr("src", "http://dummyimage.com/800x600&text=Pinternet");
  });
  // Show grid
  var $grid = $('.grid').masonry({
    itemSelector: '.grid-item',
    fitWidth: true,
    transitionDuration: '0.8s',
    columnWidth: 5
  });
  // Set layout so no image overlap on image load
  $grid.imagesLoaded().progress( function() {
    $grid.masonry('layout');
  });
});
<commit_msg>Replace all broken image links in js<commit_after>$(document).ready(function() {
  // Set title preview
  $("#title").on('keyup', function(e) {
    $("#title-preview").text($("#title").val());
    $("#title-preview").attr("href", $("#url").val());
  })
  // Set image preview
  $("#url").on('keyup', function(e) {
    $("#img-preview").attr("src", $(this).val());
  })
  // Replace broken images
  $(".grid-img").error(function() {
    $(this).attr("src", "http://dummyimage.com/800x600&text=Pinternet");
  });
  // Show grid
  var $grid = $('.grid').masonry({
    itemSelector: '.grid-item',
    fitWidth: true,
    transitionDuration: '0.8s',
    columnWidth: 5
  });
  // Set layout so no image overlap on image load
  $grid.imagesLoaded().progress( function() {
    $grid.masonry('layout');
  });
});
<|endoftext|>


<commit_before>var _ = require('highland');
var R = require('ramda');
var input = require('./input.js');
var gun = require('./gun.js')
var platforms, player, gun, map, layer, gunSprite, boxes, inputState = input.INITIAL_STATE;
var width, height, lastTime;
var GRAVITY = 700;
var bullets;
var level;

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function preload() {
  level = getParameterByName('level');
  var map = getParameterByName('map');
  var mapName = level ? "level" + level :
                map   ? map             :
                        "test";

  game.load.tilemap('map', '../resources/maps/' + mapName + ".json", null, Phaser.Tilemap.TILED_JSON);
  game.load.spritesheet('tiles', '../resources/tiles.png', 32, 32);

  game.load.spritesheet('player', '../resources/player.png', 72, 72);
  game.load.spritesheet('gun', '../resources/gun.png', 128, 128);
  game.load.image('bullet', '../resources/pl-bullet.png');
  game.load.image('box', '../resources/box.png');
  game.load.image('reflector', '../resources/reflctor.png');
  game.load.image('door', '../resources/door.png');

  game.load.image('ledge', '../resources/pl-ledge.png')
}

function create() {
  game.stage.backgroundColor = '#998458';
  game.physics.startSystem(Phaser.Physics.P2);

  map = game.add.tilemap('map');
  map.addTilesetImage('tiles');
  map.addTilesetImage('box');

  boxes = game.add.group();
  boxes.enableBody = true;
  map.createFromObjects('objects', 17, 'box', 0, true, false, boxes);
  boxes.setAll('body.bounce.y', 0.2);
  boxes.setAll('body.gravity.y', GRAVITY);
  boxes.setAll('modSize', 1);
  boxes.callAll('anchor.setTo', 0.5, 1);

  layer = map.createLayer('Tile Layer 1');
  layer.resizeWorld();
  layer.enableBody = true;

  map.setCollisionBetween(1, 16);

  target = game.add.group();
  target.enableBody = true;
  map.createFromObjects('objects', 19, 'door', 0, true, false, target);
  target.setAll('body.immovable', true);

  player = game.add.sprite(200, game.world.height - 400, 'player');
  game.physics.arcade.enable(player);
  player.body.bounce.y = 0.2;
  player.body.gravity.y = GRAVITY;
  player.body.collideWorldBounds = true;
  player.animations.add('walk', [0, 1, 2, 3, 4], 10, true);
  player.anchor.setTo(0.5, 1)
  game.camera.follow(player);

  gunSprite = gun.getSprite(game)
  bullets = game.add.group();
  bullets.enableBody = true;

  bulletReflectables = game.add.group();
  bulletReflectables.enableBody = true;
  map.createFromObjects('objects', 18, 'reflector', 0, true, false, bulletReflectables);
  bulletReflectables.setAll('body.immovable',  true)

  input().each(function(s){
    inputState = s;

    if (inputState.switchgun) {
      gun.switchType();
    }

    if(inputState.chargegun) {
      gun.startCharging(game)
    } else if(inputState.firegun) {
      gun.fire(game, bullets, player)
      gunSprite.animations.play('fire');
    }
  })
}

function update() {
  game.physics.arcade.collide(target, player, function(player, target) {
    if(level) {
      window.location = window.location.href.split('?')[0] + "?level=" + (parseInt(level) + 1)
    }
  });

  game.physics.arcade.collide(boxes, layer);
  game.physics.arcade.collide(boxes, boxes);
  game.physics.arcade.collide(player, layer);
  game.physics.arcade.collide(player, boxes);
  game.physics.arcade.collide(player, bulletReflectables);
  game.physics.arcade.collide(bullets, bulletReflectables);

  boxes.forEach(function(box) {
    if (box.body.onFloor()) {
      box.body.drag.setTo(100000);
    } else {
      box.body.drag.setTo(0);
    }
    // box.scale.x = box.modSize;
    // box.scale.y = box.modSize;
  }, this);

  if (inputState.up && (player.body.onFloor() || player.body.touching.down)){
      player.body.velocity.y = -GRAVITY/2;
  }
  gun.updateRotation(game, player, inputState)
  if (inputState.left){
    player.body.velocity.x = -150;
    player.scale.x = -Math.abs(player.scale.x);
    player.animations.play('walk');
  } else if (inputState.right){
    player.body.velocity.x = 150;
    player.scale.x = Math.abs(player.scale.x)
    player.animations.play('walk');
  } else {
    player.body.velocity.x = 0;
    player.animations.stop();
    player.frame = 0;
  }

  var thingsToDestroy = [];
  game.physics.arcade.collide(bullets, layer, function(bullet, tile) {
    thingsToDestroy.push(bullet);
  });

  var expandOrShrink = function(sprite) {
    console.log(sprite.scale.x)
    console.log(sprite.scale.y)
    if(bullet.gunType === gun.gunType.ENLARGE && Math.abs(sprite.scale.x) < 4 && Math.abs(sprite.scale.y) < 4) {
      sprite.scale = new Phaser.Point(sprite.scale.x * 2, sprite.scale.y * 2)
      sprite.x = sprite.x - sprite.width / 4
      sprite.y = sprite.y - sprite.height / 2
    } else if(bullet.gunType == gun.gunType.SHRINK && Math.abs(sprite.scale.x) > 0.25 && Math.abs(sprite.scale.y) > 0.25) {
      sprite.scale = new Phaser.Point(sprite.scale.x / 2, sprite.scale.y / 2)
      sprite.y = sprite.y + sprite.height
      sprite.x = sprite.x + sprite.width / 2
    }
  }

  game.physics.arcade.collide(bullets, boxes, function(bullet, box) {
    thingsToDestroy.push(bullet);
    expandOrShrink(box)
  });
  game.physics.arcade.collide(bullets, player, function(player, bullet) {
    thingsToDestroy.push(bullet);
    expandOrShrink(player);
  });

  for(i = 0; i < thingsToDestroy.length; i++) {
    thingsToDestroy[i].destroy();
  }

}
<commit_msg>Remove a bunch of debug<commit_after>var _ = require('highland');
var R = require('ramda');
var input = require('./input.js');
var gun = require('./gun.js')
var platforms, player, gun, map, layer, gunSprite, boxes, inputState = input.INITIAL_STATE;
var width, height, lastTime;
var GRAVITY = 700;
var bullets;
var level;

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function preload() {
  level = getParameterByName('level');
  var map = getParameterByName('map');
  var mapName = level ? "level" + level :
                map   ? map             :
                        "test";

  game.load.tilemap('map', '../resources/maps/' + mapName + ".json", null, Phaser.Tilemap.TILED_JSON);
  game.load.spritesheet('tiles', '../resources/tiles.png', 32, 32);

  game.load.spritesheet('player', '../resources/player.png', 72, 72);
  game.load.spritesheet('gun', '../resources/gun.png', 128, 128);
  game.load.image('bullet', '../resources/pl-bullet.png');
  game.load.image('box', '../resources/box.png');
  game.load.image('reflector', '../resources/reflctor.png');
  game.load.image('door', '../resources/door.png');

  game.load.image('ledge', '../resources/pl-ledge.png')
}

function create() {
  game.stage.backgroundColor = '#998458';
  game.physics.startSystem(Phaser.Physics.P2);

  map = game.add.tilemap('map');
  map.addTilesetImage('tiles');
  map.addTilesetImage('box');

  boxes = game.add.group();
  boxes.enableBody = true;
  map.createFromObjects('objects', 17, 'box', 0, true, false, boxes);
  boxes.setAll('body.bounce.y', 0.2);
  boxes.setAll('body.gravity.y', GRAVITY);
  boxes.setAll('modSize', 1);
  boxes.callAll('anchor.setTo', 0.5, 1);

  layer = map.createLayer('Tile Layer 1');
  layer.resizeWorld();
  layer.enableBody = true;

  map.setCollisionBetween(1, 16);

  target = game.add.group();
  target.enableBody = true;
  map.createFromObjects('objects', 19, 'door', 0, true, false, target);
  target.setAll('body.immovable', true);

  player = game.add.sprite(200, game.world.height - 400, 'player');
  game.physics.arcade.enable(player);
  player.body.bounce.y = 0.2;
  player.body.gravity.y = GRAVITY;
  player.body.collideWorldBounds = true;
  player.animations.add('walk', [0, 1, 2, 3, 4], 10, true);
  player.anchor.setTo(0.5, 1)
  game.camera.follow(player);

  gunSprite = gun.getSprite(game)
  bullets = game.add.group();
  bullets.enableBody = true;

  bulletReflectables = game.add.group();
  bulletReflectables.enableBody = true;
  map.createFromObjects('objects', 18, 'reflector', 0, true, false, bulletReflectables);
  bulletReflectables.setAll('body.immovable',  true)

  input().each(function(s){
    inputState = s;

    if (inputState.switchgun) {
      gun.switchType();
    }

    if(inputState.chargegun) {
      gun.startCharging(game)
    } else if(inputState.firegun) {
      gun.fire(game, bullets, player)
      gunSprite.animations.play('fire');
    }
  })
}

function update() {
  game.physics.arcade.collide(target, player, function(player, target) {
    if(level) {
      window.location = window.location.href.split('?')[0] + "?level=" + (parseInt(level) + 1)
    }
  });

  game.physics.arcade.collide(boxes, layer);
  game.physics.arcade.collide(boxes, boxes);
  game.physics.arcade.collide(player, layer);
  game.physics.arcade.collide(player, boxes);
  game.physics.arcade.collide(player, bulletReflectables);
  game.physics.arcade.collide(bullets, bulletReflectables);

  boxes.forEach(function(box) {
    if (box.body.onFloor()) {
      box.body.drag.setTo(100000);
    } else {
      box.body.drag.setTo(0);
    }
    // box.scale.x = box.modSize;
    // box.scale.y = box.modSize;
  }, this);

  if (inputState.up && (player.body.onFloor() || player.body.touching.down)){
      player.body.velocity.y = -GRAVITY/2;
  }
  gun.updateRotation(game, player, inputState)
  if (inputState.left){
    player.body.velocity.x = -150;
    player.scale.x = -Math.abs(player.scale.x);
    player.animations.play('walk');
  } else if (inputState.right){
    player.body.velocity.x = 150;
    player.scale.x = Math.abs(player.scale.x)
    player.animations.play('walk');
  } else {
    player.body.velocity.x = 0;
    player.animations.stop();
    player.frame = 0;
  }

  var thingsToDestroy = [];
  game.physics.arcade.collide(bullets, layer, function(bullet, tile) {
    thingsToDestroy.push(bullet);
  });

  var expandOrShrink = function(sprite) {
    if(bullet.gunType === gun.gunType.ENLARGE && Math.abs(sprite.scale.x) < 4 && Math.abs(sprite.scale.y) < 4) {
      sprite.scale = new Phaser.Point(sprite.scale.x * 2, sprite.scale.y * 2)
      sprite.x = sprite.x - sprite.width / 4
      sprite.y = sprite.y - sprite.height / 2
    } else if(bullet.gunType == gun.gunType.SHRINK && Math.abs(sprite.scale.x) > 0.25 && Math.abs(sprite.scale.y) > 0.25) {
      sprite.scale = new Phaser.Point(sprite.scale.x / 2, sprite.scale.y / 2)
      sprite.y = sprite.y + sprite.height
      sprite.x = sprite.x + sprite.width / 2
    }
  }

  game.physics.arcade.collide(bullets, boxes, function(bullet, box) {
    thingsToDestroy.push(bullet);
    expandOrShrink(box)
  });
  game.physics.arcade.collide(bullets, player, function(player, bullet) {
    thingsToDestroy.push(bullet);
    expandOrShrink(player);
  });

  for(i = 0; i < thingsToDestroy.length; i++) {
    thingsToDestroy[i].destroy();
  }

}
<|endoftext|>


<commit_before>$(document).ready(function() {
    if (bonfireName !== undefined) {
        ga('send', 'event',  'Bonfire', 'load', bonfireName + ':' + Math.floor(Date.now() / 1000));
    }

    var CSRF_HEADER = 'X-CSRF-Token';

    var setCSRFToken = function(securityToken) {
        jQuery.ajaxPrefilter(function(options, _, xhr) {
            if (!xhr.crossDomain) {
                xhr.setRequestHeader(CSRF_HEADER, securityToken);
            }
        });
    };

    setCSRFToken($('meta[name="csrf-token"]').attr('content'));

    $('.start-challenge').on('click', function() {
        $(this).parent().remove();
        $('.challenge-content')
            .removeClass('hidden-element')
            .addClass('animated fadeInDown');
    });

    $('.completed-challenge').on('click', function() {
        $('#complete-challenge-dialog').modal('show');
        // Only post to server if there is an authenticated user
        if ($('.signup-btn-nav').length < 1) {
            l = location.pathname.split('/');
            cn = l[l.length - 1];
            $.ajax({
                type: 'POST',
                data: {challengeNumber: cn},
                url: '/completed-challenge/'
            });
        }
    });

    function completedBonfire(didCompleteWith, bonfireSolution, thisBonfireHash) {
        $('#complete-bonfire-dialog').modal('show');
        // Only post to server if there is an authenticated user
        if ($('.signup-btn-nav').length < 1) {

            $.post(
                '/completed-bonfire',
                {
                    bonfireInfo: {
                        completedWith : didCompleteWith,
                        solution: bonfireSolution,
                        bonfireHash: thisBonfireHash
                    }
                },
                function(res) {
                if (res) {
                    window.location.href = '/bonfires'
                }
            })
        }
    }

    $('.next-bonfire-button').on('click', function() {
        var bonfireSolution = myCodeMirror.getValue();
        var thisBonfireHash = passedBonfireHash || null;
        var didCompleteWith = $('#completed-with').val() || null;
        completedBonfire(didCompleteWith, bonfireSolution, thisBonfireHash);

    });

    $('.all-challenges').on('click', function() {
        $('#all-challenges-dialog').modal('show');
    });

    $('.all-bonfires').on('click', function() {
        $('#all-bonfires-dialog').modal('show');
    });

    $('.next-challenge-button').on('click', function() {
        l = location.pathname.split('/');
        window.location = '/challenges/' + (parseInt(l[l.length - 1]) + 1);
    });

    // Bonfire instructions functions
    $('#more-info').on('click', function() {
        ga('send', 'event',  'Bonfire', 'more-info', bonfireName);
        $('#brief-instructions').hide();
        $('#long-instructions').show().removeClass('hide');

    });
    $('#less-info').on('click', function() {
        $('#brief-instructions').show();
        $('#long-instructions').hide();
    });

    // Bonfire analytics
    $('#submitButton').on('click', function() {
        attempts++;
        ga('send', 'event',  'Bonfire', 'ran-code', bonfireName);
    })
});

var profileValidation = angular.module('profileValidation',['ui.bootstrap']);
profileValidation.controller('profileValidationController', ['$scope', '$http',
    function($scope, $http) {
        $http.get('/account/api').success(function(data) {
            $scope.user = data.user;
            $scope.user.profile.username = $scope.user.profile.username ? $scope.user.profile.username.toLowerCase() : undefined;
            $scope.storedUsername = data.user.profile.username;
            $scope.storedEmail = data.user.email;
            $scope.user.email = $scope.user.email ? $scope.user.email.toLowerCase() : undefined;
            $scope.user.profile.twitterHandle = $scope.user.profile.twitterHandle ? $scope.user.profile.twitterHandle.toLowerCase() : undefined;
            $scope.asyncComplete = true;
        });
    }
]);

profileValidation.controller('pairedWithController', ['$scope',
    function($scope) {
        $scope.existingUser = null;
    }
]);

profileValidation.controller('emailSignUpController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('emailSignInController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('nonprofitFormController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('doneWithFirst100HoursFormController', ['$scope',
    function($scope) {

    }
]);

profileValidation.directive('uniqueUsername', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                ngModel.$setValidity('unique', true);
                if (element.val()) {
                    $http.get("/api/checkUniqueUsername/" + element.val()).success(function (data) {
                        if (element.val() == scope.storedUsername) {
                            ngModel.$setValidity('unique', true);
                        } else if (data) {
                            ngModel.$setValidity('unique', false);
                        }
                    });
                }
            });
        }
    }
});
// TODO: FIX THIS
profileValidation.directive('existingUsername', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                if (element.val().length > 0) {
                    ngModel.$setValidity('exists', false);
                } else {
                    ngModel.$setPristine();
                }
                if (element.val()) {
                    $http.get("/api/checkExistingUsername/" + element.val() + ' ').success(function (data) {
                        if (element.val() == scope.existingUsername) {
                            ngModel.$setValidity('exists', false);
                        } else if (data) {
                            ngModel.$setValidity('exists', true);
                        }
                    });
                }
            });
        }
    }
});

profileValidation.directive('uniqueEmail', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                ngModel.$setValidity('unique', true);
                if (element.val()) {
                    $http.get("/api/checkUniqueEmail/" + encodeURIComponent(element.val())).success(function (data) {
                        if (element.val() == scope.storedEmail) {
                            ngModel.$setValidity('unique', true);
                        } else if (data) {
                            ngModel.$setValidity('unique', false);
                        }
                    });
                };
            });
        }
    }
});<commit_msg>Removing duplicate analytics call<commit_after>$(document).ready(function() {
    if (bonfireName !== undefined) {
        ga('send', 'event',  'Bonfire', 'load', bonfireName + ':' + Math.floor(Date.now() / 1000));
    }

    var CSRF_HEADER = 'X-CSRF-Token';

    var setCSRFToken = function(securityToken) {
        jQuery.ajaxPrefilter(function(options, _, xhr) {
            if (!xhr.crossDomain) {
                xhr.setRequestHeader(CSRF_HEADER, securityToken);
            }
        });
    };

    setCSRFToken($('meta[name="csrf-token"]').attr('content'));

    $('.start-challenge').on('click', function() {
        $(this).parent().remove();
        $('.challenge-content')
            .removeClass('hidden-element')
            .addClass('animated fadeInDown');
    });

    $('.completed-challenge').on('click', function() {
        $('#complete-challenge-dialog').modal('show');
        // Only post to server if there is an authenticated user
        if ($('.signup-btn-nav').length < 1) {
            l = location.pathname.split('/');
            cn = l[l.length - 1];
            $.ajax({
                type: 'POST',
                data: {challengeNumber: cn},
                url: '/completed-challenge/'
            });
        }
    });

    function completedBonfire(didCompleteWith, bonfireSolution, thisBonfireHash) {
        $('#complete-bonfire-dialog').modal('show');
        // Only post to server if there is an authenticated user
        if ($('.signup-btn-nav').length < 1) {

            $.post(
                '/completed-bonfire',
                {
                    bonfireInfo: {
                        completedWith : didCompleteWith,
                        solution: bonfireSolution,
                        bonfireHash: thisBonfireHash
                    }
                },
                function(res) {
                if (res) {
                    window.location.href = '/bonfires'
                }
            })
        }
    }

    $('.next-bonfire-button').on('click', function() {
        var bonfireSolution = myCodeMirror.getValue();
        var thisBonfireHash = passedBonfireHash || null;
        var didCompleteWith = $('#completed-with').val() || null;
        completedBonfire(didCompleteWith, bonfireSolution, thisBonfireHash);

    });

    $('.all-challenges').on('click', function() {
        $('#all-challenges-dialog').modal('show');
    });

    $('.all-bonfires').on('click', function() {
        $('#all-bonfires-dialog').modal('show');
    });

    $('.next-challenge-button').on('click', function() {
        l = location.pathname.split('/');
        window.location = '/challenges/' + (parseInt(l[l.length - 1]) + 1);
    });

    // Bonfire instructions functions
    $('#more-info').on('click', function() {
        ga('send', 'event',  'Bonfire', 'more-info', bonfireName);
        $('#brief-instructions').hide();
        $('#long-instructions').show().removeClass('hide');

    });
    $('#less-info').on('click', function() {
        $('#brief-instructions').show();
        $('#long-instructions').hide();
    });
});

var profileValidation = angular.module('profileValidation',['ui.bootstrap']);
profileValidation.controller('profileValidationController', ['$scope', '$http',
    function($scope, $http) {
        $http.get('/account/api').success(function(data) {
            $scope.user = data.user;
            $scope.user.profile.username = $scope.user.profile.username ? $scope.user.profile.username.toLowerCase() : undefined;
            $scope.storedUsername = data.user.profile.username;
            $scope.storedEmail = data.user.email;
            $scope.user.email = $scope.user.email ? $scope.user.email.toLowerCase() : undefined;
            $scope.user.profile.twitterHandle = $scope.user.profile.twitterHandle ? $scope.user.profile.twitterHandle.toLowerCase() : undefined;
            $scope.asyncComplete = true;
        });
    }
]);

profileValidation.controller('pairedWithController', ['$scope',
    function($scope) {
        $scope.existingUser = null;
    }
]);

profileValidation.controller('emailSignUpController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('emailSignInController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('nonprofitFormController', ['$scope',
    function($scope) {

    }
]);

profileValidation.controller('doneWithFirst100HoursFormController', ['$scope',
    function($scope) {

    }
]);

profileValidation.directive('uniqueUsername', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                ngModel.$setValidity('unique', true);
                if (element.val()) {
                    $http.get("/api/checkUniqueUsername/" + element.val()).success(function (data) {
                        if (element.val() == scope.storedUsername) {
                            ngModel.$setValidity('unique', true);
                        } else if (data) {
                            ngModel.$setValidity('unique', false);
                        }
                    });
                }
            });
        }
    }
});
// TODO: FIX THIS
profileValidation.directive('existingUsername', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                if (element.val().length > 0) {
                    ngModel.$setValidity('exists', false);
                } else {
                    ngModel.$setPristine();
                }
                if (element.val()) {
                    $http.get("/api/checkExistingUsername/" + element.val() + ' ').success(function (data) {
                        if (element.val() == scope.existingUsername) {
                            ngModel.$setValidity('exists', false);
                        } else if (data) {
                            ngModel.$setValidity('exists', true);
                        }
                    });
                }
            });
        }
    }
});

profileValidation.directive('uniqueEmail', function($http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("keyup", function (event) {
                ngModel.$setValidity('unique', true);
                if (element.val()) {
                    $http.get("/api/checkUniqueEmail/" + encodeURIComponent(element.val())).success(function (data) {
                        if (element.val() == scope.storedEmail) {
                            ngModel.$setValidity('unique', true);
                        } else if (data) {
                            ngModel.$setValidity('unique', false);
                        }
                    });
                };
            });
        }
    }
});<|endoftext|>


<commit_before>var socket = io.connect('http://127.0.0.1:3000');
performance.now = performance.now || performance.webkitNow; // hack added by SD!

var localstream; //the stream of audio/video coming from this browser
var debug = true; // true to log messages

var pc = new RTCPeerConnection(null);

if(navigator.id) {
  navigator.id.watch({
    onlogin: function() {
      //we don't handle login on this page
    },
    onlogout: function() {
      window.location = "/logout";
    }
  });
}

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

function logout() {
  navigator.id.logout();
}

function getMedia(callback, args) {
  navigator.getUserMedia(
    { audio:true, video:true },
    function onStream(stream) {
      gotLocalStream(stream);
      args = args ? args : [];
      console.log(args);
      if(callback) callback.apply(callback, args);
    },
    function failure(error) {
      alert('Error: To call you need to allow video and/or mic');
      trace('Failed to get stream: ' + error);
    }
  );
}

function start() {
  getMedia();
}

/**
 * On the add of a contact
 * @param  {Event} e    event fired
 * @return {undefined}  undefined
 */
submitcontact.onsubmit = function(e) {
  e.preventDefault();
  e.stopPropagation();
  var contactemail = document.getElementById('contactemail');
  contactemail.checkValidity();
  if(contactemail.validity.valid && contactemail.value !== "") {
    socket.emit('addContact', contactemail.value);
  }
};

function call(email) {
  if(!localstream) {
    getMedia(call, [email]);
  }
  else {
    // temporary hacks to cope with API change
    if (!!localstream.videoTracks && !localstream.getVideoTracks) {
      localstream.getVideoTracks = function(){
        return this.videoTracks;
      };
    }
    if (!!localstream.audioTracks && !localstream.getAudioTracks) {
      localstream.getAudioTracks = function() {
        return this.audioTracks;
      };
    }

    pc.onaddstream = gotRemoteStream;

    pc.onicecandidate = function(event) {
      if (event.candidate) {
        socket.emit('iceCandidate', email, event.candidate);
      }
    };

    if(debug) trace("Adding Local Stream to peer connection");
    var options = null;
    setTimeout(function() {
      pc.createOffer(
        function success(offer) {
          pc.setLocalDescription(new RTCSessionDescription(offer));
          if(debug) trace("Offer from outgoing \n" + offer.sdp);
          socket.emit('offer', email, offer);
        },
        function failure(err) {
        }, options);
    }, 1000);
  }
}

function gotRemoteStream(e) {
  if(debug) trace(e.stream);
  incomingvid.src = window.URL.createObjectURL(e.stream);
}

function gotLocalStream(stream) {
  pc.addStream(stream);
  outgoingvid.src = window.URL.createObjectURL(stream); // add preview
  localstream = stream;
}

function sendAnswerFromOffer(offer, email) {
  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(ans) {
      pc.setLocalDescription(new RTCSessionDescription(ans));
      socket.emit('answer', email, ans);
    }, null, null);
  }, function(){
    if(debug) trace('offer FAILED set as remote description');
  });
}

socket.on('offer', function(email, offer) {
  if(confirm("Incoming call from " + email + "! Answer?")) {

    pc.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('iceCandidate', email, event.candidate);
      }
    };

    pc.onaddstream = gotRemoteStream;

    if(!localstream) {
      getMedia(sendAnswerFromOffer, [offer, email]);
    }
    else {
      sendAnswerFromOffer(offer, email);
    }
  }
  else {
    trace("Call denied");
  }
});

socket.on('allContacts', function(arr) {
  for(var i =  0; i < arr.length; i++) {
    document.getElementById('emails').innerHTML += "
" + arr[i] + "
";
  }
});

socket.on('contactAdded', function(email) {
  document.getElementById('contactlist').innerHTML += "
" + email + "<button style='float:right;' onclick='call(\"" + email + "\");'>Call</button>
";
  document.getElementById('contactemail').value = "";
});

socket.on('answer', function(email, answer) {
  trace('Got answer: ' + answer.sdp);
  pc.setRemoteDescription(new RTCSessionDescription(answer),
    function(e) {console.log(e);},
    function() {
      if(debug) trace('answer FAILED set as remote description');
    }
  );
});

socket.on('iceCandidate', function(email, cand) {
  pc.addIceCandidate(new RTCIceCandidate(cand));
});

start();
<commit_msg>Run callback with args<commit_after>var socket = io.connect('http://127.0.0.1:3000');
performance.now = performance.now || performance.webkitNow; // hack added by SD!

var localstream; //the stream of audio/video coming from this browser
var debug = true; // true to log messages

var pc = new RTCPeerConnection(null);

if(navigator.id) {
  navigator.id.watch({
    onlogin: function() {
      //we don't handle login on this page
    },
    onlogout: function() {
      window.location = "/logout";
    }
  });
}

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

function logout() {
  navigator.id.logout();
}

function getMedia(callback, args) {
  navigator.getUserMedia(
    { audio:true, video:true },
    function onStream(stream) {
      gotLocalStream(stream);
      args = args ? args : [];
      //run the callback with args
      if(callback) callback.apply(callback, args);
    },
    function failure(error) {
      alert('Error: To call you need to allow video and/or mic');
      trace('Failed to get stream: ' + error);
    }
  );
}

function start() {
  getMedia();
}

/**
 * On the add of a contact
 * @param  {Event} e    event fired
 * @return {undefined}  undefined
 */
submitcontact.onsubmit = function(e) {
  e.preventDefault();
  e.stopPropagation();
  var contactemail = document.getElementById('contactemail');
  contactemail.checkValidity();
  if(contactemail.validity.valid && contactemail.value !== "") {
    socket.emit('addContact', contactemail.value);
  }
};

function call(email) {
  if(!localstream) {
    getMedia(call, [email]);
  }
  else {
    // temporary hacks to cope with API change
    if (!!localstream.videoTracks && !localstream.getVideoTracks) {
      localstream.getVideoTracks = function(){
        return this.videoTracks;
      };
    }
    if (!!localstream.audioTracks && !localstream.getAudioTracks) {
      localstream.getAudioTracks = function() {
        return this.audioTracks;
      };
    }

    pc.onaddstream = gotRemoteStream;

    pc.onicecandidate = function(event) {
      if (event.candidate) {
        socket.emit('iceCandidate', email, event.candidate);
      }
    };

    if(debug) trace("Adding Local Stream to peer connection");
    var options = null;
    setTimeout(function() {
      pc.createOffer(
        function success(offer) {
          pc.setLocalDescription(new RTCSessionDescription(offer));
          if(debug) trace("Offer from outgoing \n" + offer.sdp);
          socket.emit('offer', email, offer);
        },
        function failure(err) {
        }, options);
    }, 1000);
  }
}

function gotRemoteStream(e) {
  if(debug) trace(e.stream);
  incomingvid.src = window.URL.createObjectURL(e.stream);
}

function gotLocalStream(stream) {
  pc.addStream(stream);
  outgoingvid.src = window.URL.createObjectURL(stream); // add preview
  localstream = stream;
}

function sendAnswerFromOffer(offer, email) {
  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(ans) {
      pc.setLocalDescription(new RTCSessionDescription(ans));
      socket.emit('answer', email, ans);
    }, null, null);
  }, function(){
    if(debug) trace('offer FAILED set as remote description');
  });
}

socket.on('offer', function(email, offer) {
  if(confirm("Incoming call from " + email + "! Answer?")) {

    pc.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('iceCandidate', email, event.candidate);
      }
    };

    pc.onaddstream = gotRemoteStream;

    if(!localstream) {
      getMedia(sendAnswerFromOffer, [offer, email]);
    }
    else {
      sendAnswerFromOffer(offer, email);
    }
  }
  else {
    trace("Call denied");
  }
});

socket.on('allContacts', function(arr) {
  for(var i =  0; i < arr.length; i++) {
    document.getElementById('emails').innerHTML += "
" + arr[i] + "
";
  }
});

socket.on('contactAdded', function(email) {
  document.getElementById('contactlist').innerHTML += "
" + email + "<button style='float:right;' onclick='call(\"" + email + "\");'>Call</button>
";
  document.getElementById('contactemail').value = "";
});

socket.on('answer', function(email, answer) {
  trace('Got answer: ' + answer.sdp);
  pc.setRemoteDescription(new RTCSessionDescription(answer),
    function(e) {console.log(e);},
    function() {
      if(debug) trace('answer FAILED set as remote description');
    }
  );
});

socket.on('iceCandidate', function(email, cand) {
  pc.addIceCandidate(new RTCIceCandidate(cand));
});

start();
<|endoftext|>


<commit_before>//upon initialization, the form is hidden
hiddenForm();

//first i need a new contact button
var $addContact = $('#addContact');
  //click on the button and unhide it

//create hidden form
function hiddenForm () {
  var $contactForm = $('#contactForm').hide();
  return $contactForm;
}

//new contact form
  //name, phone number, email, twitter handle, photo url
  //submit
  //on submit contact for disappears
  //POST to firebase
  //display on the page the new information

//contact list
  //displays a row with: small photo or placeholder image, name, phone number, email, twitter
  //remove button
<commit_msg>form hides when 'add new contact' button is clicked<commit_after>//use dev tool for iife

//upon initialization, the form is hidden
hideForm();

//click 'add new contact' and unhide the form
$('#addContact').click(showForm);

//show the form
function showForm () {
  var $contactForm = $('#contactForm').show();
  return $contactForm;
}

//hide the form
function hideForm () {
  var $contactForm = $('#contactForm').hide();
  return $contactForm;
}

//new contact form
  //name, phone number, email, twitter handle, photo url
  //submit
  //on submit contact for disappears
  //POST to firebase
  //display on the page the new information

//contact list
  //displays a row with: small photo or placeholder image, name, phone number, email, twitter
  //remove button
<|endoftext|>


<commit_before>function _range(start, stop, step = 1) {
  var index = 0;
  var length = (stop - start) / step;
  var result = Array(length);

  while(length) {
    result[index] = start;
    start += step;
    index += 1;
    length -= 1;
  }

  return result;
}

function mfcc( audioBuffer ) {
  var sampleRate = 44100;
  var len = audioBuffer.length;
  var t = _range(0.0, len / sampleRate, 1 / sampleRate);

  var center = len / 2;
  var cuttime = 0.04;
  var wav = audioBuffer.getChannelData(0);
  var wavdata = wav.slice(center - cuttime/2*sampleRate, center + cuttime/2*sampleRate);
  // var time = t.slice(center - cuttime/2*sampleRate, center + cuttime/2*sampleRate);

  // var owavdata = wavdata.slice();

  // pre-emphasis filter
  var pwavdata = preEmphasis(wavdata, 0.97);

  var hammingWindow = hamming(pwavdata.length);
  for(var i = 0; i < pwavdata.length; i +=1 ) {
    pwavdata[i] *= hammingWindow[i]
  }

  // DFT
  // number of samples
  var n = 2048
  var im = [];
  [wavdata, im] = minifft(pwavdata, n);

  var Pdft = [];
  for (var i = 0; i < n/2; i+=1) {
    Pdft[i] = wavdata[i] * wavdata[i] + im[i] * im[i]
  }

  // mel filterbank
  var numChannels = 20;
  df = sampleRate / n
  var filterbank, fcenters;
  [filterbank, fcenters] = melFilterBank(sampleRate, n, numChannels);

  var mspec = [];
  _range(0, numChannels).map((c) => {
    mspec.push(
      Math.log10(
        filterbank[c].map((e, i) => Pdft[i] * e )
        .reduce((acc, val) => acc + val, 0)
      )
    );
  });

  return dct(mspec, norm=true).slice(0,12);
}

/*
* DCT: Discrete Cosine Transform
*
*
*            N-1
*  y[k] = 2* sum x[n]*cos(pi*k*(2n+1)/(2*N)), 0 <= k < N.
*            n=0
*/
function dct(signal, norm=false) {
  return _range(0, signal.length).map((k) => {
    return (norm ? (k===0 ? Math.sqrt(1 / (4 * signal.length)) : Math.sqrt(1 / (2 * signal.length))) : 1)
    * 2
    * (signal.map((x, n) => {
      return x * Math.cos( Math.PI * k * (2 * n + 1) / ( 2 * signal.length ))
    }).reduce((acc, val) => acc + val, 0));
  })
}

/*
* melFilterBank
*
*/
function melFilterBank(fs, nfft, numChannels) {
  fmax = fs / 2;
  melmax = 1127.01048 * Math.log(fmax / 700.0 + 1.0);
  nmax = nfft / 2;

  df = fs / nfft;
  dmel = melmax / (numChannels + 1)

  melcenters = _range(1, numChannels + 1).map((e) => e * dmel);
  fcenters = melcenters.map((e) => 700.0 * (Math.exp(e / 1127.01048) - 1.0));
  indexcenter = fcenters.map((e) => Math.round(e / df));

  indexstart = [0].concat(indexcenter.slice(0, numChannels - 1));
  indexstop  = indexcenter.slice(1, numChannels).concat([nmax]);

  filterbank = [];
  _range(0, numChannels).forEach((c) => {
    filterbank[c] = Array(nmax).fill(0);

    increment = 1.0 / (indexcenter[c] - indexstart[c]);
    _range(indexstart[c], indexcenter[c]).map((i) => {
      return filterbank[c][i] = (i - indexstart[c]) * increment;
    });

    decrement = 1.0 / (indexstop[c] - indexcenter[c]);
    _range(indexcenter[c], indexstop[c]).map((i) => {
      return filterbank[c][i] = 1.0 - ((i - indexcenter[c]) * decrement);
    });
  });

  return [filterbank, fcenters];

}

/*
* hamming window
*   w(n) = 0.54 - 0.46 cos( 2 PI n / (M - 1) ), 0 <= n <= M - 1
*/
function hamming(n) {
  var w = [];
  for(var i = 0; i < n; i += 1) {
    w[i] = 0.54 - 0.46 * Math.cos( 2.0 * Math.PI * i / (n - 1));
  }
  return w;
}

/*
* pre emphasis filter
*   y(n) = x(n) - p x(n - 1)
*/
function preEmphasis(signal, p = 0.97) {
  var y = [];
  y[0] = signal[0];
  for(var i = 1; i < signal.length; i+=1){
    y[i] = signal[i] - ( p * signal[i - 1]);
  }

  return y;
}

function minifft(data, n = 0) {
  var N = n || data.length;
  if(data.length < n) {
    var re = Array.prototype.slice.call(data).concat(new Array(n - data.length).fill(0));
  } else {
    var re = data.slice(0, n);
  }
  var im = new Array(n).fill(0);

  for (var i = 0; i < N; i+=1) {
    for(var j = 0, h = i, k = N; k >>= 1; h >>= 1) {
      j = (j << 1) | (h & 1);
    }
    if (j > i) {
      re[j] = [re[i], re[i] = re[j]][0];
      im[j] = [im[i], im[i] = im[j]][0];
    }
  }
  for(var hN = 1; hN * 2 <= N; hN *= 2) {
    for(var i = 0; i < N; i+= hN * 2) {
      for(var j = i; j < i + hN; j+=1) {
        var cos = Math.cos(Math.PI * (j - i) / hN),
        sin = Math.sin(Math.PI * (j - i) / hN);
        var tre =  re[j+hN] * cos + im[j+hN] * sin,
        tim = -re[j+hN] * sin + im[j+hN] * cos;
        re[j+hN] = re[j] - tre;
        im[j+hN] = im[j] - tim;
        re[j] += tre;
        im[j] += tim;
      }
    }
  }

  return [re, im];
}

function onError() {
  console.log("error happen");
}
<commit_msg>preEmphasis filter と　hamming window とくっつけた<commit_after>function _range(start, stop, step = 1) {
  var index = 0;
  var length = (stop - start) / step;
  var result = Array(length);

  while(length) {
    result[index] = start;
    start += step;
    index += 1;
    length -= 1;
  }

  return result;
}

function mfcc( audioBuffer ) {
  var sampleRate = 44100;
  var len = audioBuffer.length;

  var center = len / 2;
  var cuttime = 0.04;
  var wav = audioBuffer.getChannelData(0);
  var wavdata = wav.slice(center - cuttime/2*sampleRate, center + cuttime/2*sampleRate);

  // pre emphasis filter and hamming window
  wavdata = preEmphHamming(wavdata);

  // DFT
  // number of samples
  var n = 2048
  var im = [];
  [wavdata, im] = minifft(wavdata, n);

  var Pdft = [];
  for (var i = 0; i < n/2; i+=1) {
    Pdft[i] = wavdata[i] * wavdata[i] + im[i] * im[i]
  }

  // mel filterbank
  var numChannels = 20;
  var filterbank, fcenters;
  [filterbank, fcenters] = melFilterBank(sampleRate, n, numChannels);

  var mspec = [];
  _range(0, numChannels).map((c) => {
    mspec.push(
      Math.log10(
        filterbank[c].map((e, i) => Pdft[i] * e )
        .reduce((acc, val) => acc + val, 0)
      )
    );
  });

  return dct(mspec, norm=true).slice(0,12);
}

/*
* DCT: Discrete Cosine Transform
*
*
*            N-1
*  y[k] = 2* sum x[n]*cos(pi*k*(2n+1)/(2*N)), 0 <= k < N.
*            n=0
*/
function dct(signal, norm=false) {
  return _range(0, signal.length).map((k) => {
    return (norm ? (k===0 ? Math.sqrt(1 / (4 * signal.length)) : Math.sqrt(1 / (2 * signal.length))) : 1)
    * 2
    * (signal.map((x, n) => {
      return x * Math.cos( Math.PI * k * (2 * n + 1) / ( 2 * signal.length ))
    }).reduce((acc, val) => acc + val, 0));
  })
}

/*
* melFilterBank
*
*/
function melFilterBank(fs, nfft, numChannels) {
  fmax = fs / 2;
  melmax = 1127.01048 * Math.log(fmax / 700.0 + 1.0);
  nmax = nfft / 2;

  df = fs / nfft;
  dmel = melmax / (numChannels + 1)

  melcenters = _range(1, numChannels + 1).map((e) => e * dmel);
  fcenters = melcenters.map((e) => 700.0 * (Math.exp(e / 1127.01048) - 1.0));
  indexcenter = fcenters.map((e) => Math.round(e / df));

  indexstart = [0].concat(indexcenter.slice(0, numChannels - 1));
  indexstop  = indexcenter.slice(1, numChannels).concat([nmax]);

  filterbank = [];
  _range(0, numChannels).forEach((c) => {
    filterbank[c] = Array(nmax).fill(0);

    increment = 1.0 / (indexcenter[c] - indexstart[c]);
    _range(indexstart[c], indexcenter[c]).map((i) => {
      return filterbank[c][i] = (i - indexstart[c]) * increment;
    });

    decrement = 1.0 / (indexstop[c] - indexcenter[c]);
    _range(indexcenter[c], indexstop[c]).map((i) => {
      return filterbank[c][i] = 1.0 - ((i - indexcenter[c]) * decrement);
    });
  });

  return [filterbank, fcenters];

}

/*
* hamming window
*   w(n) = 0.54 - 0.46 cos( 2 PI n / (M - 1) ), 0 <= n <= M - 1
*/
function hamming(n) {
  var w = [];
  for(var i = 0; i < n; i += 1) {
    w[i] = 0.54 - 0.46 * Math.cos( 2.0 * Math.PI * i / (n - 1));
  }
  return w;
}

/*
* pre emphasis filter
*   y(n) = x(n) - p x(n - 1)
*/
function preEmphasis(signal, p = 0.97) {
  var y = [];
  y[0] = signal[0];
  for(var i = 1; i < signal.length; i+=1){
    y[i] = signal[i] - ( p * signal[i - 1]);
  }

  return y;
}

function preEmphHamming(signal) {
  var n = signal.length;
  var y = [];
  y[0] = signal[0];

  for(var i = 1; i < n; i++) {
    y[i] = signal[i] - (0.97 * signal[i-1]);
    y[i] = 0.54 - 0.46 * Math.cos( 2.0 * Math.PI * i / (n - 1));
  }

  return y;
}

function minifft(data, n = 0) {
  var N = n || data.length;
  if(data.length < n) {
    var re = Array.prototype.slice.call(data).concat(new Array(n - data.length).fill(0));
  } else {
    var re = data.slice(0, n);
  }
  var im = new Array(n).fill(0);

  for (var i = 0; i < N; i+=1) {
    for(var j = 0, h = i, k = N; k >>= 1; h >>= 1) {
      j = (j << 1) | (h & 1);
    }
    if (j > i) {
      re[j] = [re[i], re[i] = re[j]][0];
      im[j] = [im[i], im[i] = im[j]][0];
    }
  }
  for(var hN = 1; hN * 2 <= N; hN *= 2) {
    for(var i = 0; i < N; i+= hN * 2) {
      for(var j = i; j < i + hN; j+=1) {
        var cos = Math.cos(Math.PI * (j - i) / hN),
        sin = Math.sin(Math.PI * (j - i) / hN);
        var tre =  re[j+hN] * cos + im[j+hN] * sin,
        tim = -re[j+hN] * sin + im[j+hN] * cos;
        re[j+hN] = re[j] - tre;
        im[j+hN] = im[j] - tim;
        re[j] += tre;
        im[j] += tim;
      }
    }
  }

  return [re, im];
}

function onError() {
  console.log("error happen");
}
<|endoftext|>