<commit_before>"use strict"

var bits = require("bit-twiddle")
var pool = require("typedarray-pool")
var ndarray = require("ndarray")
var ops = require("ndarray-ops")
var fft = require("ndarray-fft")

function zero(arr, lo, hi) {
  for(var i=lo; i<hi; ++i) {
    arr[i] = 0.0
  }
}

function square(x, y) {
  var n = x.length, n2 = Math.ceil(0.5*n)|0
  x[0] = y[0] = 0.0
  for(var i=1; i<n2; ++i) {
    var a = x[i], b = y[i]
    x[n-i] = x[i] = a*a + b*b
    y[n-i] = y[i] = 0.0
  }
}

function findPeriod(x, lo, hi, threshold) {
  for(var i=lo; i<hi; ++i) {
    if(x[i] > threshold) {
      var best = x[i]
      var r = i
      for(var j=i; j < hi && x[j] > threshold; ++j) {
        if(x[j] > best) {
          best = x[j]
          r = j
        }
      }
      var y0 = x[r-1], y1 = x[r], y2 = x[r+1]
      var denom = y2 - y1 + y0
      if(Math.abs(denom) < 1e-6) {
        return r
      }
      var numer = y0 - y2
      return r + 0.5 * numer / denom
    }
  }
  return 0
}

function detectPitch(signal, options) {
  options = options || {}
  var xs
  if(signal.shape) {
    xs = signal.shape[0]
  } else {
    xs = signal.length
  }

  var i, j, k
  var n = bits.nextPow2(2*xs)
  var re_arr = pool.mallocFloat(n)
  var im_arr = pool.mallocFloat(n)
  var X = ndarray.ctor(re_arr, [n], [1], 0)
  var Y = ndarray.ctor(im_arr, [n], [1], 0)

  //Initialize array depending on if it is a typed array
  if(signal.shape) {
    X.shape[0] = xs
    ops.assign(X, signal)
    X.shape[0] = n
  } else {
    re_arr.set(signal)
  }
  zero(re_arr, xs, n)
  zero(im_arr, 0, n)

  //Autocorrelate
  fft(1, X, Y)
  square(re_arr, im_arr)
  fft(-1, X, Y)

  //Detect pitch
  var threshold = options.threshold || 0.9
  var period = findPeriod(
          re_arr,
          options.start_bin || 8,
          xs>>>1,
          re_arr[0] * threshold)

  //Free temporary arrays
  pool.freeFloat(re_arr)
  pool.freeFloat(im_arr)

  return period
}
module.exports = detectPitch<commit_msg>on second thought, 16 bins is fine<commit_after>"use strict"

var bits = require("bit-twiddle")
var pool = require("typedarray-pool")
var ndarray = require("ndarray")
var ops = require("ndarray-ops")
var fft = require("ndarray-fft")

function zero(arr, lo, hi) {
  for(var i=lo; i<hi; ++i) {
    arr[i] = 0.0
  }
}

function square(x, y) {
  var n = x.length, n2 = Math.ceil(0.5*n)|0
  x[0] = y[0] = 0.0
  for(var i=1; i<n2; ++i) {
    var a = x[i], b = y[i]
    x[n-i] = x[i] = a*a + b*b
    y[n-i] = y[i] = 0.0
  }
}

function findPeriod(x, lo, hi, threshold) {
  for(var i=lo; i<hi; ++i) {
    if(x[i] > threshold) {
      var best = x[i]
      var r = i
      for(var j=i; j < hi && x[j] > threshold; ++j) {
        if(x[j] > best) {
          best = x[j]
          r = j
        }
      }
      var y0 = x[r-1], y1 = x[r], y2 = x[r+1]
      var denom = y2 - y1 + y0
      if(Math.abs(denom) < 1e-6) {
        return r
      }
      var numer = y0 - y2
      return r + 0.5 * numer / denom
    }
  }
  return 0
}

function detectPitch(signal, options) {
  options = options || {}
  var xs
  if(signal.shape) {
    xs = signal.shape[0]
  } else {
    xs = signal.length
  }

  var i, j, k
  var n = bits.nextPow2(2*xs)
  var re_arr = pool.mallocFloat(n)
  var im_arr = pool.mallocFloat(n)
  var X = ndarray.ctor(re_arr, [n], [1], 0)
  var Y = ndarray.ctor(im_arr, [n], [1], 0)

  //Initialize array depending on if it is a typed array
  if(signal.shape) {
    X.shape[0] = xs
    ops.assign(X, signal)
    X.shape[0] = n
  } else {
    re_arr.set(signal)
  }
  zero(re_arr, xs, n)
  zero(im_arr, 0, n)

  //Autocorrelate
  fft(1, X, Y)
  square(re_arr, im_arr)
  fft(-1, X, Y)

  //Detect pitch
  var threshold = options.threshold || 0.9
  var period = findPeriod(
          re_arr,
          options.start_bin || 16,
          xs>>>1,
          re_arr[0] * threshold)

  //Free temporary arrays
  pool.freeFloat(re_arr)
  pool.freeFloat(im_arr)

  return period
}
module.exports = detectPitch<|endoftext|>


<commit_before>/*
Name:           piwik
Description:    Access a Piwik API or track hits with node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-piwik
Feedback:       https://github.com/fvdm/nodejs-piwik/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-piwik/raw/develop/UNLICENSE)
*/

var urltool = require ('url');
var querystring = require ('querystring');
var http = require ('httpreq');
var app = {settings: {}};

var defaults = {
  timeout: 5000
};

// SETUP basics
app.setup = function (baseURL, token, timeout) {
  app.settings.baseURL = baseURL.replace (/\/(index\.php)?([#\?].*)?$/, '/');
  var url = urltool.parse (baseURL, true);

  // token in baseURL?
  app.settings.token = url.query && url.query.token_auth || null;

  // override with custom token, and set timeout
  if (typeof token === 'number') {
    app.settings.timeout = token;
  } else if (token) {
    app.settings.token = token;
    app.settings.timeout = timeout || defaults.timeout;
  }

  return app;
};

// API call
app.api = function (vars, cb) {
  vars = typeof vars === 'object' ? vars : {};
  vars.module = 'API';
  vars.format = 'JSON';
  vars.token_auth = app.settings.token;
  talk ({ method: 'GET', query: vars, callback: cb || null });
  return app;
};

// Track
app.track = function (vars, cb) {
  var bulk = {requests: []};
  var i, k, val, keys;
  if (app.settings.token) { bulk.token_auth = app.settings.token; }

  if (vars instanceof Array && vars [0] instanceof Object) {
    // array with objects
    for (i = 0; i < vars.length; i++) {
      keys = Object.keys (vars [i]);
      for (k = 0; k < keys.length; k++) {
        val = vars [i] [keys [k]];
        vars [i] [keys [k]] = typeof val === 'object' ? JSON.stringify (val) : val;
      }
      vars [i] .rec = 1;
      vars [i] .apiv = 1;
      vars [i] = '?'+ querystring.stringify (vars [i]);
      bulk.requests.push (vars [i]);
      delete vars [i];
    }
  } else if (vars instanceof Object) {
    // object
    keys = Object.keys (vars);
    for (i = 0; i < keys.length; i++) {
      val = vars [keys [i]];
      vars [keys [i]] = typeof val === 'object' ? JSON.stringify (val) : val;
    }
    vars.rec = 1;
    vars.apiv = 1;
    bulk.requests.push ('?'+ querystring.stringify (vars));
  }

  talk ({
    method: 'POST',
    path: 'piwik.php',
    body: JSON.stringify (bulk),
    callback: function (err, data) {
      if (err && cb) { return cb (err); }
      if (data.status === 'success') {
        cb && cb (null, data);
      } else {
        var error = new Error ('track failed');
        error.data = data;
        cb && cb (error);
      }
    }
  });

  return app;
};

// Spammers
app.loadSpammers = function (cb) {
  var options = {
    timeout: parseInt (app.settings.timeout || defaults.timeout)
  };
  http.get (
    'https://github.com/piwik/referrer-spam-blacklist/raw/master/spammers.txt',
    options,
    function (err, res) {
      if (err && cb) { return cb (err); }
      var data = res.body.trim () .split ('\n');
      var i, line;
      for (i = 0; i < data.length; i++) {
        line = data [i] .trim ();
        if (line === '') {
          delete data [i];
        }
      }
      data = data.sort ();
      cb && cb (null, data);
    }
  );

  return app;
};

// HTTP GET
function talk (props, cb) {
  // build request
  if (props.query instanceof Object) {
    var key;
    for (key in props.query) {
      if (typeof props.query [key] === 'object') {
        props.query [key] = JSON.stringify (props.query [key]);
      }
    }
  }

  var options = {
    url: app.settings.baseURL + (props.path || ''),
    method: props.method || 'GET',
    headers: {},
    timeout: parseInt (props.timeout || app.settings.timeout || defaults.timeout, 10)
  };

  if (props.query) {
    options.parameters = props.query;
  } else if (props.body) {
    options.body = props.body;
    options.headers ['Content-Type'] = 'application/json';
    options.headers ['Content-Length'] = options.body.length;
  }

  // send request
  http.doRequest (options, function (err, res) {
    var data = res && res.body || null;
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
    }

    try {
      data = JSON.parse (data);
      if (data.result && data.result === 'error') {
        error = new Error ('api error');
        error.text = data.message || null;
      }
    } catch (e) {
      error = new Error ('response invalid');
      error.error = e;
    }

    if (res && res.statusCode && res.statusCode >= 300) {
      error = new Error ('http error');
      error.code = res.statusCode;
      error.body = data;
    }

    props.callback && props.callback (error, !error && data);
  });
}

// module
module.exports = app;
<commit_msg>Fixed lint vars-on-top for options var<commit_after>/*
Name:           piwik
Description:    Access a Piwik API or track hits with node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-piwik
Feedback:       https://github.com/fvdm/nodejs-piwik/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-piwik/raw/develop/UNLICENSE)
*/

var urltool = require ('url');
var querystring = require ('querystring');
var http = require ('httpreq');
var app = {settings: {}};

var defaults = {
  timeout: 5000
};

// SETUP basics
app.setup = function (baseURL, token, timeout) {
  app.settings.baseURL = baseURL.replace (/\/(index\.php)?([#\?].*)?$/, '/');
  var url = urltool.parse (baseURL, true);

  // token in baseURL?
  app.settings.token = url.query && url.query.token_auth || null;

  // override with custom token, and set timeout
  if (typeof token === 'number') {
    app.settings.timeout = token;
  } else if (token) {
    app.settings.token = token;
    app.settings.timeout = timeout || defaults.timeout;
  }

  return app;
};

// API call
app.api = function (vars, cb) {
  vars = typeof vars === 'object' ? vars : {};
  vars.module = 'API';
  vars.format = 'JSON';
  vars.token_auth = app.settings.token;
  talk ({ method: 'GET', query: vars, callback: cb || null });
  return app;
};

// Track
app.track = function (vars, cb) {
  var bulk = {requests: []};
  var i, k, val, keys;
  if (app.settings.token) { bulk.token_auth = app.settings.token; }

  if (vars instanceof Array && vars [0] instanceof Object) {
    // array with objects
    for (i = 0; i < vars.length; i++) {
      keys = Object.keys (vars [i]);
      for (k = 0; k < keys.length; k++) {
        val = vars [i] [keys [k]];
        vars [i] [keys [k]] = typeof val === 'object' ? JSON.stringify (val) : val;
      }
      vars [i] .rec = 1;
      vars [i] .apiv = 1;
      vars [i] = '?'+ querystring.stringify (vars [i]);
      bulk.requests.push (vars [i]);
      delete vars [i];
    }
  } else if (vars instanceof Object) {
    // object
    keys = Object.keys (vars);
    for (i = 0; i < keys.length; i++) {
      val = vars [keys [i]];
      vars [keys [i]] = typeof val === 'object' ? JSON.stringify (val) : val;
    }
    vars.rec = 1;
    vars.apiv = 1;
    bulk.requests.push ('?'+ querystring.stringify (vars));
  }

  talk ({
    method: 'POST',
    path: 'piwik.php',
    body: JSON.stringify (bulk),
    callback: function (err, data) {
      if (err && cb) { return cb (err); }
      if (data.status === 'success') {
        cb && cb (null, data);
      } else {
        var error = new Error ('track failed');
        error.data = data;
        cb && cb (error);
      }
    }
  });

  return app;
};

// Spammers
app.loadSpammers = function (cb) {
  var options = {
    timeout: parseInt (app.settings.timeout || defaults.timeout)
  };
  http.get (
    'https://github.com/piwik/referrer-spam-blacklist/raw/master/spammers.txt',
    options,
    function (err, res) {
      if (err && cb) { return cb (err); }
      var data = res.body.trim () .split ('\n');
      var i, line;
      for (i = 0; i < data.length; i++) {
        line = data [i] .trim ();
        if (line === '') {
          delete data [i];
        }
      }
      data = data.sort ();
      cb && cb (null, data);
    }
  );

  return app;
};

// HTTP GET
function talk (props, cb) {
  var options = {
    url: app.settings.baseURL + (props.path || ''),
    method: props.method || 'GET',
    headers: {},
    timeout: parseInt (props.timeout || app.settings.timeout || defaults.timeout, 10)
  };

  // build request
  if (props.query instanceof Object) {
    var key;
    for (key in props.query) {
      if (typeof props.query [key] === 'object') {
        props.query [key] = JSON.stringify (props.query [key]);
      }
    }
  }

  if (props.query) {
    options.parameters = props.query;
  } else if (props.body) {
    options.body = props.body;
    options.headers ['Content-Type'] = 'application/json';
    options.headers ['Content-Length'] = options.body.length;
  }

  // send request
  http.doRequest (options, function (err, res) {
    var data = res && res.body || null;
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
    }

    try {
      data = JSON.parse (data);
      if (data.result && data.result === 'error') {
        error = new Error ('api error');
        error.text = data.message || null;
      }
    } catch (e) {
      error = new Error ('response invalid');
      error.error = e;
    }

    if (res && res.statusCode && res.statusCode >= 300) {
      error = new Error ('http error');
      error.code = res.statusCode;
      error.body = data;
    }

    props.callback && props.callback (error, !error && data);
  });
}

// module
module.exports = app;
<|endoftext|>


<commit_before>//Initialize a new map object inside of the #map div
function initMap(){
  console.log('initMap');
  window.map = new mapboxgl.Map({
    container: 'map', //HTML element to initialize the map in (or element id as string)
    zoom: 3.15,
    // minZoom: 1, //Default of 0 (world)
    // maxZoom: 12, //Default of 20 (local)
    center: [-80.7129,40.0902], //LatLng array in decimal degrees
    style: 'mapbox://styles/mapbox/outdoors-v9' //Basemap style; can be a preset from mapbox or a user defined style
  });

  //Once the map has loaded
  map.on('load', function () {
    console.log('load data');
    //Create new GeoJSON layer 'myJSON'
    map.addSource('myJSON', {
      'type': 'geojson',
      'data': myJSON
    });

    //Add loaded data and style
    map.addLayer({
      'id': 'myJSON',
      'type': 'fill',
      'source': 'myJSON',
      // 'source-layer': 'myJSON',
      'layout': { visibility: 'visible'},
      'paint': {
        'fill-outline-color': '#FFF',
        'fill-color': {
          property: 'aPayment',
          stops: [
                  [8100, '#ffffb2'],
                  [10800, '#fed976'],
                  [13500, '#feb24c'],
                  [16200, '#fd8d3c'],
                  [18900, '#fc4e2a'],
                  [21600, '#e31a1c'],
                  [24300, '#b10026'],
          ]
        },
        'fill-opacity':  1}
    });
  });
}

function setPaint(userSalary){
  document.getElementById('mapHTML').contentWindow.map.setPaintProperty('myJSON', 'fill-color', colorMap(userSalary, colorArray));
}

//Change map based on user input
//map.setPaintProperty('myJSON', 'fill-color', colorMap(60000, colorArray));
<commit_msg>Changed color map scheme<commit_after>//Initialize a new map object inside of the #map div
function initMap(){
  console.log('initMap');
  window.map = new mapboxgl.Map({
    container: 'map', //HTML element to initialize the map in (or element id as string)
    zoom: 3.15,
    // minZoom: 1, //Default of 0 (world)
    // maxZoom: 12, //Default of 20 (local)
    center: [-80.7129,40.0902], //LatLng array in decimal degrees
    style: 'mapbox://styles/mapbox/outdoors-v9' //Basemap style; can be a preset from mapbox or a user defined style
  });

  //Once the map has loaded
  map.on('load', function () {
    console.log('load data');
    //Create new GeoJSON layer 'myJSON'
    map.addSource('myJSON', {
      'type': 'geojson',
      'data': myJSON
    });

    //Add loaded data and style
    map.addLayer({
      'id': 'myJSON',
      'type': 'fill',
      'source': 'myJSON',
      // 'source-layer': 'myJSON',
      'layout': { visibility: 'visible'},
      'paint': {
        'fill-outline-color': '#FFF',
        'fill-color': {
          property: 'aPayment',
          stops: [
            // Greens ['#edf8e9','#bae4b3','#74c476','#238b45']
            // Reds ['#fee5d9','#fcae91','#fb6a4a','#cb181d']
                  [0, '#238b45'], //0-15% affordable
                  [8100, '#74c476'], //16-20% affordable
                  [10800, '#bae4b3'], //21-25% affordable
                  [13500, '#edf8e9'], //26-30% affordable
                  [16200, '#fee5d9'], //31-35% unaffordable
                  [18900, '#fcae91'], //36-40% unaffordable
                  [21600, '#fb6a4a'], //41-45% unaffordable
                  [24300, '#cb181d'], //>45% unaffordable
          ]
        },
        'fill-opacity':  1}
    });
  });
}

function setPaint(userSalary){
  document.getElementById('mapHTML').contentWindow.map.setPaintProperty('myJSON', 'fill-color', colorMap(userSalary, colorArray));
}

//Change map based on user input
//map.setPaintProperty('myJSON', 'fill-color', colorMap(60000, colorArray));
<|endoftext|>


<commit_before>process.env.NODE_ENV = 'development'

var path = require('path')

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/keithmorris/node-dotenv-extended
require('dotenv-extended').load({
  path: path.join(__dirname, '..', '.env'),
  defaults: path.join(__dirname, '..', '.env.defaults'),
  schema: path.join(__dirname, '..', '.env.schema')
})

var chalk = require('chalk')
var webpack = require('webpack')
var WebpackDevServer = require('webpack-dev-server')
var historyApiFallback = require('connect-history-api-fallback')
var httpProxyMiddleware = require('http-proxy-middleware')
var clearConsole = require('react-dev-utils/clearConsole')
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles')
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages')
var openBrowser = require('react-dev-utils/openBrowser')
var pathExists = require('path-exists')
var config = require('../config/webpack.config.dev')
var paths = require('../config/paths')

var useYarn = pathExists.sync(paths.yarnLockFile)
var cli = useYarn ? 'yarn' : 'npm'
var isInteractive = false// process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1)
}

// Tools like Cloud9 rely on this.
var DEFAULT_PORT = process.env.WEB_PORT || 3000
var compiler
var handleCompile

function setupCompiler (host, port, protocol) {
  // "Compiler" is a low-level interface to Webpack.
  // It lets us listen to some events and provide our own custom messages.
  compiler = webpack(config, handleCompile)

  // "invalid" event fires when you have changed a file, and Webpack is
  // recompiling a bundle. WebpackDevServer takes care to pause serving the
  // bundle, so if you refresh, it'll wait instead of serving the old one.
  // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
  compiler.plugin('invalid', function () {
    if (isInteractive) {
      clearConsole()
    }
    console.log('Compiling...')
  })

  var isFirstCompile = true

  // "done" event fires when Webpack has finished recompiling the bundle.
  // Whether or not you have warnings or errors, you will get this event.
  compiler.plugin('done', function (stats) {
    if (isInteractive) {
      clearConsole()
    }

    // We have switched off the default Webpack output in WebpackDevServer
    // options so we are going to "massage" the warnings and errors and present
    // them in a readable focused way.
    var messages = formatWebpackMessages(stats.toJson({}, true))
    var isSuccessful = !messages.errors.length && !messages.warnings.length
    var showInstructions = isSuccessful && (isInteractive || isFirstCompile)

    if (isSuccessful) {
      console.log(chalk.green('Compiled successfully!'))
    }

    if (showInstructions) {
      console.log()
      console.log('The app is running at:')
      console.log()
      console.log('  ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'))
      console.log()
      console.log('Note that the development build is not optimized.')
      console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.')
      console.log()
      isFirstCompile = false
    }

    // If errors exist, only show errors.
    if (messages.errors.length) {
      console.log(chalk.red('Failed to compile.'))
      console.log()
      messages.errors.forEach(message => {
        console.log(message)
        console.log()
      })
      return
    }

    // Show warnings if no errors were found.
    if (messages.warnings.length) {
      console.log(chalk.yellow('Compiled with warnings.'))
      console.log()
      messages.warnings.forEach(message => {
        console.log(message)
        console.log()
      })
      // Teach some ESLint tricks.
      console.log('You may use special comments to disable some warnings.')
      console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.')
      console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.')
    }
  })
}

// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError (proxy) {
  return function (err, req, res) {
    var host = req.headers && req.headers.host
    console.log(
      chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
      ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
    )
    console.log(
      'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
      chalk.cyan(err.code) + ').'
    )
    console.log()

    // And immediately send the proper error response to the client.
    // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
    if (res.writeHead && !res.headersSent) {
      res.writeHead(500)
    }
    res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
      host + ' to ' + proxy + ' (' + err.code + ').'
    )
  }
}

function addMiddleware (devServer) {
  // `proxy` lets you to specify a fallback server during development.
  // Every unrecognized request will be forwarded to it.
  var proxy = require(paths.appPackageJson).proxy
  devServer.use(historyApiFallback({
    // Paths with dots should still use the history fallback.
    // See https://github.com/facebookincubator/create-react-app/issues/387.
    disableDotRule: true,
    // For single page apps, we generally want to fallback to /index.html.
    // However we also want to respect `proxy` for API calls.
    // So if `proxy` is specified, we need to decide which fallback to use.
    // We use a heuristic: if request `accept`s text/html, we pick /index.html.
    // Modern browsers include text/html into `accept` header when navigating.
    // However API calls like `fetch()` won’t generally accept text/html.
    // If this heuristic doesn’t work well for you, don’t use `proxy`.
    htmlAcceptHeaders: proxy
      ? ['text/html']
      : ['text/html', '*/*']
  }))
  if (proxy) {
    if (typeof proxy !== 'string') {
      console.log(chalk.red('When specified, "proxy" in package.json must be a string.'))
      console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'))
      console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'))
      process.exit(1)
    }

    // Otherwise, if proxy is specified, we will let it handle any request.
    // There are a few exceptions which we won't send to the proxy:
    // - /index.html (served as HTML5 history API fallback)
    // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
    // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
    // Tip: use https://jex.im/regulex/ to visualize the regex
    var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/

    // Pass the scope regex both to Express and to the middleware for proxying
    // of both HTTP and WebSockets to work without false positives.
    var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
      target: proxy,
      logLevel: 'silent',
      onProxyReq: function (proxyReq, req, res) {
        // Browers may send Origin headers even with same-origin
        // requests. To prevent CORS issues, we have to change
        // the Origin to match the target URL.
        if (proxyReq.getHeader('origin')) {
          proxyReq.setHeader('origin', proxy)
        }
      },
      onError: onProxyError(proxy),
      secure: false,
      changeOrigin: true,
      ws: true
    })
    devServer.use(mayProxy, hpm)

    // Listen for the websocket 'upgrade' event and upgrade the connection.
    // If this is not done, httpProxyMiddleware will not try to upgrade until
    // an initial plain HTTP request is made.
    devServer.listeningApp.on('upgrade', hpm.upgrade)
  }

  // Finally, by now we have certainly resolved the URL.
  // It may be /index.html, so let the dev server try serving it again.
  devServer.use(devServer.middleware)
}

function runDevServer (host, port, protocol) {
  var devServer = new WebpackDevServer(compiler, {
    // Enable gzip compression of generated files.
    compress: true,
    // Silence WebpackDevServer's own logs since they're generally not useful.
    // It will still show compile warnings and errors with this setting.
    clientLogLevel: 'none',
    // By default WebpackDevServer serves physical files from current directory
    // in addition to all the virtual build products that it serves from memory.
    // This is confusing because those files won’t automatically be available in
    // production build folder unless we copy them. However, copying the whole
    // project directory is dangerous because we may expose sensitive files.
    // Instead, we establish a convention that only files in `public` directory
    // get served. Our build script will copy `public` into the `build` folder.
    // In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
    // Note that we only recommend to use `public` folder as an escape hatch
    // for files like `favicon.ico`, `manifest.json`, and libraries that are
    // for some reason broken when imported through Webpack. If you just want to
    // use an image, put it in `src` and `import` it from JavaScript instead.
    contentBase: paths.appPublic,
    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
    // for the WebpackDevServer client so it can learn when the files were
    // updated. The WebpackDevServer client is included as an entry point
    // in the Webpack development configuration. Note that only changes
    // to CSS are currently hot reloaded. JS changes will refresh the browser.
    hot: true,
    // It is important to tell WebpackDevServer to use the same "root" path
    // as we specified in the config. In development, we always serve from /.
    publicPath: config.output.publicPath,
    // WebpackDevServer is noisy by default so we emit custom message instead
    // by listening to the compiler events with `compiler.plugin` calls above.
    quiet: true,
    // Reportedly, this avoids CPU overload on some systems.
    // https://github.com/facebookincubator/create-react-app/issues/293
    watchOptions: {
      ignored: /node_modules/
    },
    // Enable HTTPS if the HTTPS environment variable is set to 'true'
    https: protocol === 'https',
    host: host,
    // https://webpack.github.io/docs/webpack-dev-server.html#proxy
    proxy: {
      '/graphql': {
        target: `http://${process.env.GRAPHQL_PROXY_DOMAIN}${process.env.GRAPHQL_PROXY_PATH}`,
        secure: false,
        pathRewrite: {'^/graphql': ''}
      }
    }
  })

  // Our custom middleware proxies requests to /index.html or a remote API.
  addMiddleware(devServer)

  // Launch WebpackDevServer.
  devServer.listen(port, (err, result) => {
    if (err) {
      return console.log(err)
    }

    if (isInteractive) {
      clearConsole()
    }
    console.log(chalk.cyan('Starting the development server...'))
    console.log()

    if (isInteractive) {
      openBrowser(protocol + '://' + host + ':' + port + '/')
    }
  })
}

function run (port) {
  var protocol = process.env.HTTPS === 'true' ? 'https' : 'http'
  var host = process.env.WEB_HOST || 'localhost'
  setupCompiler(host, port, protocol)
  runDevServer(host, port, protocol)
}

run(DEFAULT_PORT)
<commit_msg>Support a different host in development<commit_after>process.env.NODE_ENV = 'development'

var path = require('path')

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/keithmorris/node-dotenv-extended
require('dotenv-extended').load({
  path: path.join(__dirname, '..', '.env'),
  defaults: path.join(__dirname, '..', '.env.defaults'),
  schema: path.join(__dirname, '..', '.env.schema')
})

var chalk = require('chalk')
var webpack = require('webpack')
var WebpackDevServer = require('webpack-dev-server')
var historyApiFallback = require('connect-history-api-fallback')
var httpProxyMiddleware = require('http-proxy-middleware')
var clearConsole = require('react-dev-utils/clearConsole')
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles')
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages')
var openBrowser = require('react-dev-utils/openBrowser')
var pathExists = require('path-exists')
var config = require('../config/webpack.config.dev')
var paths = require('../config/paths')

var useYarn = pathExists.sync(paths.yarnLockFile)
var cli = useYarn ? 'yarn' : 'npm'
var isInteractive = false// process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1)
}

// Tools like Cloud9 rely on this.
var DEFAULT_PORT = process.env.WEB_PORT || 3000
var compiler
var handleCompile

function setupCompiler (host, port, protocol) {
  // "Compiler" is a low-level interface to Webpack.
  // It lets us listen to some events and provide our own custom messages.
  compiler = webpack(config, handleCompile)

  // "invalid" event fires when you have changed a file, and Webpack is
  // recompiling a bundle. WebpackDevServer takes care to pause serving the
  // bundle, so if you refresh, it'll wait instead of serving the old one.
  // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
  compiler.plugin('invalid', function () {
    if (isInteractive) {
      clearConsole()
    }
    console.log('Compiling...')
  })

  var isFirstCompile = true

  // "done" event fires when Webpack has finished recompiling the bundle.
  // Whether or not you have warnings or errors, you will get this event.
  compiler.plugin('done', function (stats) {
    if (isInteractive) {
      clearConsole()
    }

    // We have switched off the default Webpack output in WebpackDevServer
    // options so we are going to "massage" the warnings and errors and present
    // them in a readable focused way.
    var messages = formatWebpackMessages(stats.toJson({}, true))
    var isSuccessful = !messages.errors.length && !messages.warnings.length
    var showInstructions = isSuccessful && (isInteractive || isFirstCompile)

    if (isSuccessful) {
      console.log(chalk.green('Compiled successfully!'))
    }

    if (showInstructions) {
      console.log()
      console.log('The app is running at:')
      console.log()
      console.log('  ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'))
      console.log()
      console.log('Note that the development build is not optimized.')
      console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.')
      console.log()
      isFirstCompile = false
    }

    // If errors exist, only show errors.
    if (messages.errors.length) {
      console.log(chalk.red('Failed to compile.'))
      console.log()
      messages.errors.forEach(message => {
        console.log(message)
        console.log()
      })
      return
    }

    // Show warnings if no errors were found.
    if (messages.warnings.length) {
      console.log(chalk.yellow('Compiled with warnings.'))
      console.log()
      messages.warnings.forEach(message => {
        console.log(message)
        console.log()
      })
      // Teach some ESLint tricks.
      console.log('You may use special comments to disable some warnings.')
      console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.')
      console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.')
    }
  })
}

// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError (proxy) {
  return function (err, req, res) {
    var host = req.headers && req.headers.host
    console.log(
      chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
      ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
    )
    console.log(
      'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
      chalk.cyan(err.code) + ').'
    )
    console.log()

    // And immediately send the proper error response to the client.
    // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
    if (res.writeHead && !res.headersSent) {
      res.writeHead(500)
    }
    res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
      host + ' to ' + proxy + ' (' + err.code + ').'
    )
  }
}

function addMiddleware (devServer) {
  // `proxy` lets you to specify a fallback server during development.
  // Every unrecognized request will be forwarded to it.
  var proxy = require(paths.appPackageJson).proxy
  devServer.use(historyApiFallback({
    // Paths with dots should still use the history fallback.
    // See https://github.com/facebookincubator/create-react-app/issues/387.
    disableDotRule: true,
    // For single page apps, we generally want to fallback to /index.html.
    // However we also want to respect `proxy` for API calls.
    // So if `proxy` is specified, we need to decide which fallback to use.
    // We use a heuristic: if request `accept`s text/html, we pick /index.html.
    // Modern browsers include text/html into `accept` header when navigating.
    // However API calls like `fetch()` won’t generally accept text/html.
    // If this heuristic doesn’t work well for you, don’t use `proxy`.
    htmlAcceptHeaders: proxy
      ? ['text/html']
      : ['text/html', '*/*']
  }))
  if (proxy) {
    if (typeof proxy !== 'string') {
      console.log(chalk.red('When specified, "proxy" in package.json must be a string.'))
      console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'))
      console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'))
      process.exit(1)
    }

    // Otherwise, if proxy is specified, we will let it handle any request.
    // There are a few exceptions which we won't send to the proxy:
    // - /index.html (served as HTML5 history API fallback)
    // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
    // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
    // Tip: use https://jex.im/regulex/ to visualize the regex
    var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/

    // Pass the scope regex both to Express and to the middleware for proxying
    // of both HTTP and WebSockets to work without false positives.
    var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
      target: proxy,
      logLevel: 'silent',
      onProxyReq: function (proxyReq, req, res) {
        // Browers may send Origin headers even with same-origin
        // requests. To prevent CORS issues, we have to change
        // the Origin to match the target URL.
        if (proxyReq.getHeader('origin')) {
          proxyReq.setHeader('origin', proxy)
        }
      },
      onError: onProxyError(proxy),
      secure: false,
      changeOrigin: true,
      ws: true
    })
    devServer.use(mayProxy, hpm)

    // Listen for the websocket 'upgrade' event and upgrade the connection.
    // If this is not done, httpProxyMiddleware will not try to upgrade until
    // an initial plain HTTP request is made.
    devServer.listeningApp.on('upgrade', hpm.upgrade)
  }

  // Finally, by now we have certainly resolved the URL.
  // It may be /index.html, so let the dev server try serving it again.
  devServer.use(devServer.middleware)
}

function runDevServer (host, port, protocol) {
  var devServer = new WebpackDevServer(compiler, {
    // Enable gzip compression of generated files.
    compress: true,
    // Silence WebpackDevServer's own logs since they're generally not useful.
    // It will still show compile warnings and errors with this setting.
    clientLogLevel: 'none',
    // By default WebpackDevServer serves physical files from current directory
    // in addition to all the virtual build products that it serves from memory.
    // This is confusing because those files won’t automatically be available in
    // production build folder unless we copy them. However, copying the whole
    // project directory is dangerous because we may expose sensitive files.
    // Instead, we establish a convention that only files in `public` directory
    // get served. Our build script will copy `public` into the `build` folder.
    // In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
    // Note that we only recommend to use `public` folder as an escape hatch
    // for files like `favicon.ico`, `manifest.json`, and libraries that are
    // for some reason broken when imported through Webpack. If you just want to
    // use an image, put it in `src` and `import` it from JavaScript instead.
    contentBase: paths.appPublic,
    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
    // for the WebpackDevServer client so it can learn when the files were
    // updated. The WebpackDevServer client is included as an entry point
    // in the Webpack development configuration. Note that only changes
    // to CSS are currently hot reloaded. JS changes will refresh the browser.
    hot: true,
    // It is important to tell WebpackDevServer to use the same "root" path
    // as we specified in the config. In development, we always serve from /.
    publicPath: config.output.publicPath,
    // WebpackDevServer is noisy by default so we emit custom message instead
    // by listening to the compiler events with `compiler.plugin` calls above.
    quiet: true,
    // Reportedly, this avoids CPU overload on some systems.
    // https://github.com/facebookincubator/create-react-app/issues/293
    watchOptions: {
      ignored: /node_modules/
    },
    // Enable HTTPS if the HTTPS environment variable is set to 'true'
    https: protocol === 'https',
    host: host,
    // To deal with "Invalid Host Header":
    // https://github.com/facebook/create-react-app/issues/2271#issuecomment-302818385
    // If we upgrade Webpack we can use "allowedHosts" instead, or
    // this is fixed in create-react-app >1.0.2.
    disableHostCheck: true,
    // https://webpack.github.io/docs/webpack-dev-server.html#proxy
    proxy: {
      '/graphql': {
        target: `http://${process.env.GRAPHQL_PROXY_DOMAIN}${process.env.GRAPHQL_PROXY_PATH}`,
        secure: false,
        pathRewrite: {'^/graphql': ''}
      }
    }
  })

  // Our custom middleware proxies requests to /index.html or a remote API.
  addMiddleware(devServer)

  // Launch WebpackDevServer.
  devServer.listen(port, (err, result) => {
    if (err) {
      return console.log(err)
    }

    if (isInteractive) {
      clearConsole()
    }
    console.log(chalk.cyan('Starting the development server...'))
    console.log()

    if (isInteractive) {
      openBrowser(protocol + '://' + host + ':' + port + '/')
    }
  })
}

function run (port) {
  var protocol = process.env.HTTPS === 'true' ? 'https' : 'http'
  var host = process.env.WEB_HOST || 'localhost'
  setupCompiler(host, port, protocol)
  runDevServer(host, port, protocol)
}

run(DEFAULT_PORT)
<|endoftext|>


<commit_before><commit_msg>singapore<commit_after><|endoftext|>


<commit_before>// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.

// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".

// import socket from "./socket"
//

$('#choose-existing .form-group').hide();
$('#choose-existing .form-error').hide();
$('#create-new .form-group').hide();
$('#create-new .form-error').hide();

$('#choose-existing a').on('click', function() {
  $(this).toggleClass('active');
  $('#create-new a').removeClass('active');
  $('#choose-existing .form-group').toggle();
  $('#choose-existing .form-error').toggle();
  $('#create-new .form-group').hide();
  $('#create-new .form-error').hide();
});

$('#create-new a').on('click', function() {
  $(this).toggleClass('active');
  $('#choose-existing a').removeClass('active');
  $('#create-new .form-group').toggle();
  $('#create-new .form-error').toggle();
  $('#choose-existing .form-group').hide();
  $('#choose-existing .form-error').hide();
});
<commit_msg>clean up js<commit_after>import "phoenix_html"

var chooseExistingId = '#choose-existing';
var createNewId = '#create-new';

function toggleVisibleFormGroup(visibleId, hiddenId) {
  if (!$(this).hasClass('active')) {
    $(this).toggleClass('active');
    $(hiddenId + ' a').removeClass('active');
    $(visibleId + ' .form-group').toggle();
    $(visibleId + ' .form-error').toggle();
    $(hiddenId + ' .form-group').hide();
    $(hiddenId + ' .form-error').hide();
  }
}

$('#choose-existing .form-group').hide();
$('#choose-existing .form-error').hide();
$('#create-new .form-group').hide();
$('#create-new .form-error').hide();

$('#choose-existing a').on('click', function() {
  if (!$(this).hasClass('active')) {
    $(this).toggleClass('active');
    toggleVisibleFormGroup(chooseExistingId, createNewId);
  }
});

$('#create-new a').on('click', function() {
  if (!$(this).hasClass('active')) {
    $(this).toggleClass('active');
    toggleVisibleFormGroup(createNewId, chooseExistingId);
  }
});

<|endoftext|>


<commit_before>function Message(data){
	this.id = Number(data.postid);

	this.user = {
		id: Number(data.userid),
		name: data.username
	};

	this.value = data.message;
	this.posted = new Date(data.posted);

	this.$el = null; //after createDOM() -> div.message
}

Message.prototype.createDOM = function(){

}
<commit_msg>Update message.js<commit_after>function Message(data){
	this.id = Number(data.postid);

	this.user = {
		id: Number(data.userid),
		name: data.username
	};

	this.value = data.message;
	this.posted = new Date(data.posted);

	this.$el = null; //after createDOM() -> div.message
}

Message.prototype.createDOM = function(){
	this.$el = document.createElement('div');
}
<|endoftext|>


<commit_before>let objBrowser = chrome ? chrome : browser;
(function() {
    //Toggle the highlight option and set it in LocalStorage
    var objOptionAddHighlight = document.querySelector('[name="ext-etheraddresslookup-show_style"]');
    if(objOptionAddHighlight) {
        objOptionAddHighlight.addEventListener('click', toggleMatchHighlight);
    }

    //Select the blockchain explorer set it in LocalStorage
    var objOptionBlockchainExplorer = document.getElementById('ext-etheraddresslookup-choose_blockchain');
    if(objOptionBlockchainExplorer) {
        objOptionBlockchainExplorer.addEventListener('change', toggleBlockchainExplorer);
    }

    //Toggle the address lookups option and set it in LocalStorage
    var objAddressLookups = document.getElementById('ext-etheraddresslookup-perform_address_lookups');
    if(objAddressLookups) {
        objAddressLookups.addEventListener('click', togglePerformAddressLookups);
    }

    //Toggle the blacklist domains option and set it in LocalStorage
    let objBlacklistDomains = document.getElementById('ext-etheraddresslookup-blacklist_domains');
    if (objBlacklistDomains) {
        objBlacklistDomains.addEventListener('click', toggleBlacklistDomains);
    }

    //Toggle the use 3rd party blacklist domains option and set it in LocalStorage
    objBlacklistDomains = document.getElementById('ext-etheraddresslookup-3rd_party_blacklist_domains');
    if (objBlacklistDomains) {
        objBlacklistDomains.addEventListener('click', toggle3rdPartyBlacklistDomains);
    }

    //Toggle the use of blacklisting all punycode domains and set it in LocalStorage
    var objBlacklistPunycodeDomains = document.getElementById('ext-etheraddresslookup-block_punycode_blacklist_domains');
    if(objBlacklistPunycodeDomains) {
        objBlacklistPunycodeDomains.addEventListener('click', toggleBlockPunycodeDomains);
    }

    //Get the extension version
    var objManifest = objBrowser.runtime.getManifest();
    var objManifestVersion = document.getElementById('ext-manifest_version');
    if(objManifestVersion) {
        objManifestVersion.innerHTML = objManifest.version;
    }

    //init getting blacklisted domains
    getBlacklistedDomains();
    setInterval(function() {
        console.log("Re-caching blacklisted domains");
        getBlacklistedDomains();
    }, 180000);

    getWhitelistedDomains();
    setInterval(function() {
        console.log("Re-caching whitelisted domains");
        getWhitelistedDomains();
    }, 180000);
})();

objBrowser.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        var strOption = request.func;
        var strResponse = "";

        switch(strOption) {
            case 'highlight_option' :
                strResponse = localStorage.getItem("ext-etheraddresslookup-show_style");
                break;
            case 'blockchain_explorer' :
                strResponse = localStorage.getItem("ext-etheraddresslookup-blockchain_explorer");
                if(strResponse === null) {
                    strResponse = "https://etherscan.io/address";
                }
                break;
            case 'blacklist_domains' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-blacklist_domains") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-blacklist_domains");
                }
                break;
            case '3rd_party_blacklist_domains' :
                //This option is enabled by defailt
                if(localStorage.getItem("ext-etheraddresslookup-3rd_party_blacklist_domains") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-3rd_party_blacklist_domains");
                }
                break;
            case 'blacklist_domain_list' :
                console.log("Getting blacklisted domain list");
                strResponse = getBlacklistedDomains("eal");
                break;
            case '3p_blacklist_domain_list' :
                console.log("Getting 3p blacklisted domain list");
                strResponse = getBlacklistedDomains("3p");
                break;
            case 'use_3rd_party_blacklists' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist");
                }
                break;
            case 'block_punycode_domains' :
                //This option is disabled by default
                if(localStorage.getItem("ext-etheraddresslookup-block_punycode_blacklist_domains") === null) {
                    strResponse = 0;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-block_punycode_blacklist_domains");
                }
                break;
            case 'whitelist_domain_list' :
                console.log("Getting whitelisted domain list");
                strResponse = getWhitelistedDomains();
                break;
            case 'rpc_provider' :
                    if(localStorage.getItem("ext-etheraddresslookup-rpc_node") === null) {
                        strResponse = "https://freely-central-lark.quiknode.io/9fe4c4a0-2ea2-4ac1-ab64-f92990cd2914/118-xxADc8hKSSB9joCb-g==/";
                    } else {
                        strResponse = localStorage.getItem("ext-etheraddresslookup-rpc_node");
                    }
                break;
            case 'rpc_default_provider' :
                strResponse = "https://freely-central-lark.quiknode.io/9fe4c4a0-2ea2-4ac1-ab64-f92990cd2914/118-xxADc8hKSSB9joCb-g==/";
                break;
            case 'perform_address_lookups' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-perform_address_lookups") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-perform_address_lookups");
                }
                break;
            case 'blacklist_whitelist_domain_list' :
                var objDomainLists = {"blacklist": "", "whitelist": ""};
                var objBlacklist = JSON.parse(getBlacklistedDomains("eal"));
                objDomainLists.blacklist = objBlacklist.domains;
                objDomainLists.whitelist = getWhitelistedDomains();
                strResponse = JSON.stringify(objDomainLists);
                break;
            case 'twitter_validation' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-twitter_validation") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-twitter_validation");
                }
                break;
            case 'twitter_lists' :
                //See when they were last fetched
                let twitter_lists = {
                    "last_fetched": 0,
                    "whitelist": [],
                    "blacklist": []
                };

                if(localStorage.getItem("ext-etheraddresslookup-twitter_lists")) {
                    let saved_settings = JSON.parse(localStorage.getItem("ext-etheraddresslookup-twitter_lists"));
                    twitter_lists.last_fetched = saved_settings.last_fetched;
                }

                if((Math.floor(Date.now() - twitter_lists.last_fetched)) > 600*1000) {
                    fetch("https://raw.githubusercontent.com/MrLuit/EtherScamDB/master/_data/twitter.json")
                    .then(res => res.json())
                    .then((lists) => {
                        twitter_lists.last_fetched = Date.now();

                        //We only need the Twitter IDs
                        Object.entries(lists.whitelist).forEach(
                            ([twitter_userid, screename]) => {
                                twitter_lists.whitelist.push(twitter_userid);
                            }
                        );

                        Object.entries(lists.blacklist).forEach(
                            ([twitter_userid, screename]) => {
                                twitter_lists.blacklist.push(twitter_userid);
                            }
                        );

                        localStorage.setItem("ext-etheraddresslookup-twitter_lists", JSON.stringify(twitter_lists));
                    });
                }

                if(localStorage.getItem("ext-etheraddresslookup-twitter_lists")) {
                    var cached_list = JSON.parse(localStorage.getItem("ext-etheraddresslookup-twitter_lists"));
                    twitter_lists.whitelist = cached_list.whitelist;
                    twitter_lists.blacklist = cached_list.blacklist;
                }

                strResponse = JSON.stringify(twitter_lists);
                break;
            case 'signature_inject' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-signature_inject") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-signature_inject");
                }
                break;
            default:
                strResponse = "unsupported";
                break;
        }

        sendResponse({resp:strResponse});
    }
);

function getBlacklistedDomains(strType)
{
    var objEalBlacklistedDomains = {
        "eal": {
            "timestamp": 0,
            "domains": [],
            "format": "plain",
            "repo": "http://api.infura.io/v1/blacklist",
            "identifer": "eal"
        },
        "third_party": {
            "phishfort": {
                "timestamp": 0,
                "domains": [],
                "format": "plain",
                "repo": "https://raw.githubusercontent.com/phishfort/counter_phishing_blacklist/master/blacklists/domains.json",
                "identifer": "phishfort"
            },
            "segasec": {
                "timestamp": 0,
                "domains": [],
                "format": "sha256",
                "repo": "https://segasec.github.io/PhishingFeed/phishing-domains-sha256.json",
                "identifer": "segasec"
            }
        }
    };
    //See if we need to get the blacklisted domains - ie: do we have them cached?
    if (localStorage.getItem("ext-etheraddresslookup-blacklist_domains_list") === null) {
        updateAllBlacklists(objEalBlacklistedDomains);
    } else {
        var objBlacklistedDomains = localStorage.getItem("ext-etheraddresslookup-blacklist_domains_list");
        //Check to see if the cache is older than 5 minutes, if so re-cache it.
        objBlacklistedDomains = JSON.parse(objBlacklistedDomains);
        console.log("Domains last fetched: " + (Math.floor(Date.now() / 1000) - objBlacklistedDomains.timestamp) + " seconds ago");
        if (objBlacklistedDomains.timestamp == 0 || (Math.floor(Date.now() / 1000) - objBlacklistedDomains.timestamp) > 300) {
            updateAllBlacklists(objEalBlacklistedDomains);
        }
    }

    strType = strType || "eal";

    return localStorage.getItem(`ext-etheraddresslookup-${strType === 'eal' ? '' : '3p_'}blacklist_domains_list`);
}

function updateAllBlacklists(objEalBlacklistedDomains)
{
    getBlacklistedDomainsFromSource(objEalBlacklistedDomains.eal).then(function (arrDomains) {
        objEalBlacklistedDomains.eal.timestamp = Math.floor(Date.now() / 1000);
        objEalBlacklistedDomains.eal.domains = arrDomains;

        localStorage.setItem("ext-etheraddresslookup-blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.eal));
    });

    if( [null, 1].indexOf(localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist")) >= 0) {
        getBlacklistedDomainsFromSource(objEalBlacklistedDomains.third_party.phishfort).then(function (arrDomains) {
            objEalBlacklistedDomains.third_party.phishfort.timestamp = Math.floor(Date.now() / 1000);
            objEalBlacklistedDomains.third_party.phishfort.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-3p_blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.third_party));
            return objEalBlacklistedDomains.eal.domains;
        });

        getBlacklistedDomainsFromSource(objEalBlacklistedDomains.third_party.segasec).then(function (arrDomains) {
            objEalBlacklistedDomains.third_party.segasec.timestamp = Math.floor(Date.now() / 1000);
            objEalBlacklistedDomains.third_party.segasec.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-3p_blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.third_party));
            return objEalBlacklistedDomains.eal.domains;
        });
    }
}

function getWhitelistedDomains()
{
    let objWhitelistedDomains = {"timestamp":0,"domains":[]};
    //See if we need to get the blacklisted domains - ie: do we have them cached?
    if (localStorage.getItem("ext-etheraddresslookup-whitelist_domains_list") === null) {
        getWhitelistedDomainsFromSource().then(function (arrDomains) {
            objWhitelistedDomains.timestamp = Math.floor(Date.now() / 1000);
            objWhitelistedDomains.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-whitelist_domains_list", JSON.stringify(objWhitelistedDomains));
            return objWhitelistedDomains.domains;
        });
    } else {
        objWhitelistedDomains = localStorage.getItem("ext-etheraddresslookup-whitelist_domains_list");
        //Check to see if the cache is older than 5 minutes, if so re-cache it.
        objWhitelistedDomains = JSON.parse(objWhitelistedDomains);
        console.log("Whitelisted domains last fetched: " + (Math.floor(Date.now() / 1000) - objWhitelistedDomains.timestamp) + " seconds ago");
        if ((Math.floor(Date.now() / 1000) - objWhitelistedDomains.timestamp) > 300) {
            console.log("Caching whitelisted domains again.");
            getWhitelistedDomainsFromSource().then(function (arrDomains) {
                objWhitelistedDomains.timestamp = Math.floor(Date.now() / 1000);
                objWhitelistedDomains.domains = arrDomains;

                localStorage.setItem("ext-etheraddresslookup-whitelist_domains_list", JSON.stringify(objWhitelistedDomains));
                return objWhitelistedDomains.domains;
            });
        }
    }

    return objWhitelistedDomains.domains;
}

async function getBlacklistedDomainsFromSource(objBlacklist)
{
    try {
        console.log("Getting blacklist from GitHub now: "+ objBlacklist.repo);
        let objResponse = await fetch(objBlacklist.repo);
        return objResponse.json();
    }
    catch(objError) {
        console.log("Failed to get blacklist for "+ objBlacklist.repo, objError);
    }
}

async function getWhitelistedDomainsFromSource()
{
    try {
        console.log("Getting whitelist from GitHub now: https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json");
        let objResponse = await fetch("https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json");
        return objResponse.json();
    }
    catch(objError) {
        console.log("Failed to get whitelist for https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json", objError);
    }
}<commit_msg>Modified phishfort repo link<commit_after>let objBrowser = chrome ? chrome : browser;
(function() {
    //Toggle the highlight option and set it in LocalStorage
    var objOptionAddHighlight = document.querySelector('[name="ext-etheraddresslookup-show_style"]');
    if(objOptionAddHighlight) {
        objOptionAddHighlight.addEventListener('click', toggleMatchHighlight);
    }

    //Select the blockchain explorer set it in LocalStorage
    var objOptionBlockchainExplorer = document.getElementById('ext-etheraddresslookup-choose_blockchain');
    if(objOptionBlockchainExplorer) {
        objOptionBlockchainExplorer.addEventListener('change', toggleBlockchainExplorer);
    }

    //Toggle the address lookups option and set it in LocalStorage
    var objAddressLookups = document.getElementById('ext-etheraddresslookup-perform_address_lookups');
    if(objAddressLookups) {
        objAddressLookups.addEventListener('click', togglePerformAddressLookups);
    }

    //Toggle the blacklist domains option and set it in LocalStorage
    let objBlacklistDomains = document.getElementById('ext-etheraddresslookup-blacklist_domains');
    if (objBlacklistDomains) {
        objBlacklistDomains.addEventListener('click', toggleBlacklistDomains);
    }

    //Toggle the use 3rd party blacklist domains option and set it in LocalStorage
    objBlacklistDomains = document.getElementById('ext-etheraddresslookup-3rd_party_blacklist_domains');
    if (objBlacklistDomains) {
        objBlacklistDomains.addEventListener('click', toggle3rdPartyBlacklistDomains);
    }

    //Toggle the use of blacklisting all punycode domains and set it in LocalStorage
    var objBlacklistPunycodeDomains = document.getElementById('ext-etheraddresslookup-block_punycode_blacklist_domains');
    if(objBlacklistPunycodeDomains) {
        objBlacklistPunycodeDomains.addEventListener('click', toggleBlockPunycodeDomains);
    }

    //Get the extension version
    var objManifest = objBrowser.runtime.getManifest();
    var objManifestVersion = document.getElementById('ext-manifest_version');
    if(objManifestVersion) {
        objManifestVersion.innerHTML = objManifest.version;
    }

    //init getting blacklisted domains
    getBlacklistedDomains();
    setInterval(function() {
        console.log("Re-caching blacklisted domains");
        getBlacklistedDomains();
    }, 180000);

    getWhitelistedDomains();
    setInterval(function() {
        console.log("Re-caching whitelisted domains");
        getWhitelistedDomains();
    }, 180000);
})();

objBrowser.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        var strOption = request.func;
        var strResponse = "";

        switch(strOption) {
            case 'highlight_option' :
                strResponse = localStorage.getItem("ext-etheraddresslookup-show_style");
                break;
            case 'blockchain_explorer' :
                strResponse = localStorage.getItem("ext-etheraddresslookup-blockchain_explorer");
                if(strResponse === null) {
                    strResponse = "https://etherscan.io/address";
                }
                break;
            case 'blacklist_domains' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-blacklist_domains") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-blacklist_domains");
                }
                break;
            case '3rd_party_blacklist_domains' :
                //This option is enabled by defailt
                if(localStorage.getItem("ext-etheraddresslookup-3rd_party_blacklist_domains") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-3rd_party_blacklist_domains");
                }
                break;
            case 'blacklist_domain_list' :
                console.log("Getting blacklisted domain list");
                strResponse = getBlacklistedDomains("eal");
                break;
            case '3p_blacklist_domain_list' :
                console.log("Getting 3p blacklisted domain list");
                strResponse = getBlacklistedDomains("3p");
                break;
            case 'use_3rd_party_blacklists' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist");
                }
                break;
            case 'block_punycode_domains' :
                //This option is disabled by default
                if(localStorage.getItem("ext-etheraddresslookup-block_punycode_blacklist_domains") === null) {
                    strResponse = 0;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-block_punycode_blacklist_domains");
                }
                break;
            case 'whitelist_domain_list' :
                console.log("Getting whitelisted domain list");
                strResponse = getWhitelistedDomains();
                break;
            case 'rpc_provider' :
                    if(localStorage.getItem("ext-etheraddresslookup-rpc_node") === null) {
                        strResponse = "https://freely-central-lark.quiknode.io/9fe4c4a0-2ea2-4ac1-ab64-f92990cd2914/118-xxADc8hKSSB9joCb-g==/";
                    } else {
                        strResponse = localStorage.getItem("ext-etheraddresslookup-rpc_node");
                    }
                break;
            case 'rpc_default_provider' :
                strResponse = "https://freely-central-lark.quiknode.io/9fe4c4a0-2ea2-4ac1-ab64-f92990cd2914/118-xxADc8hKSSB9joCb-g==/";
                break;
            case 'perform_address_lookups' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-perform_address_lookups") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-perform_address_lookups");
                }
                break;
            case 'blacklist_whitelist_domain_list' :
                var objDomainLists = {"blacklist": "", "whitelist": ""};
                var objBlacklist = JSON.parse(getBlacklistedDomains("eal"));
                objDomainLists.blacklist = objBlacklist.domains;
                objDomainLists.whitelist = getWhitelistedDomains();
                strResponse = JSON.stringify(objDomainLists);
                break;
            case 'twitter_validation' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-twitter_validation") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-twitter_validation");
                }
                break;
            case 'twitter_lists' :
                //See when they were last fetched
                let twitter_lists = {
                    "last_fetched": 0,
                    "whitelist": [],
                    "blacklist": []
                };

                if(localStorage.getItem("ext-etheraddresslookup-twitter_lists")) {
                    let saved_settings = JSON.parse(localStorage.getItem("ext-etheraddresslookup-twitter_lists"));
                    twitter_lists.last_fetched = saved_settings.last_fetched;
                }

                if((Math.floor(Date.now() - twitter_lists.last_fetched)) > 600*1000) {
                    fetch("https://raw.githubusercontent.com/MrLuit/EtherScamDB/master/_data/twitter.json")
                    .then(res => res.json())
                    .then((lists) => {
                        twitter_lists.last_fetched = Date.now();

                        //We only need the Twitter IDs
                        Object.entries(lists.whitelist).forEach(
                            ([twitter_userid, screename]) => {
                                twitter_lists.whitelist.push(twitter_userid);
                            }
                        );

                        Object.entries(lists.blacklist).forEach(
                            ([twitter_userid, screename]) => {
                                twitter_lists.blacklist.push(twitter_userid);
                            }
                        );

                        localStorage.setItem("ext-etheraddresslookup-twitter_lists", JSON.stringify(twitter_lists));
                    });
                }

                if(localStorage.getItem("ext-etheraddresslookup-twitter_lists")) {
                    var cached_list = JSON.parse(localStorage.getItem("ext-etheraddresslookup-twitter_lists"));
                    twitter_lists.whitelist = cached_list.whitelist;
                    twitter_lists.blacklist = cached_list.blacklist;
                }

                strResponse = JSON.stringify(twitter_lists);
                break;
            case 'signature_inject' :
                //This option is enabled by default
                if(localStorage.getItem("ext-etheraddresslookup-signature_inject") === null) {
                    strResponse = 1;
                } else {
                    strResponse = localStorage.getItem("ext-etheraddresslookup-signature_inject");
                }
                break;
            default:
                strResponse = "unsupported";
                break;
        }

        sendResponse({resp:strResponse});
    }
);

function getBlacklistedDomains(strType)
{
    var objEalBlacklistedDomains = {
        "eal": {
            "timestamp": 0,
            "domains": [],
            "format": "plain",
            "repo": "http://api.infura.io/v1/blacklist",
            "identifer": "eal"
        },
        "third_party": {
            "phishfort": {
                "timestamp": 0,
                "domains": [],
                "format": "plain",
                "repo": "https://raw.githubusercontent.com/phishfort/phishfort-lists/master/blacklists/domains.json",
                "identifer": "phishfort"
            },
            "segasec": {
                "timestamp": 0,
                "domains": [],
                "format": "sha256",
                "repo": "https://segasec.github.io/PhishingFeed/phishing-domains-sha256.json",
                "identifer": "segasec"
            }
        }
    };
    //See if we need to get the blacklisted domains - ie: do we have them cached?
    if (localStorage.getItem("ext-etheraddresslookup-blacklist_domains_list") === null) {
        updateAllBlacklists(objEalBlacklistedDomains);
    } else {
        var objBlacklistedDomains = localStorage.getItem("ext-etheraddresslookup-blacklist_domains_list");
        //Check to see if the cache is older than 5 minutes, if so re-cache it.
        objBlacklistedDomains = JSON.parse(objBlacklistedDomains);
        console.log("Domains last fetched: " + (Math.floor(Date.now() / 1000) - objBlacklistedDomains.timestamp) + " seconds ago");
        if (objBlacklistedDomains.timestamp == 0 || (Math.floor(Date.now() / 1000) - objBlacklistedDomains.timestamp) > 300) {
            updateAllBlacklists(objEalBlacklistedDomains);
        }
    }

    strType = strType || "eal";

    return localStorage.getItem(`ext-etheraddresslookup-${strType === 'eal' ? '' : '3p_'}blacklist_domains_list`);
}

function updateAllBlacklists(objEalBlacklistedDomains)
{
    getBlacklistedDomainsFromSource(objEalBlacklistedDomains.eal).then(function (arrDomains) {
        objEalBlacklistedDomains.eal.timestamp = Math.floor(Date.now() / 1000);
        objEalBlacklistedDomains.eal.domains = arrDomains;

        localStorage.setItem("ext-etheraddresslookup-blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.eal));
    });

    if( [null, 1].indexOf(localStorage.getItem("ext-etheraddresslookup-use_3rd_party_blacklist")) >= 0) {
        getBlacklistedDomainsFromSource(objEalBlacklistedDomains.third_party.phishfort).then(function (arrDomains) {
            objEalBlacklistedDomains.third_party.phishfort.timestamp = Math.floor(Date.now() / 1000);
            objEalBlacklistedDomains.third_party.phishfort.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-3p_blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.third_party));
            return objEalBlacklistedDomains.eal.domains;
        });

        getBlacklistedDomainsFromSource(objEalBlacklistedDomains.third_party.segasec).then(function (arrDomains) {
            objEalBlacklistedDomains.third_party.segasec.timestamp = Math.floor(Date.now() / 1000);
            objEalBlacklistedDomains.third_party.segasec.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-3p_blacklist_domains_list", JSON.stringify(objEalBlacklistedDomains.third_party));
            return objEalBlacklistedDomains.eal.domains;
        });
    }
}

function getWhitelistedDomains()
{
    let objWhitelistedDomains = {"timestamp":0,"domains":[]};
    //See if we need to get the blacklisted domains - ie: do we have them cached?
    if (localStorage.getItem("ext-etheraddresslookup-whitelist_domains_list") === null) {
        getWhitelistedDomainsFromSource().then(function (arrDomains) {
            objWhitelistedDomains.timestamp = Math.floor(Date.now() / 1000);
            objWhitelistedDomains.domains = arrDomains;

            localStorage.setItem("ext-etheraddresslookup-whitelist_domains_list", JSON.stringify(objWhitelistedDomains));
            return objWhitelistedDomains.domains;
        });
    } else {
        objWhitelistedDomains = localStorage.getItem("ext-etheraddresslookup-whitelist_domains_list");
        //Check to see if the cache is older than 5 minutes, if so re-cache it.
        objWhitelistedDomains = JSON.parse(objWhitelistedDomains);
        console.log("Whitelisted domains last fetched: " + (Math.floor(Date.now() / 1000) - objWhitelistedDomains.timestamp) + " seconds ago");
        if ((Math.floor(Date.now() / 1000) - objWhitelistedDomains.timestamp) > 300) {
            console.log("Caching whitelisted domains again.");
            getWhitelistedDomainsFromSource().then(function (arrDomains) {
                objWhitelistedDomains.timestamp = Math.floor(Date.now() / 1000);
                objWhitelistedDomains.domains = arrDomains;

                localStorage.setItem("ext-etheraddresslookup-whitelist_domains_list", JSON.stringify(objWhitelistedDomains));
                return objWhitelistedDomains.domains;
            });
        }
    }

    return objWhitelistedDomains.domains;
}

async function getBlacklistedDomainsFromSource(objBlacklist)
{
    try {
        console.log("Getting blacklist from GitHub now: "+ objBlacklist.repo);
        let objResponse = await fetch(objBlacklist.repo);
        return objResponse.json();
    }
    catch(objError) {
        console.log("Failed to get blacklist for "+ objBlacklist.repo, objError);
    }
}

async function getWhitelistedDomainsFromSource()
{
    try {
        console.log("Getting whitelist from GitHub now: https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json");
        let objResponse = await fetch("https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json");
        return objResponse.json();
    }
    catch(objError) {
        console.log("Failed to get whitelist for https://raw.githubusercontent.com/409H/EtherAddressLookup/master/whitelists/domains.json", objError);
    }
}<|endoftext|>


<commit_before>const Storage = require('./storage');

const options = Storage.get();
const submit = document.querySelector('#save');
const status = document.querySelector('#status');
const inputs = {
    base: document.querySelector('#base'),
    key: document.querySelector('#key'),
    poll: document.querySelector('#poll')
};

for(let name in inputs) {
    inputs[name].value = options.api[name];
}

submit.addEventListener('click', e => {
    for(let name in inputs) {
        options.api[name] = inputs[name].value;
    }
    Storage.save(options)
        .then(() => {
            status.textContent = 'Options saved.';

            window.setTimeout(() => {
                tick.remove();
            }, 1000);
        });
});
document.body.appendChild(submit);
<commit_msg>Load storage on options page<commit_after>const Storage = require('./storage');

Storage.load()
    .then(options => {
        const submit = document.querySelector('#save');
        const status = document.querySelector('#status');
        const inputs = {
            base: document.querySelector('#base'),
            key: document.querySelector('#key'),
            poll: document.querySelector('#poll')
        };

        for(let name in inputs) {
            inputs[name].value = options.api[name];
        }

        submit.addEventListener('click', e => {
            for(let name in inputs) {
                options.api[name] = inputs[name].value;
            }
            Storage.save(options)
                .then(() => {
                    status.textContent = 'Options saved.';

                    window.setTimeout(() => {
                        tick.remove();
                    }, 1000);
                });
        });
        document.body.appendChild(submit);
    });
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();

// you can access arguments passed to your iframe like so
var num = t.arg('rand');

t.render(function(){
  // this function we be called once on initial load
  // and then called each time something changes that
  // you might want to react to, such as new data being
  // stored with t.set()
  var card = t.card('name','shortLink');
  console.log('card.get("name"): ', card.get('name'));
  console.log('card.get("shortLink"): ', card.get("shortLink"));
  document.getElementsByTagName('iframe')[0].src = "https://docs.google.com/forms/d/e/1FAIpQLSeXKOZiY8QNUpCVbNQKEG0_Dg6IAcPv-DlsO987xhd7zC01Vg/viewform?embedded=true&entry.995291397=" + card.get('name');
});

// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
  if(e.target.tagName == 'BODY') {
    t.closeOverlay().done();
  }
});

// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
  if(e.keyCode == 27) {
    t.closeOverlay().done();
  }
});
<commit_msg>modify overlay js<commit_after>/* global TrelloPowerUp */
var Promise = TrelloPowerUp.Promise;
var t = TrelloPowerUp.iframe();
var gFormUrl = '';
var cardName = '';
var cardShortLink = '';

// you can access arguments passed to your iframe like so
var num = t.arg('rand');

t.render(function(){
  // this function we be called once on initial load
  // and then called each time something changes that
  // you might want to react to, such as new data being
  // stored with t.set()

  var card = t.card('name','shortLink');
  console.log('card: ', card);
  console.log('card.get("name"): ', card.get('name'));
  console.log('card.get("shortLink"): ', card.get("shortLink"));
  return Promise.all([
    t.get('board', 'shared', 'url'),
    t.card('name','shortLink')
  ])
  .spread(function(savedGFormUrl, cardData){
    if(savedGFormUrl){
      gFormUrl = savedGFormUrl;
    } else {
      console.log('Please add form url on settings');
    }
    if(cardData){
      cardName = card.name;
      cardShortLink = card.shortLink;
    }
  })
  .then(function(){
    var formUrl = gFormUrl + "?embedded=true&entry.995291397=" + cardName;
    console.log('formUrl: ', formUrl);
    document.getElementsByTagName('iframe')[0].src = formUrl;
  })
});

// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
  if(e.target.tagName == 'BODY') {
    t.closeOverlay().done();
  }
});

// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
  if(e.keyCode == 27) {
    t.closeOverlay().done();
  }
});
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();

// you can access arguments passed to your iframe like so
var num = t.arg('rand');

t.render(function(){
  // this function we be called once on initial load
  // and then called each time something changes that
  // you might want to react to, such as new data being
  // stored with t.set()
});

// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
  if(e.target.tagName == 'BODY') {
    t.closeOverlay().done();
  }
});

// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
  if(e.keyCode == 27) {
    t.closeOverlay().done();
  }
});

console.log('card: ', t.card());
<commit_msg>get card data<commit_after>/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();

// you can access arguments passed to your iframe like so
var num = t.arg('rand');

t.render(function(){
  // this function we be called once on initial load
  // and then called each time something changes that
  // you might want to react to, such as new data being
  // stored with t.set()
  console.log('card: ', t.card());
});

// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
  if(e.target.tagName == 'BODY') {
    t.closeOverlay().done();
  }
});

// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
  if(e.keyCode == 27) {
    t.closeOverlay().done();
  }
});

<|endoftext|>


<commit_before>// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }}
}());

// Place any jQuery/helper plugins in here.

//Author URL: http://www.ianlunn.co.uk/
//License: http://creativecommons.org/licenses/by-sa/3.0/ (Attribution Share Alike). Please attribute work to Ian Lunn simply by leaving these comments in the source code or if you'd prefer, place a link on your website to http://www.ianlunn.co.uk/.

//Dual licensed under the MIT and GPL licenses:
//http://www.opensource.org/licenses/mit-license.php
//http://www.gnu.org/licenses/gpl.html
// vertical Scrolling modified by globeFreak www.cwclan.de

$(document).ready(function() { //when the document is ready

		windowHeight = $(window).height(); //get the height of the window
		city = windowHeight * 0.675; //create a variable that contains the starting position for bg-city.png
		hillsW = windowHeight * 0.010; //do the same for bg-hills.png
		hillsH = windowHeight * 0.350; //do the same for bg-hills.png
		cloudsW = windowHeight * 0.350; //do the same for bg-mountains.png
		cloudsH = windowHeight * 0.010;
		sky = 0; //sky starts at the top (0px)

		//change the css of the <html> element to give it multiple backgrounds using CSS3. This contains the variables we just worked out for each individual background
		$('html').css({"background" : "url(img/bg-city.png) " + city + "px bottom repeat-x fixed, url(img/bg-hills.png) " + hillsW + "px " + hillsH + "px repeat-x fixed, url(img/bg-clouds.png) " + cloudsW + "px " + cloudsH + "px repeat-x fixed, url(img/bg-sky.jpg) " + sky + "px " + sky + "px repeat-x #747a94 fixed"});

		function Move(){ //set up a function to be called whenever the window is scrolled or resized
			windowHeight = $(window).height(); //get the height of the window
			pos = $(window).scrollTop(); //get the position of the scrollbar
			city = windowHeight * 0.675 + pos * 1.1; //create a variable that contains the starting position for bg-city.png
			cityfix = windowHeight * 0.675;
			hillsW = windowHeight * 0.010 + pos * 0.7; //do the same for bg-hills.png
			hillsH = windowHeight * 0.350;
			cloudsW = windowHeight * 0.350 + pos * 0.51; //do the same for bg-mountains.png
			cloudsH = windowHeight * 0.010;
			skyW = 0 + pos * 0.35; //do the same for bg-mountains.png
			sky = 0; //keep the sky at the top (0px), it moves naturally with the scroll anyway

			//change the css of the <html> element to give it multiple backgrounds using CSS3. The variables contained will change for every pixel the window is resized or scrolled
			$('html').css({"background" : "url(img/bg-city.png) " + city + "px bottom repeat-x fixed, url(img/bg-hills.png) " + hillsW + "px " + hillsH + "px repeat-x fixed, url(img/bg-clouds.png) " + cloudsW + "px " + cloudsH + "px repeat-x fixed, url(img/bg-sky.jpg) " + skyW + "px " + sky + "px repeat-x #747a94 fixed"});
		}

	$(window).resize(function(){ //when the window is resized...
		Move(); //call the Move() function
	});

	$(window).bind('scroll', function(){ //when the user is scrolling...
		Move(); //call the Move() function
	});

});

// jQuery div toggle
(function ($) {
    $.fn.showHide = function (options) {

	//default vars for the plugin
        var defaults = {
            speed: 800,
			easing: '',
			changeText: 0,
			showText: 'Show',
			hideText: 'Hide'

        };
        var options = $.extend(defaults, options);

        $(this).click(function () {
			 // optionally add the class .toggleDiv to each div you want to automatically close
             //$('.toggleDiv').fadeOut(options.speed, options.easing);
             $('.toggleDiv').animate({ height: '100%', opacity: .5 }, 'slow');
			 // this var stores which button you've clicked
             var toggleClick = $(this);
		     // this reads the rel attribute of the button to determine which div id to toggle
		     var toggleDiv = $(this).attr('rel');
		     // here we toggle show/hide the correct div at the right speed and using which easing effect
		     //$(toggleDiv).fadeToggle(options.speed, options.easing, function() {
		     $(toggleDiv).animate({ height: '100%', width: '10px', opacity: .5 }, 'slow', function() {
		     // this only fires once the animation is completed
			 if(options.changeText==1){
		     $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
			 }
              });

		  return false;

        });

    };
})(jQuery);

$(document).ready(function(){

   $('.show_hide').showHide({
		speed: 800,  // speed you want the toggle to happen
		easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
		changeText: 1, // if you dont want the button text to change, set this to 0
		showText: 'View',// the button text to show when a div is closed
		hideText: 'Close' // the button text to show when a div is open

	});

});
// jQuery div toggle ---END---<commit_msg>toggle sides<commit_after>// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }}
}());

// Place any jQuery/helper plugins in here.

//Author URL: http://www.ianlunn.co.uk/
//License: http://creativecommons.org/licenses/by-sa/3.0/ (Attribution Share Alike). Please attribute work to Ian Lunn simply by leaving these comments in the source code or if you'd prefer, place a link on your website to http://www.ianlunn.co.uk/.

//Dual licensed under the MIT and GPL licenses:
//http://www.opensource.org/licenses/mit-license.php
//http://www.gnu.org/licenses/gpl.html
// vertical Scrolling modified by globeFreak www.cwclan.de

$(document).ready(function() { //when the document is ready

		windowHeight = $(window).height(); //get the height of the window
		city = windowHeight * 0.675; //create a variable that contains the starting position for bg-city.png
		hillsW = windowHeight * 0.010; //do the same for bg-hills.png
		hillsH = windowHeight * 0.350; //do the same for bg-hills.png
		cloudsW = windowHeight * 0.350; //do the same for bg-mountains.png
		cloudsH = windowHeight * 0.010;
		sky = 0; //sky starts at the top (0px)

		//change the css of the <html> element to give it multiple backgrounds using CSS3. This contains the variables we just worked out for each individual background
		$('html').css({"background" : "url(img/bg-city.png) " + city + "px bottom repeat-x fixed, url(img/bg-hills.png) " + hillsW + "px " + hillsH + "px repeat-x fixed, url(img/bg-clouds.png) " + cloudsW + "px " + cloudsH + "px repeat-x fixed, url(img/bg-sky.jpg) " + sky + "px " + sky + "px repeat-x #747a94 fixed"});

		function Move(){ //set up a function to be called whenever the window is scrolled or resized
			windowHeight = $(window).height(); //get the height of the window
			pos = $(window).scrollTop(); //get the position of the scrollbar
			city = windowHeight * 0.675 + pos * 1.1; //create a variable that contains the starting position for bg-city.png
			cityfix = windowHeight * 0.675;
			hillsW = windowHeight * 0.010 + pos * 0.7; //do the same for bg-hills.png
			hillsH = windowHeight * 0.350;
			cloudsW = windowHeight * 0.350 + pos * 0.51; //do the same for bg-mountains.png
			cloudsH = windowHeight * 0.010;
			skyW = 0 + pos * 0.35; //do the same for bg-mountains.png
			sky = 0; //keep the sky at the top (0px), it moves naturally with the scroll anyway

			//change the css of the <html> element to give it multiple backgrounds using CSS3. The variables contained will change for every pixel the window is resized or scrolled
			$('html').css({"background" : "url(img/bg-city.png) " + city + "px bottom repeat-x fixed, url(img/bg-hills.png) " + hillsW + "px " + hillsH + "px repeat-x fixed, url(img/bg-clouds.png) " + cloudsW + "px " + cloudsH + "px repeat-x fixed, url(img/bg-sky.jpg) " + skyW + "px " + sky + "px repeat-x #747a94 fixed"});
		}

	$(window).resize(function(){ //when the window is resized...
		Move(); //call the Move() function
	});

	$(window).bind('scroll', function(){ //when the user is scrolling...
		Move(); //call the Move() function
	});

});

// jQuery div toggle
(function ($) {
    $.fn.showHide = function (options) {

	//default vars for the plugin
        var defaults = {
            speed: 800,
			easing: '',
			changeText: 0,
			showText: 'Show',
			hideText: 'Hide'

        };
        var options = $.extend(defaults, options);

        $(this).click(function () {
			 // optionally add the class .toggleDiv to each div you want to automatically close
             //$('.toggleDiv').fadeOut(options.speed, options.easing);
             $('.toggleDiv').animate({ height: 0, opacity: 0 }, 'slow');
			 // this var stores which button you've clicked
             var toggleClick = $(this);
		     // this reads the rel attribute of the button to determine which div id to toggle
		     var toggleDiv = $(this).attr('rel');
		     // here we toggle show/hide the correct div at the right speed and using which easing effect
		     //$(toggleDiv).fadeToggle(options.speed, options.easing, function() {
		     $(toggleDiv).animate({ height: 'toggle', opacity: 'toggle' }, 'slow', function() {
		     // this only fires once the animation is completed
			 if(options.changeText==1){
		     $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
			 }
              });

		  return false;

        });

    };
})(jQuery);

$(document).ready(function(){

   $('.show_hide').showHide({
		speed: 800,  // speed you want the toggle to happen
		easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
		changeText: 1, // if you dont want the button text to change, set this to 0
		showText: 'View',// the button text to show when a div is closed
		hideText: 'Close' // the button text to show when a div is open

	});

});
// jQuery div toggle ---END---<|endoftext|>