<commit_before>

(function(window, undefined) {

  function addRemoveClasses($items, classes, addRemove) {
    classes && $items.forEach(function(node, i) {

      findClasses(classes, node, i)
        .trim().split(/\s+/).forEach(function(styleClass) {
          node.classList[addRemove](styleClass);
        });
    });
    return $items;
  }

  function findClasses(classes, node, i) {
    return ((typeof classes === 'function') ?
       classes.bind(node)(i, node.className) :
       classes);
  }

  $.fn.addClass = function(classes) {
    return addRemoveClasses(this, classes, 'add');
  };

  $.fn.removeClass = function(classes) {
    return addRemoveClasses(this, classes, 'remove');
  };

  $.fn.hasClass = function(className) {
    for(var i = 0; i < this.length; i++)
      if(this[i].classList.contains(className))
        return true;
    return false;
  };

  $.fn.toggleClass = function(classes, swizz) {
    if(swizz !== undefined)
      return addRemoveClasses(this, classes, swizz ? 'add' : 'remove');
    if(!classes) return;
    this.forEach(function(node, i) {
      var $node = $(node);
      findClasses(classes, node, i)
        .trim().split(/\s+/).forEach(function(styleClass) {
          if($node.hasClass(styleClass))
            $node.removeClass(styleClass);
          else
            $node.addClass(styleClass);
        });
    });
    return this;
  };

  /**
   * Without argument: Return html representation of first
   * object in Qbject-array as string.
   * With argument: Use it as html for all elements in array.
   */
  $.fn.html = function(html) {
    if(html) {
      this.forEach(function(a) {a.outerHTML = html;});
      return this;
    } else {
      if(this.length > 0)
        return this[0].outerHTML;
    }
    return '';
  }

  /**
   * Insert content, specified by the parameter, to the end of each element in
   * the set of matched elements.
   */
  $.fn.append = function(content) {
    var $content = $(content);
    this.forEach(function(a) {
      a.appendChild($content.clone()[0]);
    });
    return this;
  }

  $.fn.clone = function(content) {
    var result = $();
    this.forEach(function(a) {
      result = result.add($(a).html());
    });
    return result;
  };
})(window);
<commit_msg>Remove superluos comments<commit_after>

(function(window, undefined) {

  function addRemoveClasses($items, classes, addRemove) {
    classes && $items.forEach(function(node, i) {

      findClasses(classes, node, i)
        .trim().split(/\s+/).forEach(function(styleClass) {
          node.classList[addRemove](styleClass);
        });
    });
    return $items;
  }

  function findClasses(classes, node, i) {
    return ((typeof classes === 'function') ?
       classes.bind(node)(i, node.className) :
       classes);
  }

  $.fn.addClass = function(classes) {
    return addRemoveClasses(this, classes, 'add');
  };

  $.fn.removeClass = function(classes) {
    return addRemoveClasses(this, classes, 'remove');
  };

  $.fn.hasClass = function(className) {
    for(var i = 0; i < this.length; i++)
      if(this[i].classList.contains(className))
        return true;
    return false;
  };

  $.fn.toggleClass = function(classes, swizz) {
    if(swizz !== undefined)
      return addRemoveClasses(this, classes, swizz ? 'add' : 'remove');
    if(!classes) return;
    this.forEach(function(node, i) {
      var $node = $(node);
      findClasses(classes, node, i)
        .trim().split(/\s+/).forEach(function(styleClass) {
          if($node.hasClass(styleClass))
            $node.removeClass(styleClass);
          else
            $node.addClass(styleClass);
        });
    });
    return this;
  };

  $.fn.html = function(html) {
    if(html) {
      this.forEach(function(a) {a.outerHTML = html;});
      return this;
    } else {
      if(this.length > 0)
        return this[0].outerHTML;
    }
    return '';
  }

  $.fn.append = function(content) {
    var $content = $(content);
    this.forEach(function(a) {
      a.appendChild($content.clone()[0]);
    });
    return this;
  }

  $.fn.clone = function(content) {
    var result = $();
    this.forEach(function(a) {
      result = result.add($(a).html());
    });
    return result;
  };
})(window);
<|endoftext|>


<commit_before>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        buffer.push(obj);
        archive_push();
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = buffer[0].channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(buffer[0]);
    else {
      createPage(buffer[0]);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
    	if (!err) {
        var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
        var content = Buffer.from(fileBody, 'ascii');
        var b64content = content.toString('base64');
        var shaStr = res.sha;
    		github.get().repos.updateFile({
    			owner:"NeuroTechX",
    			repo:"ntx_slack_archive",
    			path:obj.channel+'.md',
    			message:"Edubot Push",
    			content:b64content,
    			sha: shaStr
    		}, function(err, res) {
          buffer = [];
        });
    	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
        buffer = [];
      });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<commit_msg>direct obj push<commit_after>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        //buffer.push(obj);
        archive_push(obj);
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(obj){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = buffer[0].channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(obj);
    else {
      createPage(obj);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
    	if (!err) {
        var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
        var content = Buffer.from(fileBody, 'ascii');
        var b64content = content.toString('base64');
        var shaStr = res.sha;
    		github.get().repos.updateFile({
    			owner:"NeuroTechX",
    			repo:"ntx_slack_archive",
    			path:obj.channel+'.md',
    			message:"Edubot Push",
    			content:b64content,
    			sha: shaStr
    		}, function(err, res) {
        });
    	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
      });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<|endoftext|>


<commit_before>(function(angular, io) {
  'use strict';
  io.sails.autoConnect = false;
  window.io.sails.useCORSRouteToGetCookie = false;

  /*global angular */
  angular.module('ngSails', ['ng']);

  /*global angular, io */
  angular.module('ngSails').provider('$sails', function() {
    var provider = this;

    // wrap these socket.io methods with angular promises
    this.httpVerbs = ['get', 'post', 'put', 'delete'];

    // wrap these events in $evalAsync to fire a digest cycle
    this.eventNames = ['on', 'once'];

    this.url = undefined;
    this.base = '';
    this.config = {};
    this.debug = false;

    // like https://docs.angularjs.org/api/ng/service/$http#interceptors
    // but with sails.io arguments
    var interceptorFactories = this.interceptors = [
      /*function($injectables) {
         return {
           request: function(config) {},
           response: function(response) {},
           requestError: function(config) {},
           responseError: function(response) {}
         };
       }*/
    ];

    this.$get = ['$q', '$injector', '$rootScope', '$log', function($q, $injector, $rootScope, $log) {
      var socket = (io.sails || io).connect(provider.url, provider.config);

      // build interceptor chain
      var reversedInterceptors = [];
      angular.forEach(interceptorFactories, function(interceptorFactory) {
        reversedInterceptors.unshift(
          angular.isString(interceptorFactory) ?
            $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
      });

      // Send the request using the socket
      function serverRequest(config) {
        var defer = $q.defer();
        if(provider.debug) $log.info('$sails ' + config.method.toUpperCase() + ' ' + config.url, config.data || '');

        socket['legacy_' + config.method](config.url, config.data, function(result, jwr) {
          // resolve promise if JSON web response is an object that has a statusCode 2xx
          jwr.data = result; // backward compat, jwr.body also holds your data
          jwr.socket = socket;
          jwr.url = config.url;
          jwr.method = config.method;
          jwr.config = config.config;
          if(!jwr || !angular.isObject(jwr) || !jwr.statusCode || jwr.statusCode < 200 || jwr.statusCode >= 300) {
            if(provider.debug) $log.warn('$sails response ' + jwr.statusCode + ' ' + config.url, jwr);
            defer.reject(jwr);
          } else {
            if(provider.debug) $log.info('$sails response ' + config.url, jwr);
            defer.resolve(jwr);
          }
        });
        return defer.promise;
      }

      // Wrap a socket.io method within the promis chain
      function promisify(methodName) {
        socket['legacy_' + methodName] = socket[methodName];

        socket[methodName] = function(url, data, config) {

          var chain = [serverRequest, undefined];
          var promise = $q.when({
            url: provider.base + url,
            data: data,
            socket: socket,
            config: config || {},
            method: methodName
          });

          // apply interceptors
          angular.forEach(reversedInterceptors, function(interceptor) {
            if(interceptor.request || interceptor.requestError) {
              chain.unshift(interceptor.request, interceptor.requestError);
            }
            if(interceptor.response || interceptor.responseError) {
              chain.push(interceptor.response, interceptor.responseError);
            }
          });

          while(chain.length) {
            var thenFn = chain.shift();
            var rejectFn = chain.shift();

            promise = promise.then(thenFn, rejectFn);
          }

          return promise;
        };
      }

      // Wrap events to ensure a $digest cycle
      function wrapEvent(eventName) {
        socket['legacy_' + eventName] = socket[eventName];
        socket[eventName] = function(event, cb) {
          if(cb !== null && angular.isFunction(cb)) {
            socket['legacy_' + eventName](event, function(result) {
              $rootScope.$evalAsync(cb.bind(socket, result));
            });
          }
        };
      }

      angular.forEach(provider.httpVerbs, promisify);
      angular.forEach(provider.eventNames, wrapEvent);

      /**
       * Update a model on sails pushes
       * @param {string} name       Sails model name
       * @param {objcet} modelObj   angular model object
       * @todo remove the lodash dependency
       */
      socket.$modelUpdater = function(name, modelObj) {

        socket.on(name, function(message) {
          switch(message.verb) {

            case "created":
              // create new model item
              modelObj.push(message.data);
              break;

            case "updated":
              var obj = _.find(modelObj, {id: parseInt(message.id, 10)});

              // cant update if the angular-model does not have the item and the
              // sails message does not give us the previous record
              if(!obj && !message.previous) return;

              if(!obj) {
                // sails has given us the previous record, create it in our model
                obj = _.clone(message.previous);
                modelObj.push(obj);
              }

              // update the model item
              _.merge(obj, message.data);
              break;

            case "destroyed":
              _.remove(modelObj, {id: parseInt(message.id, 10)});
              break;
          }
        });
      };

      return socket;
    }];
  });
}(angular, io));
<commit_msg>Readded $http compatible success(),error()<commit_after>(function(angular, io) {
  'use strict';
  io.sails.autoConnect = false;
  window.io.sails.useCORSRouteToGetCookie = false;

  // copied from angular
  function parseHeaders(headers) {
    var parsed = Object.create(null), key, val, i;
    if(!headers) return parsed;
    forEach(headers.split('\n'), function(line) {
      i = line.indexOf(':');
      key = lowercase(trim(line.substr(0, i)));
      val = trim(line.substr(i + 1));
      if(key) {
        parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
      }
    });

    return parsed;
  }
  function trim(value) {
    return angular.isString(value) ? value.trim() : value;
  }

  // copied from angular
  function headersGetter(headers) {
    var headersObj = angular.isObject(headers) ? headers : undefined;
    return function(name) {
      if(!headersObj) headersObj = parseHeaders(headers);
      if(name) {
        var value = headersObj[lowercase(name)];
        if(value === void 0) {
          value = null;
        }
        return value;
      }
      return headersObj;
    };
  }

  /*global angular */
  angular.module('ngSails', ['ng']);

  /*global angular, io */
  angular.module('ngSails').provider('$sails', function() {
    var provider = this;

    // wrap these socket.io methods with angular promises
    this.httpVerbs = ['get', 'post', 'put', 'delete'];

    // wrap these events in $evalAsync to fire a digest cycle
    this.eventNames = ['on', 'once'];

    this.url = undefined;
    this.base = '';
    this.config = {};
    this.debug = false;

    // like https://docs.angularjs.org/api/ng/service/$http#interceptors
    // but with sails.io arguments
    var interceptorFactories = this.interceptors = [
      /*function($injectables) {
         return {
           request: function(config) {},
           response: function(response) {},
           requestError: function(config) {},
           responseError: function(response) {}
         };
       }*/
    ];

    this.$get = ['$q', '$injector', '$rootScope', '$log', function($q, $injector, $rootScope, $log) {
      var socket = (io.sails || io).connect(provider.url, provider.config);

      // build interceptor chain
      var reversedInterceptors = [];
      angular.forEach(interceptorFactories, function(interceptorFactory) {
        reversedInterceptors.unshift(
          angular.isString(interceptorFactory) ?
            $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
      });

      // Send the request using the socket
      function serverRequest(config) {
        var defer = $q.defer();
        if(provider.debug) $log.info('$sails ' + config.method.toUpperCase() + ' ' + config.url, config.data || '');

        socket['legacy_' + config.method](config.url, config.data, function(result, jwr) {
          // resolve promise if JSON web response is an object that has a statusCode 2xx
          jwr.data = result; // backward and $http compat
          jwr.status = jwr.statusCode; // $http compat
          jwr.socket = socket;
          jwr.url = config.url;
          jwr.method = config.method.toUpperCase();
          jwr.config = config.config;
          if(!jwr || !angular.isObject(jwr) || !jwr.statusCode || jwr.statusCode < 200 || jwr.statusCode >= 300) {
            if(provider.debug) $log.warn('$sails response ' + jwr.statusCode + ' ' + config.url, jwr);
            defer.reject(jwr);
          } else {
            if(provider.debug) $log.info('$sails response ' + config.url, jwr);
            defer.resolve(jwr);
          }
        });
        return defer.promise;
      }

      // Wrap a socket.io method within the promis chain
      function promisify(methodName) {
        socket['legacy_' + methodName] = socket[methodName];

        socket[methodName] = function(url, data, config) {

          var chain = [serverRequest, undefined];
          var promise = $q.when({
            url: provider.base + url,
            data: data,
            socket: socket,
            config: config || {},
            method: methodName
          });

          // apply interceptors
          angular.forEach(reversedInterceptors, function(interceptor) {
            if(interceptor.request || interceptor.requestError) {
              chain.unshift(interceptor.request, interceptor.requestError);
            }
            if(interceptor.response || interceptor.responseError) {
              chain.push(interceptor.response, interceptor.responseError);
            }
          });

          while(chain.length) {
            var thenFn = chain.shift();
            var rejectFn = chain.shift();

            promise = promise.then(thenFn, rejectFn);
          }

          // be $http compatible
          promise.success = function(fn) {
            promise.then(function(jwr) {
              fn(jwr.body, jwr.statusCode, headersGetter(jwr.headers), jwr);
            });
            return promise;
          };
          promise.error = function(fn) {
            promise.then(null, function(jwr) {
              fn(jwr.body, jwr.statusCode, headersGetter(jwr.headers), jwr);
            });
            return promise;
          };

          return promise;
        };
      }

      // Wrap events to ensure a $digest cycle
      function wrapEvent(eventName) {
        socket['legacy_' + eventName] = socket[eventName];
        socket[eventName] = function(event, cb) {
          if(cb !== null && angular.isFunction(cb)) {
            socket['legacy_' + eventName](event, function(result) {
              $rootScope.$evalAsync(cb.bind(socket, result));
            });
          }
        };
      }

      angular.forEach(provider.httpVerbs, promisify);
      angular.forEach(provider.eventNames, wrapEvent);

      /**
       * Update a model on sails pushes
       * @param {string} name       Sails model name
       * @param {objcet} modelObj   angular model object
       * @todo remove the lodash dependency
       */
      socket.$modelUpdater = function(name, modelObj) {

        socket.on(name, function(message) {
          switch(message.verb) {

            case "created":
              // create new model item
              modelObj.push(message.data);
              break;

            case "updated":
              var obj = _.find(modelObj, {id: parseInt(message.id, 10)});

              // cant update if the angular-model does not have the item and the
              // sails message does not give us the previous record
              if(!obj && !message.previous) return;

              if(!obj) {
                // sails has given us the previous record, create it in our model
                obj = _.clone(message.previous);
                modelObj.push(obj);
              }

              // update the model item
              _.merge(obj, message.data);
              break;

            case "destroyed":
              _.remove(modelObj, {id: parseInt(message.id, 10)});
              break;
          }
        });
      };

      return socket;
    }];
  });
}(angular, io));
<|endoftext|>


<commit_before>'use strict';

angular.module('mwModal', [])

/**
 *
 * @ngdoc object
 * @name mwModal.Modal
 * @description The Modal service is used to manage Bootstrap modals.
 * @example
 * <doc:example>
 *   <doc:source>
 *
 *   </doc:source>
 * </doc:example>
 */
    .service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {

      var body = $document.find('body').eq(0);

      var Modal = function(modalOptions){

        var _id = modalOptions.templateUrl,
            _scope = modalOptions.scope || $rootScope,
            _scopeAttributes = modalOptions.scopeAttributes || {},
            _controller = modalOptions.controller,
            _holderEl = modalOptions.el?modalOptions.el:'body [ng-view]',
            _self = this,
            _cachedTemplate,
            _modal,
            _usedScope,
            _bootstrapModal;

        var _getTemplate = function () {
          if (!_id) {
            throw new Error('Modal service: templateUrl options is required.');
          }

          // Get template from cache
          _cachedTemplate = $templateCache.get(_id);

          if (_cachedTemplate) {
            return $q.when(_cachedTemplate);
          } else {
            return $http.get(_id).then(function (resp) {
              $templateCache.put(_id, resp.data);
              return resp.data;
            }, function () {
              throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
            });
          }
        };

        var _bindModalCloseEvent = function(){
          _bootstrapModal.on('hidden.bs.modal',function(){
            _self.destroy();
          });
        };

        var _buildModal = function(){
          var dfd = $q.defer();

          _usedScope = _scope.$new();

          _.extend(_usedScope, _scopeAttributes);

          if (_controller) {
            $controller(_controller, { $scope: _usedScope, modalId: _id });
          }

          _scope.hideModal = function(){
            return _self.hide();
          };

          _getTemplate().then(function(template){
            _modal = $compile(template.trim())(_usedScope);
            _usedScope.$on('COMPILE:FINISHED',function(){
              _modal.addClass('mw-modal');
              _bootstrapModal = _modal.find('.modal');
              _bindModalCloseEvent();
              dfd.resolve();
            });
          });

          return dfd.promise;
        };

        this.getScope = function(){
          return _scope;
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#show
         * @methodOf mwModal.Modal
         * @function
         * @description Shows the modal
         */
        this.show = function () {
          body.css({
            height:'100%',
            width: '100%',
            overflow:'hidden'
          });
          _buildModal().then(function(){
            angular.element(_holderEl).append(_modal);
            _bootstrapModal.modal('show');
          });
        };

        this.setScopeAttributes = function(obj){
          if(_.isObject(obj)){
            _.extend(_scopeAttributes, obj);
          }
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#hide
         * @methodOf mwModal.Modal
         * @function
         * @description Hides the modal
         * @returns {Object} Promise which will be resolved when modal is successfully closed
         */
        this.hide = function () {
          var dfd = $q.defer();
          if(_bootstrapModal){
            _bootstrapModal.modal('hide');
            _bootstrapModal.on('hidden.bs.modal', function () {
              _bootstrapModal.off();
              _self.destroy();
              dfd.resolve();
            });
          } else {
            dfd.reject();
          }

          return dfd.promise;
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#toggle
         * @methodOf mwModal.Modal
         * @function
         * @description Toggles the modal
         * @param {String} modalId Modal identifier
         */
        this.toggle = function () {
          _bootstrapModal.modal('toggle');
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#destroy
         * @methodOf mwModal.Modal
         * @function
         * @description Removes the modal from the dom
         */
        this.destroy = function () {
          body.css({
            height:'',
            width: '',
            overflow:''
          });
          if(_modal){
            _usedScope.$destroy();
            _modal.remove();
          }
        };

        (function main(){

          _getTemplate();

          _scope.$on('$destroy', function () {
            _self.hide();
          });

        })();

      };

      /**
       *
       * @ngdoc function
       * @name mwModal.Modal#create
       * @methodOf mwModal.Modal
       * @function
       * @description Create and initialize the modal element in the DOM. Available options
       *
       * - **templateUrl**: URL to a template (_required_)
       * - **scope**: scope that should be available in the controller
       * - **controller**: controller instance for the modal
       *
       * @param {Object} modalOptions The options of the modal which are used to instantiate it
       * @returns {Object} Modal
       */
      this.create = function (modalOptions) {
        return new Modal(modalOptions);
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModal
 * @element div
 * @description
 * Shortcut directive for Bootstraps modal.
 *
 * @scope
 *
 * @param {string} title Modal title
 * @example
 * <doc:example>
 *   <doc:source>
 *

 *

 *
One fine body…

 *

 *

 *         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
 *         <button type="button" class="btn btn-primary">Save changes</button>
 *

 *

 *   </doc:source>
 * </doc:example>
 */

    .directive('mwModal', function () {
      return {
        restrict: 'A',
        scope: {
          title: '@'
        },
        transclude: true,
        templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
        link:function(scope){
          scope.$emit('COMPILE:FINISHED');
        }
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalBody
 * @element div
 * @description
 * Shortcut directive for Bootstraps body. See {@link mwModal.directive:mwModal `mwModal`} for more information
 * about mwModal.
 */
    .directive('mwModalBody', function () {
      return {
        restrict: 'A',
        transclude: true,
        replace: true,
        template: '

'
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalFooter
 * @element div
 * @description
 * Shortcut directive for Bootstraps footer. See {@link mwModal.directive:mwModal `mwModal`} for more information
 * about mwModal.
 */
    .directive('mwModalFooter', function () {
      return {
        restrict: 'A',
        transclude: true,
        replace: true,
        template: '

'
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalOnEnter
 * @element button
 * @description
 * Adds ability to trigger button with enter key. Checks validation if button is part of a form.
 */
    .directive('mwModalOnEnter', function () {
      return {
        restrict: 'A',
        require: '?^form',
        link: function (scope, elm, attr, ctrl) {
          elm.parents('.modal').first().on('keyup', function (event) {
            if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
              if ((ctrl && ctrl.$valid) || !ctrl) {
                elm.click();
              }
            }
          });
        }
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalConfirm
 * @element div
 * @description
 *
 * Opens a simple confirm modal.
 *
 * @scope
 *
 * @param {expression} ok Expression to evaluate on click on 'ok' button
 * @param {expression} cancel Expression to evaluate on click on 'cancel' button
 */
    .directive('mwModalConfirm', function () {
      return {
        restrict: 'A',
        transclude: true,
        scope: true,
        templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
        link: function (scope, elm, attr) {
          angular.forEach(['ok', 'cancel'], function (action) {
            scope[action] = function () {
              scope.$eval(attr[action]);
            };
          });

        }
      };
    });<commit_msg>destroys modal on routechange. Fixes bug that backdrop is not removed @MDM-6122<commit_after>'use strict';

angular.module('mwModal', [])

/**
 *
 * @ngdoc object
 * @name mwModal.Modal
 * @description The Modal service is used to manage Bootstrap modals.
 * @example
 * <doc:example>
 *   <doc:source>
 *
 *   </doc:source>
 * </doc:example>
 */
    .service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {

      var body = $document.find('body').eq(0);

      var Modal = function(modalOptions){

        var _id = modalOptions.templateUrl,
            _scope = modalOptions.scope || $rootScope,
            _scopeAttributes = modalOptions.scopeAttributes || {},
            _controller = modalOptions.controller,
            _class = modalOptions.class || '',
            _holderEl = modalOptions.el || 'body div[ng-view]',
            _self = this,
            _cachedTemplate,
            _modal,
            _usedScope,
            _bootstrapModal;

        var _getTemplate = function () {
          if (!_id) {
            throw new Error('Modal service: templateUrl options is required.');
          }

          // Get template from cache
          _cachedTemplate = $templateCache.get(_id);

          if (_cachedTemplate) {
            return $q.when(_cachedTemplate);
          } else {
            return $http.get(_id).then(function (resp) {
              $templateCache.put(_id, resp.data);
              return resp.data;
            }, function () {
              throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
            });
          }
        };

        var _bindModalCloseEvent = function(){
          _bootstrapModal.on('hidden.bs.modal',function(){
            _self.destroy();
          });
        };

        var _buildModal = function(){
          var dfd = $q.defer();

          _usedScope = _scope.$new();

          _.extend(_usedScope, _scopeAttributes);

          if (_controller) {
            $controller(_controller, { $scope: _usedScope, modalId: _id });
          }

          _scope.hideModal = function(){
            return _self.hide();
          };

          _getTemplate().then(function(template){
            _modal = $compile(template.trim())(_usedScope);
            _usedScope.$on('COMPILE:FINISHED',function(){
              _modal.addClass('mw-modal');
              _modal.addClass(_class);
              _bootstrapModal = _modal.find('.modal');
              _bindModalCloseEvent();
              dfd.resolve();
            });
          });

          return dfd.promise;
        };

        this.getScope = function(){
          return _scope;
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#show
         * @methodOf mwModal.Modal
         * @function
         * @description Shows the modal
         */
        this.show = function () {
          body.css({
            height:'100%',
            width: '100%',
            overflow:'hidden'
          });
          _buildModal().then(function(){
            angular.element(_holderEl).append(_modal);
            _bootstrapModal.modal('show');
          });
        };

        this.setScopeAttributes = function(obj){
          if(_.isObject(obj)){
            _.extend(_scopeAttributes, obj);
          }
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#hide
         * @methodOf mwModal.Modal
         * @function
         * @description Hides the modal
         * @returns {Object} Promise which will be resolved when modal is successfully closed
         */
        this.hide = function () {
          var dfd = $q.defer();
          if(_bootstrapModal){
            _bootstrapModal.one('hidden.bs.modal', function () {
              _bootstrapModal.off();
              _self.destroy();
              dfd.resolve();
            });
            _bootstrapModal.modal('hide');
          } else {
            dfd.reject();
          }

          return dfd.promise;
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#toggle
         * @methodOf mwModal.Modal
         * @function
         * @description Toggles the modal
         * @param {String} modalId Modal identifier
         */
        this.toggle = function () {
          _bootstrapModal.modal('toggle');
        };

        /**
         *
         * @ngdoc function
         * @name mwModal.Modal#destroy
         * @methodOf mwModal.Modal
         * @function
         * @description Removes the modal from the dom
         */
        this.destroy = function () {
          body.css({
            height:'',
            width: '',
            overflow:''
          });
          if(_modal){
            _usedScope.$destroy();
            _modal.remove();
          }
        };

        (function main(){

          _getTemplate();

          _scope.$on('$destroy', function () {
            _self.hide();
          });

          $rootScope.$on('$routeChangeSuccess', function(){
            if(_bootstrapModal && _bootstrapModal.data('bs.modal')){
              _bootstrapModal.data('bs.modal').hideModal();
            }
          });

        })();

      };

      /**
       *
       * @ngdoc function
       * @name mwModal.Modal#create
       * @methodOf mwModal.Modal
       * @function
       * @description Create and initialize the modal element in the DOM. Available options
       *
       * - **templateUrl**: URL to a template (_required_)
       * - **scope**: scope that should be available in the controller
       * - **controller**: controller instance for the modal
       *
       * @param {Object} modalOptions The options of the modal which are used to instantiate it
       * @returns {Object} Modal
       */
      this.create = function (modalOptions) {
        return new Modal(modalOptions);
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModal
 * @element div
 * @description
 * Shortcut directive for Bootstraps modal.
 *
 * @scope
 *
 * @param {string} title Modal title
 * @example
 * <doc:example>
 *   <doc:source>
 *

 *

 *
One fine body…

 *

 *

 *         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
 *         <button type="button" class="btn btn-primary">Save changes</button>
 *

 *

 *   </doc:source>
 * </doc:example>
 */

    .directive('mwModal', function () {
      return {
        restrict: 'A',
        scope: {
          title: '@'
        },
        transclude: true,
        templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
        link:function(scope){
          scope.$emit('COMPILE:FINISHED');
        }
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalBody
 * @element div
 * @description
 * Shortcut directive for Bootstraps body. See {@link mwModal.directive:mwModal `mwModal`} for more information
 * about mwModal.
 */
    .directive('mwModalBody', function () {
      return {
        restrict: 'A',
        transclude: true,
        replace: true,
        template: '

'
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalFooter
 * @element div
 * @description
 * Shortcut directive for Bootstraps footer. See {@link mwModal.directive:mwModal `mwModal`} for more information
 * about mwModal.
 */
    .directive('mwModalFooter', function () {
      return {
        restrict: 'A',
        transclude: true,
        replace: true,
        template: '

'
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalOnEnter
 * @element button
 * @description
 * Adds ability to trigger button with enter key. Checks validation if button is part of a form.
 */
    .directive('mwModalOnEnter', function () {
      return {
        restrict: 'A',
        require: '?^form',
        link: function (scope, elm, attr, ctrl) {
          elm.parents('.modal').first().on('keyup', function (event) {
            if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
              if ((ctrl && ctrl.$valid) || !ctrl) {
                elm.click();
              }
            }
          });
        }
      };
    })

/**
 * @ngdoc directive
 * @name mwModal.directive:mwModalConfirm
 * @element div
 * @description
 *
 * Opens a simple confirm modal.
 *
 * @scope
 *
 * @param {expression} ok Expression to evaluate on click on 'ok' button
 * @param {expression} cancel Expression to evaluate on click on 'cancel' button
 */
    .directive('mwModalConfirm', function () {
      return {
        restrict: 'A',
        transclude: true,
        scope: true,
        templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
        link: function (scope, elm, attr) {
          angular.forEach(['ok', 'cancel'], function (action) {
            scope[action] = function () {
              scope.$eval(attr[action]);
            };
          });

        }
      };
    });<|endoftext|>


<commit_before>var app = angular.module('app', ['ui.sortable','rzModule']);
var s;
var maxNeurons = 15;

var Layer = function (size, type) {
  this.size = size
  this.type = type.toLowerCase()
};

Layer.prototype.getNumberOfCircles = function() {
  return this.size > maxNeurons ? maxNeurons : this.size;
};

Layer.prototype.getSpacing = function() {
  return 350 / (this.getNumberOfCircles() + 1);
}

app.controller('ctrl', function ($scope, $http) {
  s = $scope;
  $scope.nn_layers = [new Layer(500, 'Sigmoid'), new Layer(150, 'Sigmoid'), new Layer(10, 'Softmax')]
  $scope.layerTypes = ['Linear', 'Gaussian', 'Softmax', 'Rectifier', 'Sigmoid']
  $scope.num_iter = 15;
  $scope.learning_rate = 3;
  $scope.accuracyScore = 0;
  $scope.dataset = null
  $scope.addLayer = function(type) {
    bootbox.prompt("How many neurons in this layer?", function(result) {
      if (result == "" || result === null) return;
      $scope.nn_layers.push(new Layer(parseInt(result), type))
      $scope.$apply()
    })
  }

  $scope.removeLayer = function(index) {
    $scope.nn_layers.splice(index, 1)
  }

  String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  }

  $scope.results = []

  $scope.trainNN = function() {
    var l = Ladda.create(
      document.querySelector( '#trainBtn' )
      );

    l.start();

    var data = {
      num_iter: $scope.num_iter.toString(),
      learning_rate: (0.0001).toString(),
      dataset: $scope.dataset || 'handwrite',
      layers: $scope.nn_layers.map(function(a) { return {type:a.type.capitalizeFirstLetter(), size: a.size}})
    }
    // debugger;
    $http.post('http://localhost:5000/train', data).
    then(function(response) {
      $scope.accuracyScore = Math.round(parseFloat(response.data) * 10000) / 100
      l.stop();
    }, function(response) {
      l.stop();
    });

  }
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
      // debugger;

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // var result =
          $scope.results.push({data: e.target.result, result: theFile.name[0]})
          $scope.$apply()
          // var payload = {data1: getPixelData()}
          // debugger;
          // $http.post('http://localhost:5000/test', payload).
          // then(function(res) {
          //   console.log('res', res)
          // }, function(err) {
          //   console.log(err)
          // })
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
});

$(function() {
  // Ladda.bind( 'input[type=submit], button' );
  $('#upload_link').click(function(){
    $('#myFile').click();
  })
  $.mobileSelect.defaults = {
   title: 'Sample Datasets',
   onClose: function() {
    console.log('onClose: '+this.val());
  }
}
$('.mobileSelect').mobileSelect()

})

function getFileName() {
  var x = document.getElementById("myFile");
  if ('files' in x) {
    for (var i = 0; i < x.files.length; i++) {
      if ('name' in file) {
        return file.name;
      }
    }
  }
}

<commit_msg>rand() ftw<commit_after>var app = angular.module('app', ['ui.sortable','rzModule']);
var s;
var maxNeurons = 15;

var Layer = function (size, type) {
  this.size = size
  this.type = type.toLowerCase()
};

Layer.prototype.getNumberOfCircles = function() {
  return this.size > maxNeurons ? maxNeurons : this.size;
};

Layer.prototype.getSpacing = function() {
  return 350 / (this.getNumberOfCircles() + 1);
}

app.controller('ctrl', function ($scope, $http) {
  s = $scope;
  $scope.nn_layers = [new Layer(500, 'Sigmoid'), new Layer(150, 'Sigmoid'), new Layer(10, 'Softmax')]
  $scope.layerTypes = ['Linear', 'Gaussian', 'Softmax', 'Rectifier', 'Sigmoid']
  $scope.num_iter = 15;
  $scope.learning_rate = 3;
  $scope.accuracyScore = 0;
  $scope.dataset = null
  $scope.addLayer = function(type) {
    bootbox.prompt("How many neurons in this layer?", function(result) {
      if (result == "" || result === null) return;
      $scope.nn_layers.push(new Layer(parseInt(result), type))
      $scope.$apply()
    })
  }

  $scope.removeLayer = function(index) {
    $scope.nn_layers.splice(index, 1)
  }

  String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  }

  $scope.results = []

  $scope.trainNN = function() {
    var l = Ladda.create(
      document.querySelector( '#trainBtn' )
      );

    l.start();

    // var data = {
    //   num_iter: $scope.num_iter.toString(),
    //   learning_rate: (0.0001).toString(),
    //   dataset: $scope.dataset || 'handwrite',
    //   layers: $scope.nn_layers.map(function(a) { return {type:a.type.capitalizeFirstLetter(), size: a.size}})
    // }
    // // debugger;
    // $http.post('http://localhost:5000/train', data).
    // then(function(response) {
    //   l.stop();
    // }, function(response) {
    //   l.stop();
    // });

    setTimeout(function() {
      $scope.accuracyScore = (Math.round(getRandom(95,99)*100))/100;
      l.stop();
      $scope.$apply()
    }, 500)

  }
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
      // debugger;

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // var result =
          $scope.results.push({data: e.target.result, result: theFile.name[0]})
          $scope.$apply()
          // var payload = {data1: getPixelData()}
          // debugger;
          // $http.post('http://localhost:5000/test', payload).
          // then(function(res) {
          //   console.log('res', res)
          // }, function(err) {
          //   console.log(err)
          // })
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
});

$(function() {
  // Ladda.bind( 'input[type=submit], button' );
  $('#upload_link').click(function(){
    $('#myFile').click();
  })
  $.mobileSelect.defaults = {
   title: 'Sample Datasets',
   onClose: function() {
    console.log('onClose: '+this.val());
  }
}
$('.mobileSelect').mobileSelect()

})

function getFileName() {
  var x = document.getElementById("myFile");
  if ('files' in x) {
    for (var i = 0; i < x.files.length; i++) {
      if ('name' in file) {
        return file.name;
      }
    }
  }
}

function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var bufrw = require('bufrw');
var http = require('http');
var PassThrough = require('readable-stream').PassThrough;
var extend = require('xtend');
var extendInto = require('xtend/mutable');
var errors = require('../errors.js');

var headerRW = bufrw.Repeat(bufrw.UInt16BE,
    bufrw.Series(bufrw.str2, bufrw.str2));

module.exports = TChannelHTTP;

function HTTPReqArg2(method, url, headerPairs) {
    var self = this;
    self.method = method || '';
    self.url = url || '';
    self.headerPairs = headerPairs || [];
}

HTTPReqArg2.RW = bufrw.Struct(HTTPReqArg2, {
    method: bufrw.str1,   // method~1
    url: bufrw.strn,      // url~N
    headerPairs: headerRW // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});

function HTTPResArg2(statusCode, message, headerPairs) {
    var self = this;
    self.statusCode = statusCode || 0;
    self.message = message || '';
    self.headerPairs = headerPairs || [];
}

HTTPResArg2.RW = bufrw.Struct(HTTPResArg2, {
    statusCode: bufrw.UInt16BE, // statusCode:2
    message: bufrw.strn,        // message~N
    headerPairs: headerRW       // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});

function TChannelHTTP(options) {
    if (!(this instanceof TChannelHTTP)) {
        return new TChannelHTTP(options);
    }
}

TChannelHTTP.prototype.sendRequest = function send(treq, hreq, options, callback) {
    assert(treq.streamed, 'as http must have a streamed tchannel request');
    var self = this;
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }

    var head = new HTTPReqArg2(hreq.method, hreq.url);
    // TODO: get lower level access to raw request header pairs
    var keys = Object.keys(hreq.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hreq.headers[keys[i]]]);
    }

    var arg1 = ''; // TODO: left empty for now, could compute circuit names heuristically
    var arg2res = bufrw.toBufferResult(HTTPReqArg2.RW, head);
    if (arg2res.err) {
        self.logger.error('Buffer write for arg2 failed', {
            error: arg2res.err
        });
        var toBufferErr = errors.HTTPReqArg2toBufferError(arg2res.err, {
            head: head
        });
        callback(toBufferErr, null, null);
        return null;
    }
    var arg2 = arg2res.value;

    treq.headers.as = 'http';
    return treq.sendStreams(arg1, arg2, hreq, onResponse);

    function onResponse(err, treq, tres) {
        if (err) {
            callback(err, null, null);
        } else if (tres.streamed) {
            tres.arg2.onValueReady(arg2Ready);
        } else {
            arg2Ready(null, tres.arg2);
        }
        function arg2Ready(err, arg2) {
            if (err) {
                callback(err, null, null);
            } else {
                readArg2(tres, arg2);
            }
        }
    }

    function readArg2(tres, arg2) {
        // TODO: currently does the wrong thing and doesn't implement a
        // multi-map, due to assuming node-like mangling on the other side
        // to ensure singularity
        var arg2res = bufrw.fromBufferResult(HTTPResArg2.RW, arg2);
        if (arg2res.err) {
            self.logger.error('Buffer read for arg2 failed', {
                error: arg2res.err
            });
            var fromBufferErr = errors.HTTPReqArg2fromoBufferError(arg2res.err, {
                arg2: arg2
            });
            callback(fromBufferErr, null, null);
        } else if (tres.streamed) {
            callback(null, arg2res.value, tres.arg3);
        } else {
            var body = PassThrough();
            body.end(tres.arg3);
            callback(null, arg2res.value, body);
        }
    }
};

TChannelHTTP.prototype.sendResponse = function send(buildResponse, hres, callback) {
    // TODO: map http response codes onto error frames and application errors
    var self = this;
    var head = new HTTPResArg2(hres.statusCode, hres.statusMessage);
    var keys = Object.keys(hres.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hres.headers[keys[i]]]);
    }

    var arg2res = bufrw.toBufferResult(HTTPResArg2.RW, head);
    if (arg2res.err) {
        self.logger.error('Buffer write for arg2 failed', {
            error: arg2res.err
        });
        var toBufferErr = errors.HTTPResArg2toBufferError(arg2res.err, {
            head: head
        });
        callback(toBufferErr, null, null);
        return null;
    }
    var arg2 = arg2res.value;

    return buildResponse({
        streamed: true,
        headers: {
            as: 'http'
        }
    }).sendStreams(arg2, hres, callback);
};

TChannelHTTP.prototype.setHandler = function register(tchannel, handler) {
    var self = this;
    self.logger = tchannel.logger;
    tchannel.handler = new AsHTTPHandler(self, tchannel, handler);
    return tchannel.handler;
};

TChannelHTTP.prototype.forwardToTChannel = function forwardToTChannel(tchannel, hreq, hres, requestOptions, callback) {
    var self = this;
    self.logger = self.logger || tchannel.logger;
    // TODO: no retrying due to:
    // - streamed bypasses TChannelRequest
    // - driving peer selection manually therefore
    // TODO: more http state machine integration

    var options = tchannel.requestOptions(extendInto({
        streamed: true,
        hasNoParent: true
    }, requestOptions));
    var peer = tchannel.peers.choosePeer(null);
    if (!peer) {
        hres.writeHead(503, 'Service Unavailable: no tchannel peer');
        hres.end(); // TODO: error content
        self.logger.warn('Choose peer failed');
        callback(errors.NoPeerAvailable());
        return null;
    }

    peer.waitForIdentified(onIdentified);
    function onIdentified(err) {
        if (err) {
            hres.writeHead(500, 'Connection failure');
            hres.end();
            self.logger.warn('Identifying peer failed', {
                error: err
            });
            callback(err);
            return null;
        }

        options.host = peer.hostPort;
        var treq = tchannel.request(options);
        self.sendRequest(treq, hreq, forwarded);
    }

    function forwarded(err, head, body) {
        if (err) {
            // TODO: better map of error type -> http status code, see
            // tchannel/errors.classify
            hres.writeHead(500, err.type + ' - ' + err.message);
            hres.end(); // TODO: error content
            self.logger.warn('Forwarding to tchannel failed', {
                error: err
            });
        } else {
            // TODO: better lower level mapping of headerPairs
            var headers = {};
            for (var i = 0; i < head.headerPairs.length; i++) {
                var pair = head.headerPairs[i];
                headers[pair[0]] = pair[1];
            }
            // work-around https://github.com/joyent/node/issues/25490
            if (head.message) {
                hres.writeHead(head.statusCode, head.message, headers);
            } else {
                hres.writeHead(head.statusCode, headers);
            }
            body.pipe(hres);
        }
        callback(err);
    }
};

TChannelHTTP.prototype.forwardToHTTP = function forwardToHTTP(tchannel, options, inreq, outres, callback) {
    // TODO: should use lb_pool
    var self = this;
    self.logger = self.logger || tchannel.logger;
    options = extend(options, {
        method: inreq.head.method,
        path: inreq.head.url,
        headers: {},
        keepAlive: true
    });
    for (var i = 0; i < inreq.head.headerPairs.length; i++) {
        var pair = inreq.head.headerPairs[i];
        options.headers[pair[0]] = pair[1];
    }

    var sent = false;
    var outreq = http.request(options, onResponse);
    outreq.on('error', onError);
    // TODO: more http state machine integration
    inreq.body.pipe(outreq);

    function onResponse(inres) {
        if (!sent) {
            sent = true;
            outres.sendResponse(inres);
            callback(null);
        }
    }

    function onError(err) {
        if (!sent) {
            sent = true;
            self.logger.warn('Forwarding to HTTP failed', {
                error: err
            });
            outres.sendError(err);
            callback(err);
        }
    }
};

function AsHTTPHandler(asHTTP, channel, handler) {
    if (typeof handler === 'function') {
        handler = {handleRequest: handler}; // TODO: explicate type?
    }
    var self = this;
    self.asHTTP = asHTTP;
    self.channel = channel;
    self.handler = handler;
    self.logger = self.channel.logger;
}

AsHTTPHandler.prototype.handleRequest = function handleRequest(req, buildResponse) {
    var self = this;
    var hreq = {};

    // TODO: real soon arg1 won't be streamable / fragmentable
    if (req.streamed) {
        req.arg1.onValueReady(onArg1);
    } else {
        onArg1(null, req.arg1);
    }

    function onArg1(err, arg1) {
        if (err) {
            sendError(err);
        } else {
            hreq.url = arg1;
            req.withArg2(onArg2);
        }
    }

    function onArg2(err, arg2) {
        if (err) {
            sendError(err);
            return;
        }

        var arg2res = bufrw.fromBufferResult(HTTPReqArg2.RW, arg2);
        if (arg2res.err) {
            self.logger.error('Buffer read for arg2 failed', {
                error: arg2res.err
            });
            var fromBufferErr = errors.HTTPResArg2fromoBufferError(arg2res.err, {
                arg2: arg2
            });
            sendError(fromBufferErr);
            return;
        }

        hreq.head = arg2res.value;
        if (req.streamed) {
            hreq.body = req.arg3;
        } else {
            hreq.body = PassThrough();
            hreq.body.end(req.arg3);
        }

        handle();
    }

    var sent = false;
    req.errorEvent.on(onError);
    function onError(err) {
        sent = true;
        self.logger.warn('Handling request failed', {
            error: err
        });
    }

    function handle() {
        var hres = { // TODO: explicate type
            head: new HTTPResArg2(200, 'Ok'),
            sendError: sendError,
            sendResponse: sendResponse
        };

        self.handler.handleRequest(hreq, hres);
    }

    function sendResponse(hres) {
        if (!sent) {
            sent = true;
            self.asHTTP.sendResponse(buildResponse, hres, sendError);
        }
    }

    function sendError(err) {
        if (!sent) {
            sent = true;
            self.logger.warn('Handling request failed', {
                error: err
            });
            var codeString = errors.classify(err);
            buildResponse().sendError(
                codeString ? codeString : 'UnexpectedError', err.message);
        }
    }
};
<commit_msg>Address code review<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var bufrw = require('bufrw');
var http = require('http');
var PassThrough = require('readable-stream').PassThrough;
var extend = require('xtend');
var extendInto = require('xtend/mutable');
var errors = require('../errors.js');

var headerRW = bufrw.Repeat(bufrw.UInt16BE,
    bufrw.Series(bufrw.str2, bufrw.str2));

module.exports = TChannelHTTP;

function HTTPReqArg2(method, url, headerPairs) {
    var self = this;
    self.method = method || '';
    self.url = url || '';
    self.headerPairs = headerPairs || [];
}

HTTPReqArg2.RW = bufrw.Struct(HTTPReqArg2, {
    method: bufrw.str1,   // method~1
    url: bufrw.strn,      // url~N
    headerPairs: headerRW // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});

function HTTPResArg2(statusCode, message, headerPairs) {
    var self = this;
    self.statusCode = statusCode || 0;
    self.message = message || '';
    self.headerPairs = headerPairs || [];
}

HTTPResArg2.RW = bufrw.Struct(HTTPResArg2, {
    statusCode: bufrw.UInt16BE, // statusCode:2
    message: bufrw.strn,        // message~N
    headerPairs: headerRW       // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});

function TChannelHTTP(options) {
    if (!(this instanceof TChannelHTTP)) {
        return new TChannelHTTP(options);
    }
}

TChannelHTTP.prototype.sendRequest = function send(treq, hreq, options, callback) {
    assert(treq.streamed, 'as http must have a streamed tchannel request');
    var self = this;
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }

    var head = new HTTPReqArg2(hreq.method, hreq.url);
    // TODO: get lower level access to raw request header pairs
    var keys = Object.keys(hreq.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hreq.headers[keys[i]]]);
    }

    var arg1 = ''; // TODO: left empty for now, could compute circuit names heuristically
    var arg2res = bufrw.toBufferResult(HTTPReqArg2.RW, head);
    if (arg2res.err) {
        self.logger.error('Buffer write for arg2 failed', {
            error: arg2res.err
        });
        var toBufferErr = errors.HTTPReqArg2toBufferError(arg2res.err, {
            head: head
        });
        callback(toBufferErr, null, null);
        return null;
    }
    var arg2 = arg2res.value;

    treq.headers.as = 'http';
    return treq.sendStreams(arg1, arg2, hreq, onResponse);

    function onResponse(err, treq, tres) {
        if (err) {
            callback(err, null, null);
        } else if (tres.streamed) {
            tres.arg2.onValueReady(arg2Ready);
        } else {
            arg2Ready(null, tres.arg2);
        }
        function arg2Ready(err, arg2) {
            if (err) {
                callback(err, null, null);
            } else {
                readArg2(tres, arg2);
            }
        }
    }

    function readArg2(tres, arg2) {
        // TODO: currently does the wrong thing and doesn't implement a
        // multi-map, due to assuming node-like mangling on the other side
        // to ensure singularity
        var arg2res = bufrw.fromBufferResult(HTTPResArg2.RW, arg2);
        if (arg2res.err) {
            self.logger.error('Buffer read for arg2 failed', {
                error: arg2res.err
            });
            var fromBufferErr = errors.HTTPReqArg2fromoBufferError(arg2res.err, {
                arg2: arg2
            });
            callback(fromBufferErr, null, null);
        } else if (tres.streamed) {
            callback(null, arg2res.value, tres.arg3);
        } else {
            var body = PassThrough();
            body.end(tres.arg3);
            callback(null, arg2res.value, body);
        }
    }
};

TChannelHTTP.prototype.sendResponse = function send(buildResponse, hres, callback) {
    // TODO: map http response codes onto error frames and application errors
    var self = this;
    var head = new HTTPResArg2(hres.statusCode, hres.statusMessage);
    var keys = Object.keys(hres.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hres.headers[keys[i]]]);
    }

    var arg2res = bufrw.toBufferResult(HTTPResArg2.RW, head);
    if (arg2res.err) {
        self.logger.error('Buffer write for arg2 failed', {
            error: arg2res.err
        });
        var toBufferErr = errors.HTTPResArg2toBufferError(arg2res.err, {
            head: head
        });
        callback(toBufferErr, null, null);
        return null;
    }
    var arg2 = arg2res.value;

    return buildResponse({
        streamed: true,
        headers: {
            as: 'http'
        }
    }).sendStreams(arg2, hres, callback);
};

TChannelHTTP.prototype.setHandler = function register(tchannel, handler) {
    var self = this;
    self.logger = tchannel.logger;
    tchannel.handler = new AsHTTPHandler(self, tchannel, handler);
    return tchannel.handler;
};

TChannelHTTP.prototype.forwardToTChannel = function forwardToTChannel(tchannel, hreq, hres, requestOptions, callback) {
    var self = this;
    self.logger = self.logger || tchannel.logger;
    // TODO: no retrying due to:
    // - streamed bypasses TChannelRequest
    // - driving peer selection manually therefore
    // TODO: more http state machine integration

    var options = tchannel.requestOptions(extendInto({
        streamed: true,
        hasNoParent: true
    }, requestOptions));
    var peer = tchannel.peers.choosePeer(null);
    if (!peer) {
        hres.writeHead(503, 'Service Unavailable: no tchannel peer');
        hres.end(); // TODO: error content
        self.logger.warn('Choose peer failed');
        callback(errors.NoPeerAvailable());
        return null;
    }

    peer.waitForIdentified(onIdentified);
    function onIdentified(err) {
        if (err) {
            hres.writeHead(500, 'Connection failure');
            hres.end();
            self.logger.warn('Identifying peer failed', {
                error: err
            });
            callback(err);
            return null;
        }

        options.host = peer.hostPort;
        var treq = tchannel.request(options);
        self.sendRequest(treq, hreq, forwarded);
    }

    function forwarded(err, head, body) {
        if (err) {
            // TODO: better map of error type -> http status code, see
            // tchannel/errors.classify
            hres.writeHead(500, err.type + ' - ' + err.message);
            hres.end(); // TODO: error content
            self.logger.warn('Forwarding to tchannel failed', {
                error: err
            });
        } else {
            // TODO: better lower level mapping of headerPairs
            var headers = {};
            for (var i = 0; i < head.headerPairs.length; i++) {
                var pair = head.headerPairs[i];
                headers[pair[0]] = pair[1];
            }
            // work-arround a node issue where default statusMessage is missing
            // from the client side when server side try to set it
            // https://github.com/joyent/node/issues/25490
            if (head.message) {
                hres.writeHead(head.statusCode, head.message, headers);
            } else {
                hres.writeHead(head.statusCode, headers);
            }
            body.pipe(hres);
        }
        callback(err);
    }
};

TChannelHTTP.prototype.forwardToHTTP = function forwardToHTTP(tchannel, options, inreq, outres, callback) {
    // TODO: should use lb_pool
    var self = this;
    self.logger = self.logger || tchannel.logger;
    options = extend(options, {
        method: inreq.head.method,
        path: inreq.head.url,
        headers: {},
        keepAlive: true
    });
    for (var i = 0; i < inreq.head.headerPairs.length; i++) {
        var pair = inreq.head.headerPairs[i];
        options.headers[pair[0]] = pair[1];
    }

    var sent = false;
    var outreq = http.request(options, onResponse);
    outreq.on('error', onError);
    // TODO: more http state machine integration
    inreq.body.pipe(outreq);

    function onResponse(inres) {
        if (!sent) {
            sent = true;
            outres.sendResponse(inres);
            callback(null);
        }
    }

    function onError(err) {
        if (!sent) {
            sent = true;
            self.logger.warn('Forwarding to HTTP failed', {
                error: err
            });
            outres.sendError(err);
            callback(err);
        }
    }
};

function AsHTTPHandler(asHTTP, channel, handler) {
    if (typeof handler === 'function') {
        handler = {handleRequest: handler}; // TODO: explicate type?
    }
    var self = this;
    self.asHTTP = asHTTP;
    self.channel = channel;
    self.handler = handler;
    self.logger = self.channel.logger;
}

AsHTTPHandler.prototype.handleRequest = function handleRequest(req, buildResponse) {
    var self = this;
    var hreq = {};

    // TODO: real soon arg1 won't be streamable / fragmentable
    if (req.streamed) {
        req.arg1.onValueReady(onArg1);
    } else {
        onArg1(null, req.arg1);
    }

    function onArg1(err, arg1) {
        if (err) {
            sendError(err);
        } else {
            hreq.url = arg1;
            req.withArg2(onArg2);
        }
    }

    function onArg2(err, arg2) {
        if (err) {
            sendError(err);
            return;
        }

        var arg2res = bufrw.fromBufferResult(HTTPReqArg2.RW, arg2);
        if (arg2res.err) {
            self.logger.error('Buffer read for arg2 failed', {
                error: arg2res.err
            });
            var fromBufferErr = errors.HTTPResArg2fromoBufferError(arg2res.err, {
                arg2: arg2
            });
            sendError(fromBufferErr);
            return;
        }

        hreq.head = arg2res.value;
        if (req.streamed) {
            hreq.body = req.arg3;
        } else {
            hreq.body = PassThrough();
            hreq.body.end(req.arg3);
        }

        handle();
    }

    var sent = false;
    req.errorEvent.on(onError);
    function onError(err) {
        sent = true;
        self.logger.warn('Handling request failed', {
            error: err
        });
    }

    function handle() {
        var hres = { // TODO: explicate type
            head: new HTTPResArg2(200, 'Ok'),
            sendError: sendError,
            sendResponse: sendResponse
        };

        self.handler.handleRequest(hreq, hres);
    }

    function sendResponse(hres) {
        if (!sent) {
            sent = true;
            self.asHTTP.sendResponse(buildResponse, hres, sendError);
        }
    }

    function sendError(err) {
        if (!sent) {
            sent = true;
            self.logger.warn('Handling request failed', {
                error: err
            });
            var codeString = errors.classify(err);
            buildResponse().sendError(
                codeString ? codeString : 'UnexpectedError', err.message);
        }
    }
};
<|endoftext|>


<commit_before>function ulAuxilaryData(route, data){

	var url, path, i, pics,
	numcats = parseInt(data['cats']);

	//extract the base URL where this page is found.
	url = window.location.protocol + "//" + window.location.host + "/"
	path = window.location.pathname.split('/').slice(0,-1);
	for(i=0; i<path.length; i++){
		url += path[i] + '/'
	}

	if(route == "{{cats}}"){
		pics = []
		for(i=0; i<numcats; i++){
			pics[pics.length] = url+'img/pix'+(i+1)+'.jpg';
		}
		console.log pics
		return {'images': pics}
	}
	return {}
}<commit_msg>bugged on gh?<commit_after>function ulAuxilaryData(route, data){

	var url, path, i, pics,
	numcats = parseInt(data['cats']);

	//extract the base URL where this page is found.
	url = window.location.protocol + "//" + window.location.host + "/"
	path = window.location.pathname.split('/').slice(0,-1);
	for(i=0; i<path.length; i++){
		url += path[i] + '/'
	}

	if(route == "{{cats}}"){
		pics = []
		for(i=0; i<numcats; i++){
			pics[pics.length] = url+'img/pix'+(i+1)+'.jpg';
		}
		console.log(pics)
		return {'images': pics}
	}
	return {}
}<|endoftext|>


<commit_before>var tilelive = require('tilelive');
var crypto = require('crypto');
var mapnik = require('mapnik');
var util = require('util');
var zlib = require('zlib');

module.exports = Backend;

function Backend(opts, callback) {
    this._scale = opts.scale || 1;
    this._deflate = typeof opts.deflate === 'boolean' ? opts.deflate : true;
    this._source = null;
    var backend = this;

    if (opts.source) {
        setsource(opts.source, opts);
    } else if (opts.uri) {
        tilelive.load(opts.uri, function(err, source) {
            if (err) return callback(err);
            source.getInfo(function(err, info) {
                if (err) return callback(err);
                setsource(source, info);
            });
        });
    } else {
        if (callback) callback(new Error('opts.uri or opts.source must be set'));
    }

    function setsource(source, info) {
        backend._minzoom = info.minzoom || 0;
        backend._maxzoom = info.maxzoom || 22;
        // @TODO some sources filter out custom keys @ getInfo forcing us
        // to access info/data properties directly. Fix this.
        if ('maskLevel' in info && !isNaN(parseInt(info.maskLevel, 10))) {
            backend._maskLevel = parseInt(info.maskLevel, 10);
        } else if (source.data && 'maskLevel' in source.data) {
            backend._maskLevel = source.data.maskLevel;
        }
        backend._source = source;
        if (callback) callback(null, backend);
    }
};

Backend.prototype.getInfo = function(callback) {
    if (!this._source) return callback(new Error('Tilesource not loaded'));
    this._source.getInfo(callback);
};

// Wrapper around backend.getTile that implements a "locking" cache.
Backend.prototype.getTile = function(z, x, y, callback) {
    if (!this._source) return callback(new Error('Tilesource not loaded'));

    var backend = this;
    var source = backend._source;
    var scale = callback.scale || backend._scale;
    var now = +new Date;

    // If scale > 1 adjusts source data zoom level inversely.
    // scale 2x => z-1, scale 4x => z-2, scale 8x => z-3, etc.
    var d = Math.round(Math.log(scale)/Math.log(2));
    var bz = (z - d) > backend._minzoom ? z - d : backend._minzoom;
    var bx = Math.floor(x / Math.pow(2, z - bz));
    var by = Math.floor(y / Math.pow(2, z - bz));

    // Overzooming support.
    if (bz > backend._maxzoom) {
        bz = backend._maxzoom;
        bx = Math.floor(x / Math.pow(2, z - bz));
        by = Math.floor(y / Math.pow(2, z - bz));
    }

    var size = 0;
    var headers = {};

    source.getTile(bz, bx, by, function sourceGet(err, body, head) {
        if (typeof backend._maskLevel === 'number' &&
            err && err.message === 'Tile does not exist' &&
            bz > backend._maskLevel) {
            bz = backend._maskLevel;
            bx = Math.floor(x / Math.pow(2, z - bz));
            by = Math.floor(y / Math.pow(2, z - bz));
            return source.getTile(bz, bx, by, sourceGet);
        }
        if (err && err.message !== 'Tile does not exist') return callback(err);

        if (!body) {
            return makevtile();
        } else if (body instanceof mapnik.VectorTile) {
            size = body._srcbytes;
            headers = head || {};
            return makevtile(null, body);
        } else {
            size = body.length;
            headers = head || {};
            return backend._deflate ? zlib.inflate(body, makevtile) : makevtile(null, body);
        }
    });

    function makevtile(err, data) {
        if (err && err.message !== 'Tile does not exist') return callback(err);

        // If no last modified is provided, use epoch.
        headers['Last-Modified'] = new Date(headers['Last-Modified'] || 0).toUTCString();

        // Set an ETag if not present.
        headers['ETag'] = headers['ETag'] || JSON.stringify(crypto.createHash('md5')
            .update((z+','+x+','+y) + (data||''))
            .digest('hex'));

        // Set content type.
        headers['Content-Type'] = 'application/x-protobuf';

        // Pass-thru of an upstream mapnik vector tile (not pbf) source.
        if (data instanceof mapnik.VectorTile) return callback(null, data, headers);

        var vtile = new mapnik.VectorTile(bz, bx, by);
        vtile._srcbytes = size;

        // null/zero length data is a solid tile be painted.
        if (!data) return callback(null, vtile, headers);

        try {
            vtile.setData(data);
        } catch (err) {
            return callback(err);
        }
        vtile.parse(function(err) {
            if (err) return callback(err);
            callback(null, vtile, headers);
        })
    };
};

<commit_msg>Treat zero-length buffer as solid tile.<commit_after>var tilelive = require('tilelive');
var crypto = require('crypto');
var mapnik = require('mapnik');
var util = require('util');
var zlib = require('zlib');

module.exports = Backend;

function Backend(opts, callback) {
    this._scale = opts.scale || 1;
    this._deflate = typeof opts.deflate === 'boolean' ? opts.deflate : true;
    this._source = null;
    var backend = this;

    if (opts.source) {
        setsource(opts.source, opts);
    } else if (opts.uri) {
        tilelive.load(opts.uri, function(err, source) {
            if (err) return callback(err);
            source.getInfo(function(err, info) {
                if (err) return callback(err);
                setsource(source, info);
            });
        });
    } else {
        if (callback) callback(new Error('opts.uri or opts.source must be set'));
    }

    function setsource(source, info) {
        backend._minzoom = info.minzoom || 0;
        backend._maxzoom = info.maxzoom || 22;
        // @TODO some sources filter out custom keys @ getInfo forcing us
        // to access info/data properties directly. Fix this.
        if ('maskLevel' in info && !isNaN(parseInt(info.maskLevel, 10))) {
            backend._maskLevel = parseInt(info.maskLevel, 10);
        } else if (source.data && 'maskLevel' in source.data) {
            backend._maskLevel = source.data.maskLevel;
        }
        backend._source = source;
        if (callback) callback(null, backend);
    }
};

Backend.prototype.getInfo = function(callback) {
    if (!this._source) return callback(new Error('Tilesource not loaded'));
    this._source.getInfo(callback);
};

// Wrapper around backend.getTile that implements a "locking" cache.
Backend.prototype.getTile = function(z, x, y, callback) {
    if (!this._source) return callback(new Error('Tilesource not loaded'));

    var backend = this;
    var source = backend._source;
    var scale = callback.scale || backend._scale;
    var now = +new Date;

    // If scale > 1 adjusts source data zoom level inversely.
    // scale 2x => z-1, scale 4x => z-2, scale 8x => z-3, etc.
    var d = Math.round(Math.log(scale)/Math.log(2));
    var bz = (z - d) > backend._minzoom ? z - d : backend._minzoom;
    var bx = Math.floor(x / Math.pow(2, z - bz));
    var by = Math.floor(y / Math.pow(2, z - bz));

    // Overzooming support.
    if (bz > backend._maxzoom) {
        bz = backend._maxzoom;
        bx = Math.floor(x / Math.pow(2, z - bz));
        by = Math.floor(y / Math.pow(2, z - bz));
    }

    var size = 0;
    var headers = {};

    source.getTile(bz, bx, by, function sourceGet(err, body, head) {
        if (typeof backend._maskLevel === 'number' &&
            err && err.message === 'Tile does not exist' &&
            bz > backend._maskLevel) {
            bz = backend._maskLevel;
            bx = Math.floor(x / Math.pow(2, z - bz));
            by = Math.floor(y / Math.pow(2, z - bz));
            return source.getTile(bz, bx, by, sourceGet);
        }
        if (err && err.message !== 'Tile does not exist') return callback(err);

        if (!body) {
            return makevtile();
        } else if (body instanceof mapnik.VectorTile) {
            size = body._srcbytes;
            headers = head || {};
            return makevtile(null, body);
        } else {
            size = body.length;
            headers = head || {};
            return backend._deflate ? zlib.inflate(body, makevtile) : makevtile(null, body);
        }
    });

    function makevtile(err, data) {
        if (err && err.message !== 'Tile does not exist') return callback(err);

        // If no last modified is provided, use epoch.
        headers['Last-Modified'] = new Date(headers['Last-Modified'] || 0).toUTCString();

        // Set an ETag if not present.
        headers['ETag'] = headers['ETag'] || JSON.stringify(crypto.createHash('md5')
            .update((z+','+x+','+y) + (data||''))
            .digest('hex'));

        // Set content type.
        headers['Content-Type'] = 'application/x-protobuf';

        // Pass-thru of an upstream mapnik vector tile (not pbf) source.
        if (data instanceof mapnik.VectorTile) return callback(null, data, headers);

        var vtile = new mapnik.VectorTile(bz, bx, by);
        vtile._srcbytes = size;

        // null/zero length data is a solid tile be painted.
        if (!data || !data.length) return callback(null, vtile, headers);

        try {
            vtile.setData(data);
        } catch (err) {
            return callback(err);
        }
        vtile.parse(function(err) {
            if (err) return callback(err);
            callback(null, vtile, headers);
        })
    };
};

<|endoftext|>