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

// Create our app
var app = express();
const PORT = process.env.PORT || 3000;

app.use(function(req,res,next){
  if(req.headers['x-forwarded-proto'] === 'http'){
    next();
  }else{
    res.redirect('http://'+ req.hostname + req.url);
  }
});
app.use(express.static('public'));

app.listen(PORT,function(){
  console.log('Express server is up on port '+PORT);
});
<commit_msg>update heroku server<commit_after>var express = require('express');

// Create our app
var app = express();
const PORT = process.env.PORT || 3000;

app.use(function(req,res,next){
  if(req.headers['x-forwarded-proto'] === 'https'){
    res.redirect('http://'+ req.hostname + req.url);

  }else{
    next();
  }
});
app.use(express.static('public'));

app.listen(PORT,function(){
  console.log('Express server is up on port '+PORT);
});
<|endoftext|>


<commit_before>//[The "BSD license"]
// Copyright (c) 2012 Terence Parr
// Copyright (c) 2012 Sam Harwell
// Copyright (c) 2014 Eric Vergnaud
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

// A token has properties: text, type, line, character position in the line
// (so we can ignore tabs), token channel, index, and source from which
// we obtained this token.

function Token() {
	this.source = null;
	this.type = null; // token type of the token
	this.channel = null; // The parser ignores everything not on
							// DEFAULT_CHANNEL
	this.start = null; // optional; return -1 if not implemented.
	this.stop = null; // optional; return -1 if not implemented.
	this.tokenIndex = null; // from 0..n-1 of the token object in the input
							// stream
	this.line = null; // line=1..n of the 1st character
	this.column = null; // beginning of the line at which it occurs, 0..n-1
	this._text = null; // text of the token.
	return this;
}

Token.INVALID_TYPE = 0;

// During lookahead operations, this "token" signifies we hit rule end ATN state
// and did not follow it despite needing to.
Token.EPSILON = -2;

Token.MIN_USER_TOKEN_TYPE = 1;

Token.EOF = -1;

// All tokens go to the parser (unless skip() is called in that rule)
// on a particular "channel". The parser tunes to a particular channel
// so that whitespace etc... can go to the parser on a "hidden" channel.

Token.DEFAULT_CHANNEL = 0;

// Anything on different channel than DEFAULT_CHANNEL is not parsed
// by parser.

Token.HIDDEN_CHANNEL = 1;

// Explicitly set the text for this token. If {code text} is not
// {@code null}, then {@link //getText} will return this value rather than
// extracting the text from the input.
//
// @param text The explicit text of the token, or {@code null} if the text
// should be obtained from the input along with the start and stop indexes
// of the token.

Object.defineProperty(Token.prototype, "text", {
	get : function() {
		return this._text;
	},
	set : function(text) {
		this._text = text;
	}
});

Token.prototype.getTokenSource = function() {
	return this.source[0];
};

Token.prototype.getInputStream = function() {
	return this.source[1];
};

function CommonToken(source, type, channel, start, stop) {
	Token.call(this);
	this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;
	this.type = type !== undefined ? type : null;
	this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;
	this.start = start !== undefined ? start : -1;
	this.stop = stop !== undefined ? stop : -1;
	this.tokenIndex = -1;
	if (this.source[0] !== null) {
		this.line = source[0].line;
		this.column = source[0].column;
	} else {
		this.column = -1;
	}
	return this;
}

CommonToken.prototype = Object.create(Token.prototype);
CommonToken.prototype.constructor = CommonToken;

// An empty {@link Pair} which is used as the default value of
// {@link //source} for tokens that do not have a source.
CommonToken.EMPTY_SOURCE = [ null, null ];

// Constructs a new {@link CommonToken} as a copy of another {@link Token}.
//
//

// If {@code oldToken} is also a {@link CommonToken} instance, the newly
// constructed token will share a reference to the {@link //text} field and
// the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
// be assigned the result of calling {@link //getText}, and {@link //source}
// will be constructed from the result of {@link Token//getTokenSource} and
// {@link Token//getInputStream}.

//
// @param oldToken The token to copy.
//
CommonToken.prototype.clone = function() {
	var t = new CommonToken(this.source, this.type, this.channel, this.start,
			this.stop);
	t.tokenIndex = this.tokenIndex;
	t.line = this.line;
	t.column = this.column;
	t.text = this.text;
	return t;
};

Object.defineProperty(CommonToken.prototype, "text", {
	get : function() {
		if (this._text !== null) {
			return this._text;
		}
		var input = this.getInputStream();
		if (input === null) {
			return null;
		}
		var n = input.size;
		if (this.start < n && this.stop < n) {
			return input.getText(this.start, this.stop);
		} else {
			return "<EOF>";
		}
	},
	set : function(text) {
		this._text = text;
	}
});

CommonToken.prototype.toString = function() {
	var txt = this.text;
	if (txt !== null) {
		txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
	} else {
		txt = "<no text>";
	}
	return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" +
			txt + "',<" + this.type + ">" +
			(this.channel > 0 ? ",channel=" + this.channel : "") + "," +
			this.line + ":" + this.column + "]";
};

exports.Token = Token;
exports.CommonToken = CommonToken;
<commit_msg>removed NL<commit_after>//[The "BSD license"]
// Copyright (c) 2012 Terence Parr
// Copyright (c) 2012 Sam Harwell
// Copyright (c) 2014 Eric Vergnaud
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

// A token has properties: text, type, line, character position in the line
// (so we can ignore tabs), token channel, index, and source from which
// we obtained this token.

function Token() {
	this.source = null;
	this.type = null; // token type of the token
	this.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL
	this.start = null; // optional; return -1 if not implemented.
	this.stop = null; // optional; return -1 if not implemented.
	this.tokenIndex = null; // from 0..n-1 of the token object in the input stream
	this.line = null; // line=1..n of the 1st character
	this.column = null; // beginning of the line at which it occurs, 0..n-1
	this._text = null; // text of the token.
	return this;
}

Token.INVALID_TYPE = 0;

// During lookahead operations, this "token" signifies we hit rule end ATN state
// and did not follow it despite needing to.
Token.EPSILON = -2;

Token.MIN_USER_TOKEN_TYPE = 1;

Token.EOF = -1;

// All tokens go to the parser (unless skip() is called in that rule)
// on a particular "channel". The parser tunes to a particular channel
// so that whitespace etc... can go to the parser on a "hidden" channel.

Token.DEFAULT_CHANNEL = 0;

// Anything on different channel than DEFAULT_CHANNEL is not parsed
// by parser.

Token.HIDDEN_CHANNEL = 1;

// Explicitly set the text for this token. If {code text} is not
// {@code null}, then {@link //getText} will return this value rather than
// extracting the text from the input.
//
// @param text The explicit text of the token, or {@code null} if the text
// should be obtained from the input along with the start and stop indexes
// of the token.

Object.defineProperty(Token.prototype, "text", {
	get : function() {
		return this._text;
	},
	set : function(text) {
		this._text = text;
	}
});

Token.prototype.getTokenSource = function() {
	return this.source[0];
};

Token.prototype.getInputStream = function() {
	return this.source[1];
};

function CommonToken(source, type, channel, start, stop) {
	Token.call(this);
	this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;
	this.type = type !== undefined ? type : null;
	this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;
	this.start = start !== undefined ? start : -1;
	this.stop = stop !== undefined ? stop : -1;
	this.tokenIndex = -1;
	if (this.source[0] !== null) {
		this.line = source[0].line;
		this.column = source[0].column;
	} else {
		this.column = -1;
	}
	return this;
}

CommonToken.prototype = Object.create(Token.prototype);
CommonToken.prototype.constructor = CommonToken;

// An empty {@link Pair} which is used as the default value of
// {@link //source} for tokens that do not have a source.
CommonToken.EMPTY_SOURCE = [ null, null ];

// Constructs a new {@link CommonToken} as a copy of another {@link Token}.
//
//

// If {@code oldToken} is also a {@link CommonToken} instance, the newly
// constructed token will share a reference to the {@link //text} field and
// the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
// be assigned the result of calling {@link //getText}, and {@link //source}
// will be constructed from the result of {@link Token//getTokenSource} and
// {@link Token//getInputStream}.

//
// @param oldToken The token to copy.
//
CommonToken.prototype.clone = function() {
	var t = new CommonToken(this.source, this.type, this.channel, this.start,
			this.stop);
	t.tokenIndex = this.tokenIndex;
	t.line = this.line;
	t.column = this.column;
	t.text = this.text;
	return t;
};

Object.defineProperty(CommonToken.prototype, "text", {
	get : function() {
		if (this._text !== null) {
			return this._text;
		}
		var input = this.getInputStream();
		if (input === null) {
			return null;
		}
		var n = input.size;
		if (this.start < n && this.stop < n) {
			return input.getText(this.start, this.stop);
		} else {
			return "<EOF>";
		}
	},
	set : function(text) {
		this._text = text;
	}
});

CommonToken.prototype.toString = function() {
	var txt = this.text;
	if (txt !== null) {
		txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
	} else {
		txt = "<no text>";
	}
	return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" +
			txt + "',<" + this.type + ">" +
			(this.channel > 0 ? ",channel=" + this.channel : "") + "," +
			this.line + ":" + this.column + "]";
};

exports.Token = Token;
exports.CommonToken = CommonToken;
<|endoftext|>


<commit_before>"use strict";

var logger = require('../logger').get('appium')
  , fs = require('fs')
  , ncp = require('ncp').ncp
  , request = require('request')
  , _ = require('underscore')
  , path = require('path')
  , rimraf = require('rimraf')
  , exec = require('child_process').exec
  , util = require('util')
  , temp = require('temp')
  , os = require('os').type()
  , AdmZip = require('adm-zip');

exports.downloadFile = function(fileUrl, cb) {
  // We will be downloading the files to a directory, so make sure it's there
  // This step is not required if you have manually created the directory
  temp.open({prefix: 'appium-app', suffix: '.zip'}, function(err, info) {
    var file = fs.createWriteStream(info.path);
    request(fileUrl).pipe(file).on('close', function() {
      logger.info(fileUrl + ' downloaded to ' + info.path);
      cb(info.path);
    });
  });
};

exports.copyLocalZip = function(localZipPath, cb) {
  logger.info("Copying local zip to tmp dir");
  fs.stat(localZipPath, function(err) {
    if (err) return cb(err);
    temp.open({prefix: 'appium-app', suffix: '.zip'}, function(err, info) {
      var infile = fs.createReadStream(localZipPath);
      var outfile = fs.createWriteStream(info.path);
      infile.pipe(outfile).on('close', function() {
        logger.info(localZipPath + ' copied to ' + info.path);
        cb(null, info.path);
      });
    });
  });
};

exports.unzipFile = function(zipPath, cb) {
  logger.info("Unzipping " + zipPath);
  exports.testZipArchive(zipPath, function(err, valid) {
    if (valid) {
      if (exports.isWindows()) {
        var zip = new AdmZip(zipPath);
        zip.extractAllTo(path.dirname(zipPath), true);
        logger.info("Unzip successful");
        cb(null,null);
      } else {
        var execOpts = {cwd: path.dirname(zipPath), maxBuffer: 524288};
        exec('unzip -o ' + zipPath, execOpts, function(err, stderr, stdout) {
          if (!err) {
            logger.info("Unzip successful");
            cb(null, stderr);
          } else {
            logger.error("Unzip threw error " + err);
            logger.error("Stderr: " + stderr);
            logger.error("Stdout: " + stdout);
            cb("Archive could not be unzipped, check appium logs.", null);
          }
        });
      }
    } else {
      cb(err, null);
    }
  });
};

exports.testZipArchive = function(zipPath, cb) {
  logger.info("Testing zip archive: " + zipPath);
  if (exports.isWindows()) {
    if (fs.existsSync(zipPath)) {
      logger.info("Zip archive tested clean");
      cb(null, true);
    } else {
      cb("Zip archive was not found.", false);
    }
  } else {
    var execOpts = {cwd: path.dirname(zipPath)};
    exec("unzip -t " + zipPath, execOpts, function(err, stderr, stdout) {
      if (!err) {
        if(/No errors detected/.exec(stderr)) {
          logger.info("Zip archive tested clean");
          cb(null, true);
        } else {
          logger.error("Zip file " + zipPath + " was not valid");
          logger.error("Stderr: " + stderr);
          logger.error("Stdout: " + stdout);
          cb("Zip archive did not test successfully, check appium server logs " +
             "for output", false);
        }
      } else {
        logger.error("Test zip archive threw error " + err);
        logger.error("Stderr: " + stderr);
        logger.error("Stdout: " + stdout);
        cb("Error testing zip archive, are you sure this is a zip file?", null);
      }
    });
  }
};

exports.unzipApp = function(zipPath, appExt, cb) {
  exports.unzipFile(zipPath, function(err, output) {
    if (!err) {
      var reg = new RegExp("inflating: (.+" + appExt + ")/?");
      var match = reg.exec(output);
      if (match) {
        var appPath = path.resolve(path.dirname(zipPath), match[1]);
        cb(null, appPath);
      } else {
        cb("App zip unzipped OK, but we couldn't find a .app bundle in it. " +
           "Make sure your archive contains the .app package and nothing else",
           null);
      }
    } else {
      cb(err, null);
    }
  });
};

exports.checkBuiltInApp = function(appName, version, cb) {
  logger.info("Looking for built in app " + appName);
  exports.getBuiltInAppDir(version, function(err, appDir) {
    if (err) {
      cb(err);
    } else {
      var appPath = path.resolve(appDir, appName + ".app");
      fs.stat(appPath, function(err, s) {
        if (err) {
          cb(err, appPath);
        } else if (!s.isDirectory()) {
          cb("App package was not a directory", appPath);
        } else {
          logger.info("Got app, trying to copy to tmp dir");
          exports.copyBuiltInApp(appPath, appName, cb);
        }
      });
    }
  });
};

exports.checkSafari = function(version, cb) {
  exports.checkBuiltInApp("MobileSafari", version, cb);
};

exports.checkPreferencesApp = function(version, cb) {
  exports.checkBuiltInApp("Preferences", version, cb);
};

exports.getBuiltInAppDir = function(version, cb) {
  var appDir = "/Applications/Xcode.app/Contents/Developer/Platforms" +
               "/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" +
               version + ".sdk/Applications/";
  fs.stat(appDir, function(err, s) {
    if (err) {
      cb(err);
    } else if (!s.isDirectory()) {
      cb("Could not load built in applications directory");
    } else {
      cb(null, appDir);
    }
  });
};

exports.copyBuiltInApp = function(appPath, appName, cb) {
  var newAppDir = path.resolve(exports.getTempPath(), 'Appium-' + appName + '.app');
  ncp(appPath, newAppDir, function(err) {
    if (err) {
      cb(err);
    } else {
      logger.info("Copied " + appName + " to " + newAppDir);
      cb(null, newAppDir);
    }
  });
};

exports.cleanSafari = function(safariVer, cb) {
  var baseDir = "Library/Application Support/iPhone Simulator/" +
                       safariVer + "/Library/";
  exports.getUser(function(err, user) {
    if (err) {
      logger.error(err);
      cb(err);
    } else {
      var baseSupportDir = path.resolve("/Users", user, baseDir);
      fs.stat(baseSupportDir, function(err) {
        if (err) {
          logger.info(err.message);
          var p = process.env.HOME + '/' + baseDir;
          if(!fs.existsSync(p)) {
            return cb(new Error("Could not find support directory for mobile safari, does " +
                         "it exist at " + baseDir + " or " + p + "?"));
          } else {
            baseSupportDir = p;
          }
        }
        var toDeletes = [
          'Caches/Snapshots/com.apple.mobilesafari'
          , 'Caches/com.apple.mobilesafari/Cache.db*'
          , 'Caches/com.apple.WebAppCache/*.db'
          , 'Safari/*.plist'
          , 'WebKit/LocalStorage/*.*'
          , 'Library/WebKit/GeolocationSites.plist'
          , 'Cookies/*.binarycookies'
        ];
        var deletes = 0;
        var errToRet = null;
        var finish = function(err) {
          deletes++;
          if (err) {
            errToRet = err;
          }
          if (deletes === toDeletes.length) {
            cb(errToRet);
          }
        };
        _.each(toDeletes, function(del) {
          var toDelete = path.resolve(baseSupportDir, del);
          toDelete = toDelete.replace(/ /g, "\\ ");
          logger.info("Deleting " + toDelete);
          var cmd = "rm -rf " + toDelete;
          exec(cmd, function(err) {
            finish(err);
          });
        });
      });
    }
  });
};

exports.getUser = function(cb) {
  logger.info("Determining current user");
  exec("whoami", { maxBuffer: 524288 }, function(err, stdout) {
    if (err) {
      logger.error(err);
      cb(err);
    } else {
      logger.info("User is " + stdout.trim());
      cb(null, stdout.trim());
    }
  });
};

exports.delay = function(secs) {
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < (secs * 1000.0));
};

var pad0 = function(x) {
  if (x.toString().length == 1) {
    x = '0' + x;
  }
  return x;
};

exports.escapeSpecialChars = function(str, quoteEscape) {
  if (typeof str !== "string") {
    return str;
  }
  if (typeof quoteEscape === "undefined") {
    quoteEscape = false;
  }
  str = str
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'");
  if (quoteEscape) {
    var re = new RegExp(quoteEscape, "g");
    str = str.replace(re, "\\" + quoteEscape);
  }
  return str;
};

exports.parseWebCookies = function(cookieStr) {
  var cookies = [];
  var splits = cookieStr.trim().split(";");
  _.each(splits, function(split) {
    split = split.trim();
    if (split !== "") {
      split = split.split("=");
      cookies.push({
        name: decodeURIComponent(split[0])
        , value: decodeURIComponent(split[1])
      });
    }
  });
  return cookies;
};

exports.rotateImage = function(imgPath, deg, cb) {
  logger.info("Rotating image " + imgPath + " " + deg + " degrees");
  var scriptPath = path.resolve(__dirname, "uiauto/Rotate.applescript");
  var cmd = "osascript " + scriptPath + " " + JSON.stringify(imgPath) +
            " " + deg;
  exec(cmd, { maxBuffer: 524288 }, function(err, stdout) {
    if (err) return cb(err);
    console.log(stdout);
    cb(null);
  });
};

exports.isWindows = function() {
  return os === 'Windows_NT';
};

exports.getTempPath = function () {
  return exports.isWindows() ? "C:\\Windows\\Temp" : "/tmp";
};

exports.getGitRev = function(cb) {
  var cwd = path.resolve(__dirname, "..");
  exec("git rev-parse HEAD", {cwd: cwd, maxBuffer: 524288}, function(err, stdout) {
    if (err) return cb(err);
    cb(null, stdout.trim());
  });
};
<commit_msg>Fixed an issue where 'stdout maxBuffer exceeded' throws when unzipping a lot of files.<commit_after>"use strict";

var logger = require('../logger').get('appium')
  , fs = require('fs')
  , ncp = require('ncp').ncp
  , request = require('request')
  , _ = require('underscore')
  , path = require('path')
  , rimraf = require('rimraf')
  , exec = require('child_process').exec
  , util = require('util')
  , temp = require('temp')
  , os = require('os').type()
  , AdmZip = require('adm-zip');

exports.downloadFile = function(fileUrl, cb) {
  // We will be downloading the files to a directory, so make sure it's there
  // This step is not required if you have manually created the directory
  temp.open({prefix: 'appium-app', suffix: '.zip'}, function(err, info) {
    var file = fs.createWriteStream(info.path);
    request(fileUrl).pipe(file).on('close', function() {
      logger.info(fileUrl + ' downloaded to ' + info.path);
      cb(info.path);
    });
  });
};

exports.copyLocalZip = function(localZipPath, cb) {
  logger.info("Copying local zip to tmp dir");
  fs.stat(localZipPath, function(err) {
    if (err) return cb(err);
    temp.open({prefix: 'appium-app', suffix: '.zip'}, function(err, info) {
      var infile = fs.createReadStream(localZipPath);
      var outfile = fs.createWriteStream(info.path);
      infile.pipe(outfile).on('close', function() {
        logger.info(localZipPath + ' copied to ' + info.path);
        cb(null, info.path);
      });
    });
  });
};

exports.unzipFile = function(zipPath, cb) {
  logger.info("Unzipping " + zipPath);
  exports.testZipArchive(zipPath, function(err, valid) {
    if (valid) {
      if (exports.isWindows()) {
        var zip = new AdmZip(zipPath);
        zip.extractAllTo(path.dirname(zipPath), true);
        logger.info("Unzip successful");
        cb(null,null);
      } else {
        var execOpts = {cwd: path.dirname(zipPath), maxBuffer: 524288};
        exec('unzip -o ' + zipPath, execOpts, function(err, stderr, stdout) {
          if (!err) {
            logger.info("Unzip successful");
            cb(null, stderr);
          } else {
            logger.error("Unzip threw error " + err);
            logger.error("Stderr: " + stderr);
            logger.error("Stdout: " + stdout);
            cb("Archive could not be unzipped, check appium logs.", null);
          }
        });
      }
    } else {
      cb(err, null);
    }
  });
};

exports.testZipArchive = function(zipPath, cb) {
  logger.info("Testing zip archive: " + zipPath);
  if (exports.isWindows()) {
    if (fs.existsSync(zipPath)) {
      logger.info("Zip archive tested clean");
      cb(null, true);
    } else {
      cb("Zip archive was not found.", false);
    }
  } else {
    var execOpts = {cwd: path.dirname(zipPath)};
    exec("unzip -tq " + zipPath, execOpts, function(err, stderr, stdout) {
      if (!err) {
        if(/No errors detected/.exec(stderr)) {
          logger.info("Zip archive tested clean");
          cb(null, true);
        } else {
          logger.error("Zip file " + zipPath + " was not valid");
          logger.error("Stderr: " + stderr);
          logger.error("Stdout: " + stdout);
          cb("Zip archive did not test successfully, check appium server logs " +
             "for output", false);
        }
      } else {
        logger.error("Test zip archive threw error " + err);
        logger.error("Stderr: " + stderr);
        logger.error("Stdout: " + stdout);
        cb("Error testing zip archive, are you sure this is a zip file? " + err, null);
      }
    });
  }
};

exports.unzipApp = function(zipPath, appExt, cb) {
  exports.unzipFile(zipPath, function(err, output) {
    if (!err) {
      var reg = new RegExp("inflating: (.+" + appExt + ")/?");
      var match = reg.exec(output);
      if (match) {
        var appPath = path.resolve(path.dirname(zipPath), match[1]);
        cb(null, appPath);
      } else {
        cb("App zip unzipped OK, but we couldn't find a .app bundle in it. " +
           "Make sure your archive contains the .app package and nothing else",
           null);
      }
    } else {
      cb(err, null);
    }
  });
};

exports.checkBuiltInApp = function(appName, version, cb) {
  logger.info("Looking for built in app " + appName);
  exports.getBuiltInAppDir(version, function(err, appDir) {
    if (err) {
      cb(err);
    } else {
      var appPath = path.resolve(appDir, appName + ".app");
      fs.stat(appPath, function(err, s) {
        if (err) {
          cb(err, appPath);
        } else if (!s.isDirectory()) {
          cb("App package was not a directory", appPath);
        } else {
          logger.info("Got app, trying to copy to tmp dir");
          exports.copyBuiltInApp(appPath, appName, cb);
        }
      });
    }
  });
};

exports.checkSafari = function(version, cb) {
  exports.checkBuiltInApp("MobileSafari", version, cb);
};

exports.checkPreferencesApp = function(version, cb) {
  exports.checkBuiltInApp("Preferences", version, cb);
};

exports.getBuiltInAppDir = function(version, cb) {
  var appDir = "/Applications/Xcode.app/Contents/Developer/Platforms" +
               "/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" +
               version + ".sdk/Applications/";
  fs.stat(appDir, function(err, s) {
    if (err) {
      cb(err);
    } else if (!s.isDirectory()) {
      cb("Could not load built in applications directory");
    } else {
      cb(null, appDir);
    }
  });
};

exports.copyBuiltInApp = function(appPath, appName, cb) {
  var newAppDir = path.resolve(exports.getTempPath(), 'Appium-' + appName + '.app');
  ncp(appPath, newAppDir, function(err) {
    if (err) {
      cb(err);
    } else {
      logger.info("Copied " + appName + " to " + newAppDir);
      cb(null, newAppDir);
    }
  });
};

exports.cleanSafari = function(safariVer, cb) {
  var baseDir = "Library/Application Support/iPhone Simulator/" +
                       safariVer + "/Library/";
  exports.getUser(function(err, user) {
    if (err) {
      logger.error(err);
      cb(err);
    } else {
      var baseSupportDir = path.resolve("/Users", user, baseDir);
      fs.stat(baseSupportDir, function(err) {
        if (err) {
          logger.info(err.message);
          var p = process.env.HOME + '/' + baseDir;
          if(!fs.existsSync(p)) {
            return cb(new Error("Could not find support directory for mobile safari, does " +
                         "it exist at " + baseDir + " or " + p + "?"));
          } else {
            baseSupportDir = p;
          }
        }
        var toDeletes = [
          'Caches/Snapshots/com.apple.mobilesafari'
          , 'Caches/com.apple.mobilesafari/Cache.db*'
          , 'Caches/com.apple.WebAppCache/*.db'
          , 'Safari/*.plist'
          , 'WebKit/LocalStorage/*.*'
          , 'Library/WebKit/GeolocationSites.plist'
          , 'Cookies/*.binarycookies'
        ];
        var deletes = 0;
        var errToRet = null;
        var finish = function(err) {
          deletes++;
          if (err) {
            errToRet = err;
          }
          if (deletes === toDeletes.length) {
            cb(errToRet);
          }
        };
        _.each(toDeletes, function(del) {
          var toDelete = path.resolve(baseSupportDir, del);
          toDelete = toDelete.replace(/ /g, "\\ ");
          logger.info("Deleting " + toDelete);
          var cmd = "rm -rf " + toDelete;
          exec(cmd, function(err) {
            finish(err);
          });
        });
      });
    }
  });
};

exports.getUser = function(cb) {
  logger.info("Determining current user");
  exec("whoami", { maxBuffer: 524288 }, function(err, stdout) {
    if (err) {
      logger.error(err);
      cb(err);
    } else {
      logger.info("User is " + stdout.trim());
      cb(null, stdout.trim());
    }
  });
};

exports.delay = function(secs) {
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < (secs * 1000.0));
};

var pad0 = function(x) {
  if (x.toString().length == 1) {
    x = '0' + x;
  }
  return x;
};

exports.escapeSpecialChars = function(str, quoteEscape) {
  if (typeof str !== "string") {
    return str;
  }
  if (typeof quoteEscape === "undefined") {
    quoteEscape = false;
  }
  str = str
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'");
  if (quoteEscape) {
    var re = new RegExp(quoteEscape, "g");
    str = str.replace(re, "\\" + quoteEscape);
  }
  return str;
};

exports.parseWebCookies = function(cookieStr) {
  var cookies = [];
  var splits = cookieStr.trim().split(";");
  _.each(splits, function(split) {
    split = split.trim();
    if (split !== "") {
      split = split.split("=");
      cookies.push({
        name: decodeURIComponent(split[0])
        , value: decodeURIComponent(split[1])
      });
    }
  });
  return cookies;
};

exports.rotateImage = function(imgPath, deg, cb) {
  logger.info("Rotating image " + imgPath + " " + deg + " degrees");
  var scriptPath = path.resolve(__dirname, "uiauto/Rotate.applescript");
  var cmd = "osascript " + scriptPath + " " + JSON.stringify(imgPath) +
            " " + deg;
  exec(cmd, { maxBuffer: 524288 }, function(err, stdout) {
    if (err) return cb(err);
    console.log(stdout);
    cb(null);
  });
};

exports.isWindows = function() {
  return os === 'Windows_NT';
};

exports.getTempPath = function () {
  return exports.isWindows() ? "C:\\Windows\\Temp" : "/tmp";
};

exports.getGitRev = function(cb) {
  var cwd = path.resolve(__dirname, "..");
  exec("git rev-parse HEAD", {cwd: cwd, maxBuffer: 524288}, function(err, stdout) {
    if (err) return cb(err);
    cb(null, stdout.trim());
  });
};
<|endoftext|>


<commit_before>// Helper Functions
import firebase from 'APP/fire'

// ----------------------------------
// --- Presentation/Slide Helpers ---
// ----------------------------------
export const getSlideType = (presentationID, slideID) => {
  let slideType
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/type`)
    .once('value', snapshot => {
      slideType = snapshot.val()
    })
  return slideType
}

export const getPresentationTitle = presentationID =>
  firebase.database()
    .ref(`presentations/${presentationID}/title`)
    .once('value')
    .then(presTitle => presTitle.val())

export const getSlides = presentationID =>
  firebase.database()
    .ref(`presentations/${presentationID}/slides`)
    .on('value', snapshot => snapshot)

export const getQuillSnippet = (presentationID, slideID) => {
  let snippet
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quillContents`)
    .once('value', snapshot => {
      snippet = snapshot.val()
    })
  return JSON.parse(snippet)
}

export const getVRDescription = (presentationID, slideID) => {
  let description
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/VRContents/description`)
    .once('value', snapshot => {
      description = snapshot.val()
    })
  return description
}

export const slideMetadata = (presentationID, slideID) => {
  const slideData = {}
  if (getSlideType(presentationID, slideID) === 'quill') {
    slideData.type = 'Text'
    const quillSnippet = getQuillSnippet(presentationID, slideID)
    if (quillSnippet && typeof(quillSnippet.ops[0].insert) === 'string') {
      slideData.content = quillSnippet.ops[0].insert.slice(0, 71)
    } else {
      slideData.content = 'Image'
    }
  }
  else if (getSlideType(presentationID, slideID) === 'quiz') {
    slideData.type = 'Quiz'
    slideData.content = getQuestion(presentationID, slideID)
  }
  else if (getSlideType(presentationID, slideID) === 'VR') {
    slideData.type = 'VR'
    slideData.content = getVRDescription(presentationID, slideID)
  }
  return slideData
}

// --------------------
// --- Quiz Helpers ---
// --------------------
export const getQuestion = (presentationID, slideID) => {
  let question
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/question`)
    .once('value', snapshot => {
      question = snapshot.val()
    })
  return question
}

export const getAnswers = (presentationID, slideID) => {
  let answers
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/answers`)
    .once('value', snapshot => {
      answers = snapshot.val()
    })
  return answers
}

export const getCorrectAnswers = (presentationID, slideID) => {
  let correctAnswers
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/correctAnswers`)
    .once('value', snapshot => {
      correctAnswers = snapshot.val()
    })
  return correctAnswers
}

export const slideHasQuiz = (presentationID, slideID) => {
  let hasQuiz
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/type`)
    .once('value', snapshot => {
      const slideType = snapshot.val()
      hasQuiz = slideType === 'quiz'
    })
  return hasQuiz
}

// construct random quiz data **MAKE SOME**
export const generateRandomQuiz = () => {
  const randomQuizes = [
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What instrument was crafted to sound like the human voice?',
      answers: ['Oboe', 'Violin', 'Trombone', 'Saxophone', 'Trumpet', 'Guitar']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    }
  ]

  return randomQuizes[Math.floor(Math.random() * 10)]
}
<commit_msg>fix: can't slice null<commit_after>// Helper Functions
import firebase from 'APP/fire'

// ----------------------------------
// --- Presentation/Slide Helpers ---
// ----------------------------------
export const getSlideType = (presentationID, slideID) => {
  let slideType
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/type`)
    .once('value', snapshot => {
      slideType = snapshot.val()
    })
  return slideType
}

export const getPresentationTitle = presentationID =>
  firebase.database()
    .ref(`presentations/${presentationID}/title`)
    .once('value')
    .then(presTitle => presTitle.val())

export const getSlides = presentationID =>
  firebase.database()
    .ref(`presentations/${presentationID}/slides`)
    .on('value', snapshot => snapshot)

export const getQuillSnippet = (presentationID, slideID) => {
  let snippet
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quillContents`)
    .once('value', snapshot => {
      snippet = snapshot.val()
    })
    .then(() => JSON.parse(snippet))
}

export const getVRDescription = (presentationID, slideID) => {
  let description
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/VRContents/description`)
    .once('value', snapshot => {
      description = snapshot.val()
    })
  return description
}

export const slideMetadata = (presentationID, slideID) => {
  const slideData = {}
  if (getSlideType(presentationID, slideID) === 'quill') {
    slideData.type = 'Text'
    const quillSnippet = getQuillSnippet(presentationID, slideID)
    if (quillSnippet && typeof(quillSnippet.ops[0].insert) === 'string') {
      slideData.content = quillSnippet.ops[0].insert.slice(0, 71)
    } else {
      slideData.content = 'Image'
    }
  } else if (getSlideType(presentationID, slideID) === 'quiz') {
    slideData.type = 'Quiz'
    slideData.content = getQuestion(presentationID, slideID)
  } else if (getSlideType(presentationID, slideID) === 'VR') {
    slideData.type = 'VR'
    slideData.content = getVRDescription(presentationID, slideID)
  }
  return slideData
}

// --------------------
// --- Quiz Helpers ---
// --------------------
export const getQuestion = (presentationID, slideID) => {
  let question
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/question`)
    .once('value', snapshot => {
      question = snapshot.val()
    })
  return question
}

export const getAnswers = (presentationID, slideID) => {
  let answers
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/answers`)
    .once('value', snapshot => {
      answers = snapshot.val()
    })
  return answers
}

export const getCorrectAnswers = (presentationID, slideID) => {
  let correctAnswers
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/quiz-contents/correctAnswers`)
    .once('value', snapshot => {
      correctAnswers = snapshot.val()
    })
  return correctAnswers
}

export const slideHasQuiz = (presentationID, slideID) => {
  let hasQuiz
  firebase.database()
    .ref(`presentations/${presentationID}/slides/${slideID}/type`)
    .once('value', snapshot => {
      const slideType = snapshot.val()
      hasQuiz = slideType === 'quiz'
    })
  return hasQuiz
}

// construct random quiz data **MAKE SOME**
export const generateRandomQuiz = () => {
  const randomQuizes = [
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What instrument was crafted to sound like the human voice?',
      answers: ['Oboe', 'Violin', 'Trombone', 'Saxophone', 'Trumpet', 'Guitar']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    },
    {
      question: 'What is the largest city in North America by population?',
      answers: ['New York', 'Mexico City', 'Los Angeles', 'Quebec', 'Chicago', 'Boston']
    }
  ]

  return randomQuizes[Math.floor(Math.random() * 10)]
}
<|endoftext|>


<commit_before>require('babel/register')({
  ignore: /node_modules|public/
})

// modules
var koa = require('koa')
var qs = require('koa-qs')
var csrf = require('koa-csrf')
var mount = require('koa-mount')
var serve = require('koa-static')
var session = require('koa-session')
var compress = require('koa-compress')
var debug = require('debug')('bshed:server')
var responseTime = require('koa-response-time')

// application modules
debug('loading modules')
var config = require('./config')
var models = require('./models')
var s3 = require('./lib/s3')
var api = require('./api')
var client = require('./client/renderer/middleware')

// initialization
debug('initializing modules')
s3 = s3(config.aws)
models = models({
  config: config.database
})
api = api({
  config: config.api,
  models: models,
  s3: s3
})
client = client({
  assetPath: config.server.assets
})

/**
 * SERVER
 */
var server = qs(koa())
server.name = config.server.name
server.env = config.server.env
server.keys = config.secret
server.config = config
server.models = models
server.api = api

/**
 * MIDDLEWARE
 */
if (server.env === 'development')
  server.use(require('koa-logger')()) // request logging
server.use(responseTime()) // x-response-time
server.use(compress()) // compression
server.use(serve(config.server.assets, config.server.middleware.serve)) // assets
server.use(session(config.server.middleware.session, server)) // sessions
server.use(csrf()) // csrf

// set csrf cookie token
server.use(function* setCsrfCookie (next) {
  this.cookies.set('XSRF-TOKEN', this.csrf)
  yield next
})

/**
 * APPLICATIONS
 */
debug('mounting modules')
server.use(mount(api))
server.use(mount(client))

/**
 * SERVER INITIALIZER
 *
 * Listen for connections
 * returns server instance
 */
server.init = function init (port=config.server.port) {
  debug('initializing server using port %d', port)
  server.server = server.listen(port, () => debug('listening on port %d', port))
  return server.server
}

// export the server so it can be started externally
module.exports = server

// initialize server if called directly
if (require.main === module)
  server.init()
<commit_msg>Cleaning up server<commit_after>// modules
var koa = require('koa')
var qs = require('koa-qs')
var csrf = require('koa-csrf')
var session = require('koa-session')
var compress = require('koa-compress')
var debug = require('debug')('bshed:server')
var middleware = require('./utils/middleware')
var responseTime = require('koa-response-time')

// libs and modules
debug('loading libs and modules')
var modelLoader = require('./models')
var s3Loader = require('./lib/s3')
var apiLoader = require('./api')

// configuration
debug('loading and generating config')
var configGenerator = require('./config')
var config = configGenerator({})

// initialization
debug('initializing libs and modules')
var s3 = s3Loader(config.aws)
var models = modelLoader(config)
var api = apiLoader({config, models, s3})

/**
 * SERVER
 * Exported so it can be started externally
 */
var server = module.exports = qs(koa())
Object.assign(server, {
  name: config.name,
  keys: config.keys,
  env: config.env,
  config,
  models,
  api,
  s3
})

/**
 * MIDDLEWARE
 */

// request logging
if (server.env === 'development')
  server.use(require('koa-logger')())

// x-response-time
server.use(responseTime())

// compression
server.use(compress())

// cookie sessions
server.use(session(config.middleware.session, server))

// csrf token
server.use(csrf())

// XSRF-TOKEN
server.use(middleware.setCsrfToken())

// logged_in cookie
server.use(middleware.setLoggedInCookie())

/**
 * APPLICATION
 */
debug('mounting modules')
server.use(api)

/**
 * SERVER INITIALIZER
 *
 * Listen for connections
 * returns server instance
 */
server.init = function init (port=config.port) {
  debug(`initializing server using port ${port}`)
  server.server = server.listen(port, () => debug(`listening on port ${port}`))
  return server.server
}

// initialize server if called directly
if (require.main === module)
  server.init()
<|endoftext|>


<commit_before>Ajax = {
  init: function() {
    $.ajaxSetup({
      error: function(req, textStatus, errorThrown){
        // common
        if (req.status == 400) {
          Notifier.error(req.responseText);
          return;
        }
        else if (req.status == 401) {
          if (demo) return Notifier.error("That action is not supported in demo mode.");
          $.cookie('back', window.location.href);
          window.location = current_stream+'/login';
          return;
        }
        else if (req.status == 404) return;

        // stream.js
        if (this.url.indexOf(stream_url) >= 0) {
          if (req.status == 0) {
            Notifier.error("You are offline.");
            StreamLoader.schedule_autoload(30 * 1000);
            return;
          }
          else if (req.status == 403) {
            $('#loading_data').remove();
            $('#loading_data_failed').show();
            alert('You do not have permission to view or organize on this squad. ' +
              'You may need to sign out and sign back in on another account or ' +
              'request an organizer invitation from the squad leaders.');
            return;
          }
        }
        // not stream.js
        else {
          if (req.status == 0) {
            Notifier.error("You are offline.");
            return;
          }
          else if (req.status == 403) {
            Notifier.error('You do not have permission to perform that action. ' +
              'You may need to sign out and sign back in on another account or ' +
              'request an organizer invitation from the squad leaders.');
            return;
          }
        }

        if (errorThrown){ throw errorThrown; }
        if (req.responseText) {
          console.log(req.responseText);
          // this is a little white lie -- this actually usually occurs due to a server bug
          Notifier.error("Oops!  It looks like your connection is having problems. "+
            "Please try that action again soon.");
        }
      }
    });
  }
};
<commit_msg>the server is returning 401 for no stream access now, i think<commit_after>Ajax = {
  init: function() {
    $.ajaxSetup({
      error: function(req, textStatus, errorThrown){
        // common
        if (req.status == 400) {
          Notifier.error(req.responseText);
          return;
        }
        else if (req.status == 401) {
          if (demo) return Notifier.error("That action is not supported in demo mode.");
          $.cookie('back', window.location.href);
          window.location = current_stream+'/login';
          return;
        }
        else if (req.status == 404) return;

        // stream.js
        if (this.url.indexOf(stream_url) >= 0) {
          if (req.status == 0) {
            Notifier.error("You are offline.");
            StreamLoader.schedule_autoload(30 * 1000);
            return;
          }
          else if (req.status == 401 || req.status == 403) {
            $('#loading_data').remove();
            $('#loading_data_failed').show();
            alert('You do not have permission to view or organize on this squad. ' +
              'You may need to sign out and sign back in on another account or ' +
              'request an organizer invitation from the squad leaders.');
            return;
          }
        }
        // not stream.js
        else {
          if (req.status == 0) {
            Notifier.error("You are offline.");
            return;
          }
          else if (req.status == 403) {
            Notifier.error('You do not have permission to perform that action. ' +
              'You may need to sign out and sign back in on another account or ' +
              'request an organizer invitation from the squad leaders.');
            return;
          }
        }

        if (errorThrown){ throw errorThrown; }
        if (req.responseText) {
          console.log(req.responseText);
          // this is a little white lie -- this actually usually occurs due to a server bug
          Notifier.error("Oops!  It looks like your connection is having problems. "+
            "Please try that action again soon.");
        }
      }
    });
  }
};
<|endoftext|>


<commit_before>var type = require("../type");
var event = require("../event");
var config = require("../config");
var render = require("../render");

require("./event");

var store = new WeakMap();
var cachedProps = new WeakMap();

function update(dom, component, root) {
  event.emit(component, "update");
  var vtree = component.render();
  render(root, vtree);
  event.emit(component, "updated");
}

function emitEvent(dom, component, type, detail) {
  var event = new CustomEvent(type, {
    detail: detail
  });
  dom.dispatchEvent(event);
}

function register(name, componentClass) {
  var propTypes = componentClass.prototype.propTypes;
  document.registerElement(name, {
    prototype: Object.assign(Object.create(HTMLElement.prototype), {
      createdCallback: function() {
        var component = new componentClass({});
        var root = this.createShadowRoot();
        event.on(component, "upstream:update", update.bind(null, this, component, root));
        event.on(component, "upstream:emit-event", emitEvent.bind(null, this, component));
        event.emit(component, "create");
        store.set(this, {
          component: component,
          root: root
        });
      },
      attachedCallback: function() {
        var state = store.get(this);
        event.emit(state.component, "mount", state.root);
      },
      detachedCallback: function() {
        var state = store.get(this);
        event.emit(state.component, "unmount");
      },
      attributeChangedCallback: function(name, previous, value) {
        if(!propTypes[name]) {
          return;
        }
        var state = store.get(this);
        var oldProps = cachedProps.get(this) || {};
        var props = Object.assign({}, oldProps);
        if(value === null) {
          delete props[name];
        } else {
          if(propTypes[name] === type.boolean) {
            props[name] = true;
          } else {
            props[name] = type.cast(value, propTypes[name]);
          }
        }
        cachedProps.set(this, props);
        state.component.replaceProps(props);
      }
    })
  });
}

module.exports = register;
<commit_msg>remove unused require()<commit_after>var type = require("../type");
var event = require("../event");
var render = require("../render");

require("./event");

var store = new WeakMap();
var cachedProps = new WeakMap();

function update(dom, component, root) {
  event.emit(component, "update");
  var vtree = component.render();
  render(root, vtree);
  event.emit(component, "updated");
}

function emitEvent(dom, component, type, detail) {
  var event = new CustomEvent(type, {
    detail: detail
  });
  dom.dispatchEvent(event);
}

function register(name, componentClass) {
  var propTypes = componentClass.prototype.propTypes;
  document.registerElement(name, {
    prototype: Object.assign(Object.create(HTMLElement.prototype), {
      createdCallback: function() {
        var component = new componentClass({});
        var root = this.createShadowRoot();
        event.on(component, "upstream:update", update.bind(null, this, component, root));
        event.on(component, "upstream:emit-event", emitEvent.bind(null, this, component));
        event.emit(component, "create");
        store.set(this, {
          component: component,
          root: root
        });
      },
      attachedCallback: function() {
        var state = store.get(this);
        event.emit(state.component, "mount", state.root);
      },
      detachedCallback: function() {
        var state = store.get(this);
        event.emit(state.component, "unmount");
      },
      attributeChangedCallback: function(name, previous, value) {
        if(!propTypes[name]) {
          return;
        }
        var state = store.get(this);
        var oldProps = cachedProps.get(this) || {};
        var props = Object.assign({}, oldProps);
        if(value === null) {
          delete props[name];
        } else {
          if(propTypes[name] === type.boolean) {
            props[name] = true;
          } else {
            props[name] = type.cast(value, propTypes[name]);
          }
        }
        cachedProps.set(this, props);
        state.component.replaceProps(props);
      }
    })
  });
}

module.exports = register;
<|endoftext|>


<commit_before>/**
 * @author Kuitos
 * @homepage https://github.com/kuitos/
 * @since 2015-11-30
 */

var path = require('path');
var jsonServer = require('json-mock-kuitos');
var webpack = require('webpack');
var config = require('./webpack-dev.config');

var app = jsonServer.create();
var compiler = webpack(config);

var apiPrefix = '';
var filename = path.resolve(__dirname, './mock/db.json');

app.use(require('webpack-dev-middleware')(compiler, {
	noInfo: false,
	stats: {
		colors: true,
		cached: false
	},
	publicPath: config.output.publicPath
}));

// redirect root location to demos index
app.use(/\/$/, function(req, res) {
	res.redirect('/demos/index.html');
});

app.use(require('webpack-hot-middleware')(compiler));
app.use(jsonServer.defaults({static: path.resolve(__dirname)}));
app.use(jsonServer.router(apiPrefix, filename));

app.listen(3000, 'localhost', function(err) {
	if (err) {
		console.log(err);
		return;
	}

	console.log('Listening at http://localhost:3000');
});
<commit_msg>refactor(server.js): 修改使用端口的方式 (#252)<commit_after>/**
 * @author Kuitos
 * @homepage https://github.com/kuitos/
 * @since 2015-11-30
 */

var path = require('path');
var jsonServer = require('json-mock-kuitos');
var webpack = require('webpack');
var config = require('./webpack-dev.config');

var app = jsonServer.create();
var compiler = webpack(config);

var apiPrefix = '';
var filename = path.resolve(__dirname, './mock/db.json');

app.use(require('webpack-dev-middleware')(compiler, {
	noInfo: false,
	stats: {
		colors: true,
		cached: false
	},
	publicPath: config.output.publicPath
}));

// redirect root location to demos index
app.use(/\/$/, function(req, res) {
	res.redirect('/demos/index.html');
});

app.use(require('webpack-hot-middleware')(compiler));
app.use(jsonServer.defaults({static: path.resolve(__dirname)}));
app.use(jsonServer.router(apiPrefix, filename));

const port = 3000;
app.listen(port, 'localhost', function(err) {
	if (err) {
		console.log(err);
		return;
	}

	console.log(`Listening at http://localhost:${port}`);
});

<|endoftext|>


<commit_before>function getResult(callback, json) {

    console.log("Call made : api_2_call_2");

    var input = json.input;

    var all_required = false;
    if(input.geoCode&&input.date){
        var date = input.date;
        var geoCode = input.geoCode;
        all_required = true;
    }

    if(all_required){

        var date_ISO_8601 = date + 'T';

        if(input.time){
            var time = input.time;
            date_ISO_8601 += time.toString();
        }else{
            date_ISO_8601 += '00:00:00';
        }

        date_ISO_8601 += 'Z';

        json.input.date_ISO_8601 = date_ISO_8601;

        json.index = json.index+1;
        if(json.step[json.index].nb=="end"){
            callback(json);
        }else{
             var action_module = require('./'+ json.step[json.index].call_id + '.js');
             action_module.getResult(function(result) {
                callback(result);
             },json);
        }
    }
}

exports.getResult = getResult;
<commit_msg>Update api_2_call_2.js<commit_after>function getResult(callback, json) {

    console.log("Call made : api_2_call_2");

    var input = json.input;

    var all_required = false;
    if(input.geoCode&&input.date){
        var date = input.date;
        var geoCode = input.geoCode;
        all_required = true;
    }

    if(all_required){

        var date_ISO_8601 = date + 'T';

        if(input.time){
            console.log("input api_2_call_2 : ", input);
            console.log("time api_2_call_2 : ");
            //var time = input.time;
            //date_ISO_8601 += time.toString();
        }else{
            date_ISO_8601 += '00:00:00';
        }

        date_ISO_8601 += 'Z';

        json.input.date_ISO_8601 = date_ISO_8601;

        json.index = json.index+1;
        if(json.step[json.index].nb=="end"){
            callback(json);
        }else{
             var action_module = require('./'+ json.step[json.index].call_id + '.js');
             action_module.getResult(function(result) {
                callback(result);
             },json);
        }
    }
}

exports.getResult = getResult;
<|endoftext|>


<commit_before>/**
 * Get a travel time surface and accessibility results for a particular origin.
 * Pass in references to the query (the JS object stored in query.json), the stopTreeCache, the origin file, the
 * x and y coordinates of the origin relative to the query, what parameter you want (BEST_CASE, WORST_CASE or AVERAGE),
 * and a grid. Returns a travel time/accessibility surface which can be used by isochoroneTile and accessibilityForCutoff
 */
export default function getSurface ({grid, origin, query, stopTreeCache, which}) {
  let surface = new Uint8Array(query.width * query.height)

  let transitOffset = getTransitOffset(origin.data[0])

  // how many departure minutes are there. skip number of stops
  let nMinutes = origin.data[transitOffset + 1]

  let travelTimes = new Uint8Array(nMinutes)

  // store the accessibility at each departure minute for every possible cutoff 1 - 120
  let access = new Float64Array(nMinutes * 120)

  // x and y refer to pixel coordinates not origins here
  // loop over rows first
  for (let y = 0, pixelIdx = 0, stcOffset = 0; y < query.height; y++) {
    for (let x = 0; x < query.width; x++, pixelIdx++) {
      let nStops = stopTreeCache.data[stcOffset++]

      // can we reach this pixel without riding transit?
      let nonTransitTime = origin.getNonTransitTime({x, y})

      // fill with unreachable, or the walk distance
      travelTimes.fill(nonTransitTime)

      for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
        // read the stop ID
        let stopId = stopTreeCache.data[stcOffset++]

        // read the time (minutes)
        let time = stopTreeCache.data[stcOffset++]

        // de-delta-code times
        for (let minute = 0, previous = 0; minute < nMinutes; minute++) {
          let offset = origin.index[stopId] + minute * 2 // * 2 because path info is included as well
          let travelTimeToStop = origin.data[offset] + previous
          previous = travelTimeToStop

          if (travelTimeToStop === -1) continue

          let travelTimeToPixel = (travelTimeToStop / 60 + time) | 0

          if (travelTimeToPixel > 254) continue

          if (travelTimes[minute] > travelTimeToPixel) travelTimes[minute] = travelTimeToPixel
        }
      }

      // compute and set value for pixel
      surface[pixelIdx] = computePixelValue(which, travelTimes)

      // compute access values
      computeAccessValues(x, y, query, grid, travelTimes, access)
    }
  }

  return {
    surface,
    access,
    nMinutes
  }
}

/**
 * Where is the transit portion of the origin data there are a certain number of pixels in each direction aroudn the origin with times in them. read the radius, multiply by two to get diameter, add one because there is a pixel in the center, square to get number of pixels, add one to skip the first value which gives radius, and or with to convert to 32-bit int.
 *
 * @param {Number} radius
 * @return {Number}
 */

export function getTransitOffset (radius) {
  return (Math.pow(radius * 2 + 1, 2) + 1) | 0
}

/**
 * Get the pixel value
 *
 * @param {String} which
 * @param {Uint8Array} travelTimes
 * @return {Number} pixelValue
 */

export function computePixelValue (which, travelTimes) {
  switch (which) {
    case 'BEST_CASE':
      return computeBestPixelValue(travelTimes)
    case 'AVERAGE':
      return computeAveragePixelValue(travelTimes)
    case 'WORST_CASE':
      return computeWorstPixelValue(travelTimes)
  }
}

/**
 * Compute best pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeBestPixelValue (travelTimes) {
  let pixel = 255
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.min(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute average pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeAveragePixelValue (travelTimes) {
  let sum = 0
  let count = 0

  for (let i = 0; i < travelTimes.length; i++) {
    if (travelTimes[i] !== 255) {
      sum += travelTimes[i]
      count++
    }
  }

  // coerce to int
  if (count > travelTimes.length / 2) return (sum / count) | 0
  else return 255
}

/**
 * Compute worst pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeWorstPixelValue (travelTimes) {
  let pixel = 0
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.max(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute access values for x, y
 *
 * @param {Number} x
 * @param {Number} y
 * @param {Object} query
 * @param {Object} grid
 * @param {Uint8Array} travelTimes
 * @param {Float64Array} accessPerMinute
 */

export function computeAccessValues (x, y, query, grid, travelTimes, access) {
  // get value of this pixel from grid
  // or everything with 0 so that v8 can do type inference
  let gridx = x + query.west - grid.west | 0
  let gridy = y + query.north - grid.north | 0

  // if condition below fails we're off the grid, value is zero, don't bother with calculations
  if (gridx >= 0 && gridx < grid.width && gridy >= 0 && gridy < grid.height) {
    let val = grid.data[gridy * grid.width + gridx]

    for (let minute = 0; minute < travelTimes.length; minute++) {
      let travelTime = travelTimes[minute]

      if (travelTime !== 255) {
        // put this in all of the correct cutoff categories for this minute
        for (let cutoff = 119; cutoff >= travelTime; cutoff--) {
          access[cutoff * travelTimes.length + minute] += val
        }
      }
    }
  }
}
<commit_msg>remove optimizations which have no effect on speed.<commit_after>/**
 * Get a travel time surface and accessibility results for a particular origin.
 * Pass in references to the query (the JS object stored in query.json), the stopTreeCache, the origin file, the
 * x and y coordinates of the origin relative to the query, what parameter you want (BEST_CASE, WORST_CASE or AVERAGE),
 * and a grid. Returns a travel time/accessibility surface which can be used by isochoroneTile and accessibilityForCutoff
 */
export default function getSurface ({grid, origin, query, stopTreeCache, which}) {
  let surface = new Uint8Array(query.width * query.height)

  let transitOffset = getTransitOffset(origin.data[0])

  // how many departure minutes are there. skip number of stops
  let nMinutes = origin.data[transitOffset + 1]

  let travelTimes = new Uint8Array(nMinutes)

  // store the accessibility at each departure minute for every possible cutoff 1 - 120
  let access = new Float64Array(nMinutes * 120)

  // x and y refer to pixel coordinates not origins here
  // loop over rows first
  for (let y = 0, pixelIdx = 0, stcOffset = 0; y < query.height; y++) {
    for (let x = 0; x < query.width; x++, pixelIdx++) {
      let nStops = stopTreeCache.data[stcOffset++]

      // can we reach this pixel without riding transit?
      let nonTransitTime = origin.getNonTransitTime({x, y})

      // fill with unreachable, or the walk distance
      travelTimes.fill(nonTransitTime)

      for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
        // read the stop ID
        let stopId = stopTreeCache.data[stcOffset++]

        // read the time (minutes)
        let time = stopTreeCache.data[stcOffset++]

        // de-delta-code times
        for (let minute = 0, previous = 0; minute < nMinutes; minute++) {
          let offset = origin.index[stopId] + minute * 2 // * 2 because path info is included as well
          let travelTimeToStop = origin.data[offset] + previous
          previous = travelTimeToStop

          if (travelTimeToStop === -1) continue

          let travelTimeToPixel = (travelTimeToStop / 60 + time) | 0

          if (travelTimeToPixel > 254) continue

          if (travelTimes[minute] > travelTimeToPixel) travelTimes[minute] = travelTimeToPixel
        }
      }

      // compute and set value for pixel
      surface[pixelIdx] = computePixelValue(which, travelTimes)

      // compute access values
      computeAccessValues(x, y, query, grid, travelTimes, access)
    }
  }

  return {
    surface,
    access,
    nMinutes
  }
}

/**
 * Where is the transit portion of the origin data there are a certain number of pixels in each direction aroudn the origin with times in them. read the radius, multiply by two to get diameter, add one because there is a pixel in the center, square to get number of pixels, add one to skip the first value which gives radius, and or with to convert to 32-bit int.
 *
 * @param {Number} radius
 * @return {Number}
 */

export function getTransitOffset (radius) {
  return (Math.pow(radius * 2 + 1, 2) + 1) | 0
}

/**
 * Get the pixel value
 *
 * @param {String} which
 * @param {Uint8Array} travelTimes
 * @return {Number} pixelValue
 */

export function computePixelValue (which, travelTimes) {
  switch (which) {
    case 'BEST_CASE':
      return computeBestPixelValue(travelTimes)
    case 'AVERAGE':
      return computeAveragePixelValue(travelTimes)
    case 'WORST_CASE':
      return computeWorstPixelValue(travelTimes)
  }
}

/**
 * Compute best pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeBestPixelValue (travelTimes) {
  let pixel = 255
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.min(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute average pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeAveragePixelValue (travelTimes) {
  let sum = 0
  let count = 0

  for (let i = 0; i < travelTimes.length; i++) {
    if (travelTimes[i] !== 255) {
      sum += travelTimes[i]
      count++
    }
  }

  // coerce to int
  if (count > travelTimes.length / 2) return (sum / count) | 0
  else return 255
}

/**
 * Compute worst pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeWorstPixelValue (travelTimes) {
  let pixel = 0
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.max(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute access values for x, y
 *
 * @param {Number} x
 * @param {Number} y
 * @param {Object} query
 * @param {Object} grid
 * @param {Uint8Array} travelTimes
 * @param {Float64Array} accessPerMinute
 */

export function computeAccessValues (x, y, query, grid, travelTimes, access) {
  // get value of this pixel from grid
  let gridx = x + query.west - grid.west
  let gridy = y + query.north - grid.north

  // if condition below fails we're off the grid, value is zero, don't bother with calculations
  if (gridx >= 0 && gridx < grid.width && gridy >= 0 && gridy < grid.height) {
    let val = grid.data[gridy * grid.width + gridx]

    for (let minute = 0; minute < travelTimes.length; minute++) {
      let travelTime = travelTimes[minute]

      if (travelTime !== 255) {
        // put this in all of the correct cutoff categories for this minute
        for (let cutoff = 119; cutoff >= travelTime; cutoff--) {
          access[cutoff * travelTimes.length + minute] += val
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>var http = require('http');
var router = require('node-simple-router')({list_dir: false});
var url = require('url') ;

var Twit = require('twit')

var T = new Twit({
    consumer_key:         process.env.TWITTER_CONSUMER_KEY
  , consumer_secret:      process.env.TWITTER_CONSUMER_SECRET
  , access_token:         process.env.TWITTER_ACCESS_TOKEN
  , access_token_secret:  process.env.TWITTER_ACCESS_TOKEN_SECRET
})

router.get("/hello", function(request, response) {response.end("Hello, World!");});
router.get("/sinceId", function(request, response) {
  var queryObject = url.parse(request.url,true).query;

  var result = 0;
  var startId = queryObject['since'];
  var tag = queryObject['tag'];

  if(typeof startId === 'undefined') {
    startId = 0;
  }

  if(typeof tag !== 'undefined') {
    var searchOptions = {
      q: tag,
      since_id: startId,
      count: 100,
      result_type: 'recent',
      include_entities: 0
    };

    T.get('search/tweets', searchOptions, function(err, data, res) {
      var result = {
        length: data['statuses'].length,
         maxId: data['search_metadata']['max_id']
      }
      response.end(JSON.stringify(result));
      // console.log(data)
    });
  } else {
    var result = {
      length: 0,
       maxId: 0,
       error: 'no tag'
    }
    response.end(JSON.stringify(result));
  }
});

function getOAuth(done){
  var OAuth = require('oauth');
  var OAuth2 = OAuth.OAuth2;
  var twitterConsumerKey = 'your key';
  var twitterConsumerSecret = 'your secret';
  var oauth2 = new OAuth2(server.config.keys.twitter.consumerKey,
       twitterConsumerSecret,
       'https://api.twitter.com/',
       null,
       'oauth2/token',
       null);
  oauth2.getOAuthAccessToken(
       '',
       {'grant_type':'client_credentials'},
       function (e, access_token, refresh_token, results){
       console.log('bearer: ',access_token);
       done();
  });
};

http.createServer(router).listen(process.env.PORT || 1187);
<commit_msg>changed output to simpler format<commit_after>var http = require('http');
var router = require('node-simple-router')({list_dir: false});
var url = require('url') ;

var Twit = require('twit')

var T = new Twit({
    consumer_key:         process.env.TWITTER_CONSUMER_KEY
  , consumer_secret:      process.env.TWITTER_CONSUMER_SECRET
  , access_token:         process.env.TWITTER_ACCESS_TOKEN
  , access_token_secret:  process.env.TWITTER_ACCESS_TOKEN_SECRET
})

router.get("/hello", function(request, response) {response.end("Hello, World!");});
router.get("/sinceId", function(request, response) {
  var queryObject = url.parse(request.url,true).query;

  var result = 0;
  var startId = queryObject['since'];
  var tag = queryObject['tag'];

  if(typeof startId === 'undefined') {
    startId = 0;
  }

  if(typeof tag !== 'undefined') {
    var searchOptions = {
      q: tag,
      since_id: startId,
      count: 100,
      result_type: 'recent',
      include_entities: 0
    };

    T.get('search/tweets', searchOptions, function(err, data, res) {
      var result = {
        length: data['statuses'].length,
         maxId: data['search_metadata']['max_id']
      }
      response.end(JSON.stringify(result));
      // console.log(data)
    });
  } else {
    var result = {
      length: 0,
       maxId: 0,
       error: 'no tag'
    }
    // response.end(JSON.stringify(result));
    response.end(result.length + " ; " + result.maxId);
  }
});

function getOAuth(done){
  var OAuth = require('oauth');
  var OAuth2 = OAuth.OAuth2;
  var twitterConsumerKey = 'your key';
  var twitterConsumerSecret = 'your secret';
  var oauth2 = new OAuth2(server.config.keys.twitter.consumerKey,
       twitterConsumerSecret,
       'https://api.twitter.com/',
       null,
       'oauth2/token',
       null);
  oauth2.getOAuthAccessToken(
       '',
       {'grant_type':'client_credentials'},
       function (e, access_token, refresh_token, results){
       console.log('bearer: ',access_token);
       done();
  });
};

http.createServer(router).listen(process.env.PORT || 1187);
<|endoftext|>


<commit_before>'use strict'

var remix = require('ethereum-remix')

/**
 * Manage remix and source highlighting
 */
function Debugger (id, appAPI, executionContextEvent, editorEvent) {
  this.el = document.querySelector(id)
  this.debugger = new remix.ui.Debugger()
  this.sourceMappingDecoder = new remix.util.SourceMappingDecoder()
  this.el.appendChild(this.debugger.render())
  this.appAPI = appAPI
  this.markers = {}
  this.breakPointManager = new remix.code.BreakpointManager(this.debugger, (sourceLocation) => {
    return this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
  })

  this.debugger.setBreakpointManager(this.breakPointManager)
  this.breakPointManager.event.register('breakpointHit', (sourceLocation) => {
    this.editor.setBreakpoint(this.touchedBreakpoint, 'breakpointUntouched')
    var lineColumnPos = this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
    this.editor.setBreakpoint(lineColumnPos.start.line, 'breakpointTouched')
    var self = this
    setTimeout(function () {
      self.editor.setBreakpoint(lineColumnPos.start.line, 'breakpointUntouched')
    }, 5000)
  })

  function convertSourceLocation (self, fileName, row) {
    var source = {}
    for (let file in self.compiler.lastCompilationResult.data.sourceList) {
      if (self.compiler.lastCompilationResult.data.sourceList[file] === fileName) {
        source.file = file
        break
      }
    }
    source.start = self.offsetToLineColumnConverter.lineBreakPositionsByContent[source.file][row > 0 ? row - 1 : 0]
    source.end = self.offsetToLineColumnConverter.lineBreakPositionsByContent[source.file][row]
    source.row = row
    return source
  }

  editorEvent.register('breakpointCleared', (fileName, row) => {
    this.breakPointManager.remove(convertSourceLocation(this, fileName, row))
  })

  editorEvent.register('breakpointAdded', (fileName, row) => {
    this.breakPointManager.add(convertSourceLocation(this, fileName, row))
  })

  var self = this
  executionContextEvent.register('contextChanged', this, function (context) {
    self.switchProvider(context)
  })

  this.debugger.event.register('traceUnloaded', this, function () {
    self.appAPI.currentSourceLocation(null)
  })

  // unload if a file has changed (but not if tabs were switched)
  editorEvent.register('contentChanged', function () {
    self.debugger.unLoad()
    self.removeMarkers()
  })

  // register selected code item, highlight the corresponding source location
  this.debugger.codeManager.event.register('changed', this, function (code, address, index) {
    if (self.appAPI.lastCompilationResult()) {
      this.debugger.callTree.sourceLocationTracker.getSourceLocationFromInstructionIndex(address, index, self.appAPI.lastCompilationResult().data.contracts, function (error, rawLocation) {
        if (!error) {
          var lineColumnPos = self.appAPI.offsetToLineColumn(rawLocation, rawLocation.file)
          self.appAPI.currentSourceLocation(lineColumnPos, rawLocation)
        } else {
          self.appAPI.currentSourceLocation(null)
        }
      })
    }
  })
}

/**
 * Start debugging using Remix
 *
 * @param {String} txHash    - hash of the transaction
 */
Debugger.prototype.debug = function (txHash) {
  var self = this
  this.debugger.web3().eth.getTransaction(txHash, function (error, tx) {
    if (!error) {
      self.debugger.setCompilationResult(self.appAPI.lastCompilationResult().data)
      self.debugger.debug(tx)
    }
  })
}

Debugger.prototype.switchFile = function (rawLocation) {
  var name = this.editor.getCacheFile() // current opened tab
  var source = this.compiler.lastCompilationResult.data.sourceList[rawLocation.file] // auto switch to that tab
  if (name !== source) {
    this.switchToFile(source) // command the app to swicth to the next file
  }
}

/**
 * add a new web3 provider to remix
 *
 * @param {String} type - type/name of the provider to add
 * @param {Object} obj  - provider
 */
Debugger.prototype.addProvider = function (type, obj) {
  this.debugger.addProvider(type, obj)
}

/**
 * switch the provider
 *
 * @param {String} type - type/name of the provider to use
 */
Debugger.prototype.switchProvider = function (type) {
  this.debugger.switchProvider(type)
}

/**
 * get the current provider
 */
Debugger.prototype.web3 = function (type) {
  return this.debugger.web3()
}

module.exports = Debugger
<commit_msg>remove source location from breakpoint (keep only row number)<commit_after>'use strict'

var remix = require('ethereum-remix')

/**
 * Manage remix and source highlighting
 */
function Debugger (id, appAPI, executionContextEvent, editorEvent) {
  this.el = document.querySelector(id)
  this.debugger = new remix.ui.Debugger()
  this.sourceMappingDecoder = new remix.util.SourceMappingDecoder()
  this.el.appendChild(this.debugger.render())
  this.appAPI = appAPI
  this.markers = {}
  this.breakPointManager = new remix.code.BreakpointManager(this.debugger, (sourceLocation) => {
    return this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
  })

  this.debugger.setBreakpointManager(this.breakPointManager)
  this.breakPointManager.event.register('breakpointHit', (sourceLocation) => {
    this.editor.setBreakpoint(this.touchedBreakpoint, 'breakpointUntouched')
    var lineColumnPos = this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
    this.editor.setBreakpoint(lineColumnPos.start.line, 'breakpointTouched')
    var self = this
    setTimeout(function () {
      self.editor.setBreakpoint(lineColumnPos.start.line, 'breakpointUntouched')
    }, 5000)
  })

  function convertSourceLocation (self, fileName, row) {
    var source = {}
    for (let file in self.compiler.lastCompilationResult.data.sourceList) {
      if (self.compiler.lastCompilationResult.data.sourceList[file] === fileName) {
        source.file = file
        break
      }
    }
    source.row = row
    return source
  }

  editorEvent.register('breakpointCleared', (fileName, row) => {
    this.breakPointManager.remove(convertSourceLocation(this, fileName, row))
  })

  editorEvent.register('breakpointAdded', (fileName, row) => {
    this.breakPointManager.add(convertSourceLocation(this, fileName, row))
  })

  var self = this
  executionContextEvent.register('contextChanged', this, function (context) {
    self.switchProvider(context)
  })

  this.debugger.event.register('traceUnloaded', this, function () {
    self.appAPI.currentSourceLocation(null)
  })

  // unload if a file has changed (but not if tabs were switched)
  editorEvent.register('contentChanged', function () {
    self.debugger.unLoad()
    self.removeMarkers()
  })

  // register selected code item, highlight the corresponding source location
  this.debugger.codeManager.event.register('changed', this, function (code, address, index) {
    if (self.appAPI.lastCompilationResult()) {
      this.debugger.callTree.sourceLocationTracker.getSourceLocationFromInstructionIndex(address, index, self.appAPI.lastCompilationResult().data.contracts, function (error, rawLocation) {
        if (!error) {
          var lineColumnPos = self.appAPI.offsetToLineColumn(rawLocation, rawLocation.file)
          self.appAPI.currentSourceLocation(lineColumnPos, rawLocation)
        } else {
          self.appAPI.currentSourceLocation(null)
        }
      })
    }
  })
}

/**
 * Start debugging using Remix
 *
 * @param {String} txHash    - hash of the transaction
 */
Debugger.prototype.debug = function (txHash) {
  var self = this
  this.debugger.web3().eth.getTransaction(txHash, function (error, tx) {
    if (!error) {
      self.debugger.setCompilationResult(self.appAPI.lastCompilationResult().data)
      self.debugger.debug(tx)
    }
  })
}

Debugger.prototype.switchFile = function (rawLocation) {
  var name = this.editor.getCacheFile() // current opened tab
  var source = this.compiler.lastCompilationResult.data.sourceList[rawLocation.file] // auto switch to that tab
  if (name !== source) {
    this.switchToFile(source) // command the app to swicth to the next file
  }
}

/**
 * add a new web3 provider to remix
 *
 * @param {String} type - type/name of the provider to add
 * @param {Object} obj  - provider
 */
Debugger.prototype.addProvider = function (type, obj) {
  this.debugger.addProvider(type, obj)
}

/**
 * switch the provider
 *
 * @param {String} type - type/name of the provider to use
 */
Debugger.prototype.switchProvider = function (type) {
  this.debugger.switchProvider(type)
}

/**
 * get the current provider
 */
Debugger.prototype.web3 = function (type) {
  return this.debugger.web3()
}

module.exports = Debugger
<|endoftext|>