<commit_before>(function () {
"use strict";

var require = window.require = makeRequire("/");
require.resolve = resolve;
function makeRequire(root) {
function require(path) {
  return realRequire(root, path);
}
function requireAsync(path, callback) {
  realRequireAsync(root, path, function (module) {
    callback(null, module);
  }, callback);
}
require.async = requireAsync;
return require;
}

////////////////////////////////////////////////////////////////////////////////
// Get source files via XHR.
// Protect calls to get to cache and not allow concurrent requests.
// This I/O can be very expensive.
var files = {};
var missing = {};
var pendingGet = {};
function get(path, callback, errback) {
  if (path in files) return callback(path, files[path]);
  if (path in missing) return errback(missing[path]);
  if (path in pendingGet) return pendingGet[path].push([callback, errback]);
  pendingGet[path] = [[callback, errback]];
  realGet(path, function (contents) {
    files[path] = contents;
    flush();
  }, function (err) {
    missing[path] = err;
    flush();
  });
  function flush() {
    var pending = pendingGet[path];
    delete pendingGet[path];
    pending.forEach(function (pair) {
      get(path, pair[0], pair[1]);
    });
  }
}
function realGet(path, callback, errback) {
  var request = new XMLHttpRequest();
  request.onload = function () {
    callback(this.responseText);
  };
  request.onerror = function () {
    errback(this);
  };
  request.open("GET", path, true);
  request.setRequestHeader("Pragma", "no-cache");
  request.send();
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Use a temporary filesystem to write the wrapped js files.
// The writeFile function outputs the url the file that a script tag can use.
var fs;
var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
requestFileSystem(window.TEMPORARY, null, function (fileSystem) {
  fs = fileSystem;
  window.modulesReady();
}, function (fileError) {
  throw new Error("Unable to create temporary fs for module loader: " + fileError);
});
function writeFile(path, contents, callback, errback) {
  fs.root.getFile(path, {create: true}, function (fileEntry) {
    fileEntry.createWriter(function (fileWriter) {
      var truncated = false;
      fileWriter.onwriteend = function () {
        if (!truncated) {
          truncated = true;
          this.truncate(this.position);
          return;
        }
        callback(fileEntry.toURL());
      };
      fileWriter.onerror = errback;
      fileWriter.write(new Blob([contents], {type: 'text/plain'}));
    }, errback);
  }, errback);
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Resolve relative paths to absolute paths.
// Also implements module lookup logic and automatic file extensions.
// Root is always an absolute path starting and ending with a `/`
// path is the actual string used in require.
// If path starts with a `/`, then it's an absolute require.
// If paths starts with a `.`, then it's a relative require.
// Otherwise it's a module path and we must search for it.
// We also want to support optional extensions, loading json files, and
// parsing package.json looking for main.
// callback(realPath, contents) or errback(err) are the output.
var mappings = {};
require.mappings = mappings;
require.resolve = resolve;
function resolve(root, path, callback, errback) {
  function success(fullPath, contents) {
    mappings[root + ":" + path] = fullPath;
    callback(fullPath, contents);
  }
  if (path[0] === "/") return find(path, success, errback);
  if (path[0] === ".") return find(realPath(root + path), success, errback);
  var base = root;
  cycle();
  function cycle() {
    base = base.match(/^(.*\/)[^\/]*$/)[1];
    find(base + "modules/" + path, success, function () {
      if (base.length > 1) {
        base = base.substr(0, base.length - 1);
        cycle();
      }
      else {
        errback(new Error("Can't find module: " + path + " in " + root));
      }
    });
  }
}
function realPath(path) {
  var match;
  // Remove /./ entries from path
  while (match = path.match(/(\/)\.\//)) {
    path = path.replace(match[0], match[1]);
  }
  // Convert /foo/../ entries from path
  while (match = path.match(/(\/[^\/]*\/)\.\.\//)) {
    path = path.replace(match[0], match[1]);
  }
  return path;
}
function find(path, callback, errback) {
  // .js extensions are passed through as-is
  if (/\.js$/.test(path)) return get(path, callback, errback);
  // Then try looking for package.json
  // Then try appending the .js extension
  get(path + "/package.json", function (jsonPath, json) {
    // Parse the JSON file
    var doc;
    try { doc = JSON.parse(json); }
    catch (err) { return errback(err); }
    // Abort if main is missing
    if (!doc.main) {
      return errback(new Error("Missing main field in " + jsonPath));
    }
    find(realPath(path + "/" + doc.main), callback, errback);
  }, function () {
    get(path + ".js", callback, function () {
      errback(new Error("Unable to find module: " + path));
    });
  });
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Load loads a module and all it's dependencies, wraps them in AMD and inserts
// them as script tags.
function load(root, path, callback, errback) {
  resolve(root, path, function (realPath, contents) {
    process(realPath, contents, callback, errback);
  }, errback);
}
var defs = {};
require.defs = defs;
var defCallbacks = {};
window.define = define;
function define(path, deps, fn) {
  var def = { path: path, deps: deps, fn: fn };
  defs[path] = def;
  var callback = defCallbacks[path];
  delete defCallbacks[path];
  callback(def);
}
var processPending = {};
function process(path, contents, callback, errback) {
  if (path in defs) return callback(defs[path]);
  if (path in processPending) {
    return processPending[path].push([callback, errback]);
  }
  processPending[path] = [[callback, errback]];
  realProcess(path, contents, function (def) {
    defs[path] = def;
    flush(null, def);
  }, flush);
  function flush(err, def) {
    var pending = processPending[path];
    delete processPending[path];
    pending.forEach(function (pair) {
      if (err) pair[1](err);
      else pair[0](def);
    });
  }
}
function realProcess(path, contents, callback, errback) {
  // Scan for dependencies
  var root = path.match(/^(.*\/)[^\/]*$/)[1];
  var matches = contents.match(/require\((['"])[^)]*\1\)/g);
  var deps = [];
  if (!matches) return save();
  // If there are dependencies, load them first.
  var left = matches.length;
  for (var i = 0, l = left; i < l; i++) {
    var match = matches[i].match(/require\((['"])([^)]*)\1\)/)[2];
    resolve(root, match, onResolve, errback);
  }
  function onResolve(realPath, contents) {
    deps.push(realPath);
    process(realPath, contents, check, errback);
  }
  function check(dep) {
    deps.push(dep);
    if (--left) return;
    deps.sort();
    save();
  }

  function save() {
    // Wrap and save the file
    var wrappedjs = 'window.define(' + JSON.stringify(path) + ', ' + JSON.stringify(deps) +
      ', function (module, exports, require, __dirname, __filename) {\n' + contents + '\n});';
    writeFile(path.substr(1).replace(/\//g, "_"), wrappedjs, function (url) {
      defCallbacks[path] = callback;
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      document.head.appendChild(script);
    }, errback);
  }
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
var modules = {};
require.modules = modules;
function realRequire(root, path) {
  var realPath = mappings[root + ":" + path];
  if (!realPath) throw new Error("Can't require sync yet: " + path + " in " + root);
  var def = defs[realPath];
  if (!def) throw new Error("Missing definition for: " + realPath);
  return start(def);
}
function realRequireAsync(root, path, callback, errback) {
  load(root, path, function (def) {
    var module;
    try {
      module = start(def);
    }
    catch (err) {
      return errback(err);
    }
    callback(module);
  }, errback);
}

function start(def) {
  var pathname = def.path;
  var dirname = pathname.match(/^(.*\/)[^\/]*$/)[1];
  var require = makeRequire(dirname);
  var exports = {};
  var module = {exports: exports};
  delete defs[pathname];
  modules[pathname] = exports;
  def.fn(module, exports, require, dirname, pathname);
  modules[pathname] = module.exports;
  return module.exports;
}

}());
<commit_msg>Don't call errback multiple times, that's bad<commit_after>(function () {
"use strict";

var require = window.require = makeRequire("/");
require.resolve = resolve;
function makeRequire(root) {
function require(path) {
  return realRequire(root, path);
}
function requireAsync(path, callback) {
  realRequireAsync(root, path, function (module) {
    callback(null, module);
  }, callback);
}
require.async = requireAsync;
return require;
}

////////////////////////////////////////////////////////////////////////////////
// Get source files via XHR.
// Protect calls to get to cache and not allow concurrent requests.
// This I/O can be very expensive.
var files = {};
var missing = {};
var pendingGet = {};
function get(path, callback, errback) {
  if (path in files) return callback(path, files[path]);
  if (path in missing) return errback(missing[path]);
  if (path in pendingGet) return pendingGet[path].push([callback, errback]);
  pendingGet[path] = [[callback, errback]];
  realGet(path, function (contents) {
    files[path] = contents;
    flush();
  }, function (err) {
    missing[path] = err;
    flush();
  });
  function flush() {
    var pending = pendingGet[path];
    delete pendingGet[path];
    pending.forEach(function (pair) {
      get(path, pair[0], pair[1]);
    });
  }
}
function realGet(path, callback, errback) {
  var request = new XMLHttpRequest();
  request.onload = function () {
    callback(this.responseText);
  };
  request.onerror = function () {
    errback(this);
  };
  request.open("GET", path, true);
  request.setRequestHeader("Pragma", "no-cache");
  request.send();
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Use a temporary filesystem to write the wrapped js files.
// The writeFile function outputs the url the file that a script tag can use.
var fs;
var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
requestFileSystem(window.TEMPORARY, null, function (fileSystem) {
  fs = fileSystem;
  window.modulesReady();
}, function (fileError) {
  throw new Error("Unable to create temporary fs for module loader: " + fileError);
});
function writeFile(path, contents, callback, errback) {
  fs.root.getFile(path, {create: true}, function (fileEntry) {
    fileEntry.createWriter(function (fileWriter) {
      var truncated = false;
      fileWriter.onwriteend = function () {
        if (!truncated) {
          truncated = true;
          this.truncate(this.position);
          return;
        }
        callback(fileEntry.toURL());
      };
      fileWriter.onerror = errback;
      fileWriter.write(new Blob([contents], {type: 'text/plain'}));
    }, errback);
  }, errback);
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Resolve relative paths to absolute paths.
// Also implements module lookup logic and automatic file extensions.
// Root is always an absolute path starting and ending with a `/`
// path is the actual string used in require.
// If path starts with a `/`, then it's an absolute require.
// If paths starts with a `.`, then it's a relative require.
// Otherwise it's a module path and we must search for it.
// We also want to support optional extensions, loading json files, and
// parsing package.json looking for main.
// callback(realPath, contents) or errback(err) are the output.
var mappings = {};
require.mappings = mappings;
require.resolve = resolve;
function resolve(root, path, callback, errback) {
  function success(fullPath, contents) {
    mappings[root + ":" + path] = fullPath;
    callback(fullPath, contents);
  }
  if (path[0] === "/") return find(path, success, errback);
  if (path[0] === ".") return find(realPath(root + path), success, errback);
  var base = root;
  cycle();
  function cycle() {
    base = base.match(/^(.*\/)[^\/]*$/)[1];
    find(base + "modules/" + path, success, function () {
      if (base.length > 1) {
        base = base.substr(0, base.length - 1);
        cycle();
      }
      else {
        errback(new Error("Can't find module: " + path + " in " + root));
      }
    });
  }
}
function realPath(path) {
  var match;
  // Remove /./ entries from path
  while (match = path.match(/(\/)\.\//)) {
    path = path.replace(match[0], match[1]);
  }
  // Convert /foo/../ entries from path
  while (match = path.match(/(\/[^\/]*\/)\.\.\//)) {
    path = path.replace(match[0], match[1]);
  }
  return path;
}
function find(path, callback, errback) {
  // .js extensions are passed through as-is
  if (/\.js$/.test(path)) return get(path, callback, errback);
  // Then try looking for package.json
  // Then try appending the .js extension
  get(path + "/package.json", function (jsonPath, json) {
    // Parse the JSON file
    var doc;
    try { doc = JSON.parse(json); }
    catch (err) { return errback(err); }
    // Abort if main is missing
    if (!doc.main) {
      return errback(new Error("Missing main field in " + jsonPath));
    }
    find(realPath(path + "/" + doc.main), callback, errback);
  }, function () {
    get(path + ".js", callback, function () {
      errback(new Error("Unable to find module: " + path));
    });
  });
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Load loads a module and all it's dependencies, wraps them in AMD and inserts
// them as script tags.
function load(root, path, callback, errback) {
  resolve(root, path, function (realPath, contents) {
    process(realPath, contents, callback, errback);
  }, errback);
}
var defs = {};
require.defs = defs;
var defCallbacks = {};
window.define = define;
function define(path, deps, fn) {
  var def = { path: path, deps: deps, fn: fn };
  defs[path] = def;
  var callback = defCallbacks[path];
  delete defCallbacks[path];
  callback(def);
}
var processPending = {};
function process(path, contents, callback, errback) {
  if (path in defs) return callback(defs[path]);
  if (path in processPending) {
    return processPending[path].push([callback, errback]);
  }
  processPending[path] = [[callback, errback]];
  realProcess(path, contents, function (def) {
    defs[path] = def;
    flush(null, def);
  }, flush);
  function flush(err, def) {
    var pending = processPending[path];
    delete processPending[path];
    pending.forEach(function (pair) {
      if (err) pair[1](err);
      else pair[0](def);
    });
  }
}
function realProcess(path, contents, callback, errback) {
  var failed;
  function fail(err) {
    if (failed) return;
    failed = true;
    errback(err);
  }
  // Scan for dependencies
  var root = path.match(/^(.*\/)[^\/]*$/)[1];
  var matches = contents.match(/require\((['"])[^)]*\1\)/g);
  var deps = [];
  if (!matches) return save();
  // If there are dependencies, load them first.
  var left = matches.length;
  for (var i = 0, l = left; i < l; i++) {
    var match = matches[i].match(/require\((['"])([^)]*)\1\)/)[2];
    resolve(root, match, onResolve, fail);
  }
  function onResolve(realPath, contents) {
    deps.push(realPath);
    process(realPath, contents, check, fail);
  }
  function check(dep) {
    deps.push(dep);
    if (--left) return;
    deps.sort();
    save();
  }

  function save() {
    // Wrap and save the file
    var wrappedjs = 'window.define(' + JSON.stringify(path) + ', ' + JSON.stringify(deps) +
      ', function (module, exports, require, __dirname, __filename) {\n' + contents + '\n});';
    writeFile(path.substr(1).replace(/\//g, "_"), wrappedjs, function (url) {
      defCallbacks[path] = callback;
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      document.head.appendChild(script);
    }, errback);
  }
}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
var modules = {};
require.modules = modules;
function realRequire(root, path) {
  var realPath = mappings[root + ":" + path];
  if (!realPath) throw new Error("Can't require sync yet: " + path + " in " + root);
  var def = defs[realPath];
  if (!def) throw new Error("Missing definition for: " + realPath);
  return start(def);
}
function realRequireAsync(root, path, callback, errback) {
  load(root, path, function (def) {
    var module;
    try {
      module = start(def);
    }
    catch (err) {
      return errback(err);
    }
    callback(module);
  }, errback);
}

function start(def) {
  var pathname = def.path;
  var dirname = pathname.match(/^(.*\/)[^\/]*$/)[1];
  var require = makeRequire(dirname);
  var exports = {};
  var module = {exports: exports};
  delete defs[pathname];
  modules[pathname] = exports;
  def.fn(module, exports, require, dirname, pathname);
  modules[pathname] = module.exports;
  return module.exports;
}

}());
<|endoftext|>


<commit_before>var Wrapper = require('./Wrapper');

console.log("---------------------------------");
console.log("Code Kata: Word Wrap, by @romenrg");
console.log("---------------------------------");
var argv = process.argv.slice(2);
var errorMessage = "ERROR: First argument should be 'text to process' and second 'number of columns'";
if (argv.length == 2) {
    var result = (new Wrapper()).wrap(argv[0], parseInt(argv[1]));
    if (result == "error") {
        console.log(errorMessage);
    }
    else {
        console.log(result);
    }
}
else {
    console.log(errorMessage);
}<commit_msg>Adapting the cli to the new static version of the wrap function<commit_after>var Wrapper = require('./Wrapper');

console.log("---------------------------------");
console.log("Code Kata: Word Wrap, by @romenrg");
console.log("---------------------------------");
var argv = process.argv.slice(2);
var errorMessage = "ERROR: First argument should be 'text to process' and second 'number of columns'";
if (argv.length == 2) {
    var result = Wrapper.wrap(argv[0], parseInt(argv[1]));
    if (result == "error") {
        console.log(errorMessage);
    }
    else {
        console.log(result);
    }
}
else {
    console.log(errorMessage);
}<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/bluetooth-connect';

export default Ember.Component.extend({
  layout,

  bluetooth: Ember.inject.service(),

  _handleValueEvent(event) {
    let batteryLevel = event.target.value.getUint8(0);
    console.log('> Battery Level is ' + batteryLevel + '%');
  },

  actions: {
    connect() {
      this.get('bluetooth')
      .connectDevice({ filters: [{ services: ['battery_service'] }] })
      .then((device) => {
        console.log(`Connected to device: ${JSON.stringify(device)}`);
      });
    },

    readValue() {
      this.get('bluetooth')
        .readValue('battery_service', 'battery_level')
        .then(value => {
          console.log(`Battery level is: ${value}`);
        });
    },

    startNotifications() {
      this.get('bluetooth')
        .startNotifications('battery_service', 'battery_level', this._handleValueEvent);
    },

    stopNotifications() {
      this.get('bluetooth').stopNotifications();
    }
  }
});
<commit_msg>Save battery level<commit_after>import Ember from 'ember';
import layout from '../templates/components/bluetooth-connect';

export default Ember.Component.extend({
  classNames: ['bluetooth-connect'],
  layout,

  bluetooth: Ember.inject.service(),

  batteryLevel: 0,

  _handleValueEvent(event) {
    let batteryLevel = event.target.value.getUint8(0);
    this.set('batteryLevel', batteryLevel);
  },

  actions: {
    connect() {
      this.get('bluetooth')
      .connectDevice({ filters: [{ services: ['battery_service'] }] })
      .then((device) => {
        console.log(`Connected to device: ${JSON.stringify(device)}`);
      });
    },

    readValue() {
      this.get('bluetooth')
        .readValue('battery_service', 'battery_level')
        .then(value => {
          this.set('batteryLevel', value);
        });
    },

    startNotifications() {
      this.get('bluetooth')
        .startNotifications('battery_service', 'battery_level', (event) => this._handleValueEvent(event));
    },

    stopNotifications() {
      this.get('bluetooth').stopNotifications();
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var paths = require('./gulp-tasks/config.js').paths;
var browserSync = require('browser-sync');

gulp.task('fonts', require('./gulp-tasks/fonts.js')(gulp));
gulp.task('images', require('./gulp-tasks/images.js')(gulp));
gulp.task('jquery', require('./gulp-tasks/jquery.js')(gulp));
gulp.task('vendor', require('./gulp-tasks/vendor.js')(gulp));
gulp.task('minify-html', require('./gulp-tasks/html.js')(gulp));
gulp.task('less', require('./gulp-tasks/less.js')(gulp));
gulp.task('build', require('./gulp-tasks/build.js')(gulp));
gulp.task('js-watch', ['build'], browserSync.reload);
gulp.task('less-watch', ['less'], browserSync.reload);
gulp.task('build-all', ['vendor', 'build', 'less', 'minify-html', 'fonts', 'images', 'jquery']);
gulp.task('default', ['serve']);

gulp.task('serve', ['build-all'], function() {
  browserSync({
    server: './cordova/www'
  });
  gulp.watch(paths.js.watch, ['js-watch']);
  gulp.watch(paths.less.watch, ['less-watch']);
});

gulp.task('serve-with-node', ['build-all'], serve({
  root: ['./dist'],
  port: process.env.PORT || 8080
}));

gulp.task('test', function(done) {
  var karma = require('karma').server;
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, done);
});<commit_msg>Production config for mobile-client<commit_after>'use strict';

var gulp = require('gulp');
var paths = require('./gulp-tasks/config.js').paths;
var browserSync = require('browser-sync');
var serve = require('gulp-serve');

gulp.task('fonts', require('./gulp-tasks/fonts.js')(gulp));
gulp.task('images', require('./gulp-tasks/images.js')(gulp));
gulp.task('jquery', require('./gulp-tasks/jquery.js')(gulp));
gulp.task('vendor', require('./gulp-tasks/vendor.js')(gulp));
gulp.task('minify-html', require('./gulp-tasks/html.js')(gulp));
gulp.task('less', require('./gulp-tasks/less.js')(gulp));
gulp.task('build', require('./gulp-tasks/build.js')(gulp));
gulp.task('js-watch', ['build'], browserSync.reload);
gulp.task('less-watch', ['less'], browserSync.reload);
gulp.task('build-all', ['vendor', 'build', 'less', 'minify-html', 'fonts', 'images', 'jquery']);
gulp.task('default', ['serve']);

gulp.task('serve', ['build-all'], function() {
  browserSync({
    server: './cordova/www'
  });
  gulp.watch(paths.js.watch, ['js-watch']);
  gulp.watch(paths.less.watch, ['less-watch']);
});

gulp.task('serve-with-node', ['build-all'], serve({
  root: ['./cordova/www'],
  port: process.env.PORT || 8080
}));

gulp.task('test', function(done) {
  var karma = require('karma').server;
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, done);
});<|endoftext|>


<commit_before>// Geometries
var point = new ol.geom.Point(
    ol.proj.transform([3,50], 'EPSG:4326', 'EPSG:3857')
    );

// Features
var pointFeature = new ol.Feature(point);

// Source and vector layer
var vectorSource = new ol.source.Vector();

var style = new ol.style.Style({
    image: new ol.style.Circle({
        fill: new ol.style.Fill({
            color: 'rgba(255, 100, 50, 0.3)'
        }),
        stroke: new ol.style.Stroke({
            width: 1,
            color: 'rgba(255, 100, 50, 0.8)'
        }),
        radius: 7
    }),
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: style
});

// Maps
var map = new ol.Map({
target: 'map',  // The DOM element that will contains the map
renderer: 'canvas', // Force the renderer to be used
layers: [
// Add a new Tile layer getting tiles from OpenStreetMap source
new ol.layer.Tile({
    source: new ol.source.OSM()
}),
vectorLayer
],
// Create a view centered on the specified location and zoom level
view: new ol.View({
    center: ol.proj.transform([2.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
    zoom: 2
})
});

function emptyVector() {
  var features = vectorSource.getFeatures();

  for(var i = 0; i < features.length; i++) {
    vectorSource.removeFeature(features[i]);
  }
}

function updateMap() {
  if(vectorSource.getFeatures().length > 0) { // Empty the vector, if full
    emptyVector();
  }

loklakFetcher.checkTweets(query, function(tweets) {
    for(var i = 0; i < tweets.data.length; i++) {
        if (tweets.data[i].indexOf(query) !== -1) {
            break;
        }
    }
    if(i === tweets.data.length) {
        return;
    }
});

// Fetch loklak API data, and fill the vector
loklakFetcher.getTweets(query, function(tweets) {
    for(var i = 0; i < tweets.statuses.length; i++) {
        if(tweets.statuses[i].location_point !== undefined){
            // Creation of the point with the tweet's coordinates
            //  Coords system swap is required: OpenLayers uses by default
            //  EPSG:3857, while loklak's output is EPSG:4326
            var point = new ol.geom.Point(ol.proj.transform(tweets.statuses[i].location_point, 'EPSG:4326', 'EPSG:3857'));
            vectorSource.addFeature(new ol.Feature({  // Add the point to the data vector
                geometry: point
            }));
        }
    }
});
}

// Event listeners for updating the map
document.getElementById('searchButton').addEventListener('click', updateMap);

document.getElementById('searchField').addEventListener('keyup', function(e) {
  if(e.keyCode === 13) {
    updateMap();
  }
});
<commit_msg>emoji valid<commit_after>// Geometries
var point = new ol.geom.Point(
    ol.proj.transform([3,50], 'EPSG:4326', 'EPSG:3857')
    );

// Features
var pointFeature = new ol.Feature(point);

// Source and vector layer
var vectorSource = new ol.source.Vector();

var style = new ol.style.Style({
    image: new ol.style.Circle({
        fill: new ol.style.Fill({
            color: 'rgba(255, 100, 50, 0.3)'
        }),
        stroke: new ol.style.Stroke({
            width: 1,
            color: 'rgba(255, 100, 50, 0.8)'
        }),
        radius: 7
    }),
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: style
});

// Maps
var map = new ol.Map({
target: 'map',  // The DOM element that will contains the map
renderer: 'canvas', // Force the renderer to be used
layers: [
// Add a new Tile layer getting tiles from OpenStreetMap source
new ol.layer.Tile({
    source: new ol.source.OSM()
}),
vectorLayer
],
// Create a view centered on the specified location and zoom level
view: new ol.View({
    center: ol.proj.transform([2.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
    zoom: 2
})
});

function emptyVector() {
  var features = vectorSource.getFeatures();

  for(var i = 0; i < features.length; i++) {
    vectorSource.removeFeature(features[i]);
  }
}

function updateMap() {
  if(vectorSource.getFeatures().length > 0) { // Empty the vector, if full
    emptyVector();
  }

var query = document.getElementById('searchField').value;

loklakFetcher.checkTweets(query, function(tweets) {
    for(var i = 0; i < tweets.data.length; i++) {
        if (tweets.data[i].indexOf(query) !== -1) {
            break;
        }
    }
    if(i === tweets.data.length) {
        return;
    }
});

// Fetch loklak API data, and fill the vector
loklakFetcher.getTweets(query, function(tweets) {
    for(var i = 0; i < tweets.statuses.length; i++) {
        if(tweets.statuses[i].location_point !== undefined){
            // Creation of the point with the tweet's coordinates
            //  Coords system swap is required: OpenLayers uses by default
            //  EPSG:3857, while loklak's output is EPSG:4326
            var point = new ol.geom.Point(ol.proj.transform(tweets.statuses[i].location_point, 'EPSG:4326', 'EPSG:3857'));
            vectorSource.addFeature(new ol.Feature({  // Add the point to the data vector
                geometry: point
            }));
        }
    }
});
}

// Event listeners for updating the map
document.getElementById('searchButton').addEventListener('click', updateMap);

document.getElementById('searchField').addEventListener('keyup', function(e) {
  if(e.keyCode === 13) {
    updateMap();
  }
});
<|endoftext|>


<commit_before>var provider;

import { getConfiguration, configure } from 'torii/configuration';

import GoogleBearerProvider from 'torii/providers/google-oauth2-bearer';
import QUnit from 'qunit';

let { module, test } = QUnit;
let originalConfiguration;

module('Unit - GoogleAuth2BearerProvider', {
  setup: function(){
    originalConfiguration = getConfiguration();
    configure({
      providers: {
        'google-oauth2-bearer': {}
      }
    });
    provider = GoogleBearerProvider.create();
  },
  teardown: function(){
    Ember.run(provider, 'destroy');
    configure(originalConfiguration);
  }
});

test("Provider requires an apiKey", function(assert){
  assert.throws(function(){
    provider.buildUrl();
  }, /Expected configuration value apiKey to be defined.*google-oauth2-bearer/);
});

test("Provider generates a URL with required config", function(assert){
  configure({
    providers: {
      'google-oauth2-bearer': {
        apiKey: 'abcdef'
      }
    }
  });

  var expectedUrl = provider.get('baseUrl') + '?' + 'response_type=token' +
          '&client_id=' + 'abcdef' +
          '&redirect_uri=' + encodeURIComponent(provider.get('redirectUri')) +
          '&state=' + provider.get('state') +
          '&scope=email';

  assert.equal(provider.buildUrl(),
        expectedUrl,
        'generates the correct URL');
});
<commit_msg>test google oauth2 bearer optional parameters<commit_after>var provider;

import { getConfiguration, configure } from 'torii/configuration';

import GoogleBearerProvider from 'torii/providers/google-oauth2-bearer';
import QUnit from 'qunit';

let { module, test } = QUnit;
let originalConfiguration;

module('Unit - GoogleAuth2BearerProvider', {
  setup: function(){
    originalConfiguration = getConfiguration();
    configure({
      providers: {
        'google-oauth2-bearer': {}
      }
    });
    provider = GoogleBearerProvider.create();
  },
  teardown: function(){
    Ember.run(provider, 'destroy');
    configure(originalConfiguration);
  }
});

test("Provider requires an apiKey", function(assert){
  assert.throws(function(){
    provider.buildUrl();
  }, /Expected configuration value apiKey to be defined.*google-oauth2-bearer/);
});

test("Provider generates a URL with required config", function(assert){
  configure({
    providers: {
      'google-oauth2-bearer': {
        apiKey: 'abcdef'
      }
    }
  });

  var expectedUrl = provider.get('baseUrl') + '?' + 'response_type=token' +
          '&client_id=' + 'abcdef' +
          '&redirect_uri=' + encodeURIComponent(provider.get('redirectUri')) +
          '&state=' + provider.get('state') +
          '&scope=email';

  assert.equal(provider.buildUrl(),
        expectedUrl,
        'generates the correct URL');
});

test("Provider generates a URL with optional parameters", function(assert){
  configure({
    providers: {
      'google-oauth2-bearer': {
        apiKey: 'abcdef',
        requestVisibleActions: 'http://some-url.com',
        hd: 'google.com'
      }
    }
  });

  var expectedUrl = provider.get('baseUrl') + '?' + 'response_type=token' +
          '&client_id=' + 'abcdef' +
          '&redirect_uri=' + encodeURIComponent(provider.get('redirectUri')) +
          '&state=' + provider.get('state') +
          '&scope=email' +
          '&request_visible_actions=' + encodeURIComponent('http://some-url.com') +
          '&hd=google.com';

  assert.equal(provider.buildUrl(),
        expectedUrl,
        'generates the correct URL');
});
<|endoftext|>


<commit_before>Arbiter.Cordova = (function() {

	var state = 0;

	var isNeutral = function(){
		return state === Arbiter.Cordova.STATES.NEUTRAL;
	};

	var waitForNeutralQueue = [];

	var waitingForReset = false;

	var waitForNeutral = function(func){
		if(!Arbiter.Util.funcExists(func)){
			return;
		}

		if(isNeutral()){
			func();
		}else{
			waitForNeutralQueue.push(func);
		}
	};

	var executeWaitingFuncs = function(){
		for(var func = waitForNeutralQueue.shift(); Arbiter.Util.funcExists(func);
			func = waitForNeutralQueue.shift()){

			func();
		}
	};

	return {

		STATES : {
				NEUTRAL: 0,
				CREATING_PROJECT: 1,
				UPDATING: 2,
				OUTSIDE_AOI_WARNING: 3,
				TAKING_PICTURE: 4
		},

		osmLinkClicked: function(){

			cordova.exec(null, null, "ArbiterCordova", "osmLinkClicked", []);
		},

		isAddingGeometryPart: function(isAddingPart){

			cordova.exec(null, null, "ArbiterCordova", "isAddingGeometryPart", [isAddingPart]);
		},

		gotPicture: function(){

			cordova.exec(null, null, "ArbiterCordova", "gotPicture", []);
		},

		featureNotInAOI: function(featureId, insertFeature, cancelInsertFeature){

			Arbiter.Cordova.setState(Arbiter.Cordova.STATES.OUTSIDE_AOI_WARNING);

			cordova.exec(function(){

				if(Arbiter.Util.existsAndNotNull(insertFeature)){

					insertFeature();
				}

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);

			}, function(){

				if(Arbiter.Util.existsAndNotNull(cancelInsertFeature)){
					cancelInsertFeature();
				}

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, "ArbiterCordova", "featureNotInAOI", [featureId]);
		},

		layersAlreadyInProject: function(layersAlreadyInProject){

			console.log("layersAlreadyInProject: " + JSON.stringify(layersAlreadyInProject));

			cordova.exec(null, null, "ArbiterCordova", "layersAlreadyInProject", [layersAlreadyInProject]);
		},

		appFinishedLoading: function(){

			cordova.exec(null, null, "ArbiterCordova", "appFinishedLoading", []);
		},

		gotNotifications: function(){

			cordova.exec(null, null, "ArbiterCordova", "gotNotifications", []);
		},

		finishedGettingLocation: function(){

			cordova.exec(null, null, "ArbiterCordova", "finishedGettingLocation", []);
		},

		/**
		 * Save the current maps extent
		 */
		resetWebApp : function(tx) {
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			var reset = function(){
				console.log("resetWebApp: " + JSON.stringify(bbox));
				cordova.exec(null, null, "ArbiterCordova",
						"resetWebApp", [bbox, zoom]);
			};

			if(waitingForReset !== true){
				// Don't reset while a sync is occurring.
				waitForNeutral(function(){
					Arbiter.SQLiteTransactionManager.executeAfterDone(reset);
				});

				waitingForReset = true;
			}
		},

		getTileCount: function(){
			var bbox = Arbiter.Map.getCurrentExtent();

			var count = Arbiter.getTileUtil().getTileCount(bbox);

			cordova.exec(null, null, "ArbiterCordova",
					"confirmTileCount", [count]);
		},

		/**
		 * Get the area of interest in the aoi map and call the native method to
		 * save it to be set when onResume gets called on the MapActivity
		 */
		setProjectsAOI : function(layers) {
			var bbox = Arbiter.Map.getCurrentExtent();

			var count = Arbiter.getTileUtil().getTileCount(bbox);

			cordova.exec(null, null, "ArbiterCordova",
					"setProjectsAOI", [bbox.toBBOX(), count]);
		},

		setNewProjectsAOI: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();
			console.log("setNewProjectsAOI: bbox = " + bbox);
			cordova.exec(null, null, "ArbiterCordova",
					"setNewProjectsAOI", [bbox]);
		},

		goToProjects: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			cordova.exec(null, null, "ArbiterCordova",
					"goToProjects", [bbox, zoom]);
		},

		createNewProject: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			cordova.exec(null, null, "ArbiterCordova",
					"createNewProject", [bbox, zoom]);
		},

		errorCreatingProject: function(e){

			console.log("errorCreatingProject", e);
			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova",
					"errorCreatingProject", [e]);
		},

		errorLoadingFeatures: function(troublesomeFeatureTypes){
			var str = "";

			for(var i = 0; i < troublesomeFeatureTypes.length; i++){
				if(i > 0){
					str += troublesomeFeatureTypes[i];
				}else{
					str += ", " + troublesomeFeatureTypes[i];
				}
			}

			cordova.exec(null, null, "ArbiterCordova", "errorLoadingFeatures", [str]);
		},

		doneAddingLayers: function(){
			cordova.exec(null, null, "ArbiterCordova",
					"doneAddingLayers", []);
		},

		errorAddingLayers: function(e){
			cordova.exec(null, null, "ArbiterCordova",
					"errorAddingLayers", [e]);
		},

		// validate in here.
		getUpdatedGeometry: function(){

			console.log("getUpdatedGeometry");

			Arbiter.Controls.ControlPanel.finishInserting(function(){

				console.log("finished inserting");

				// Also finishes modifying the geometry
				Arbiter.Controls.ControlPanel.exitModifyMode(function(){

					try{
						var selectedFeature = Arbiter.Controls
							.ControlPanel.getSelectedFeature();

						console.log("selectedFeature", selectedFeature);

						if(!Arbiter.Util.existsAndNotNull(selectedFeature)){

							cordova.exec(null, null, "ArbiterCordova", "invalidGeometriesEntered", [null, null]);
						}else{
							console.log("selectedFeature isn't null");
							var featureId = null;

							if(selectedFeature.metadata !== null
									&& selectedFeature.metadata !== undefined){

								featureId = selectedFeature.metadata[
								    Arbiter.FeatureTableHelper.ID];
							}

							var layerId = Arbiter.Util.getLayerId(selectedFeature.layer);

							var schema = Arbiter.getLayerSchemas()[layerId];

							// Validate the feature and remove any invalid parts.
							var featureValidation = new Arbiter.Validation.Feature(selectedFeature, true);

							var invalidGeometries = featureValidation.validate();

							if(Arbiter.Util.existsAndNotNull(selectedFeature.metadata)
									&& selectedFeature.metadata[Arbiter.Validation.Feature.REMOVED_DURING_VALIDATION]){

								cordova.exec(null, null, "ArbiterCordova", "invalidGeometriesEntered", [schema.getFeatureType(), featureId]);
							}else{

								var insideAOI = featureValidation.checkFeatureAddedInsideAOI();

								var exec = function(){

									var wktGeometry = null;

									if(Arbiter.Util.existsAndNotNull(selectedFeature.geometry)){
										if(!Arbiter.Util.existsAndNotNull(featureId)){
											wktGeometry = Arbiter.Geometry.getNativeWKT(selectedFeature, layerId);
										}else{
											wktGeometry = Arbiter.Geometry.checkForGeometryCollection(layerId, featureId, schema.getSRID());
										}
									}

									cordova.exec(null, null, "ArbiterCordova", "showUpdatedGeometry",
											[schema.getFeatureType(), featureId, layerId, wktGeometry]);
								};

								if(insideAOI){
									exec();
								}else{

									Arbiter.Cordova.featureNotInAOI(featureId, exec, function(){

										// Using this to cancel the edit right now...
										Arbiter.Cordova.resetWebApp();
									});
								}

							}
						}
					}catch(e){
						console.log(e.stack);
					}
				});
			});
		},

		featureUnselected: function(){

			cordova.exec(null, null, "ArbiterCordova", "featureUnselected", []);
		},

		featureSelected : function(featureType, featureId, layerId,
				feature, mode, cancel){

			var featureValidator = new Arbiter.Validation.Feature(feature, false);

			featureValidator.validate();

			console.log("featureSelected featureValidator", featureValidator);

			if(featureValidator.hasValidGeometries === true){

				console.log("featureSelected: featureType = " + featureType
						+ ", featureId = " + featureId + ", layerId = "
						+ layerId + ", mode = " + mode + ", cancel = "
						+ cancel + ", feature = ", feature);

				var schemas = Arbiter.getLayerSchemas();

				var schema = schemas[layerId];

				var wktGeometry = null;

				if(cancel === false){

					if(!Arbiter.Util.existsAndNotNull(featureId)){
						wktGeometry = Arbiter.Geometry.getNativeWKT(feature, layerId);
					}else{
						wktGeometry = Arbiter.Geometry.checkForGeometryCollection(layerId, featureId, schema.getSRID());
					}
				}

				// Put check in place because its causing issues when modifying new features.
				// Don't want it to stop editing...
				if(Arbiter.Util.existsAndNotNull(featureId)){
					Arbiter.Controls.ControlPanel.exitModifyMode();
				}

				console.log("displayFeatureDialog selectedFeature: ", Arbiter.Controls.ControlPanel.getSelectedFeature());

				cordova.exec(null, null, "ArbiterCordova", "featureSelected",
						[featureType, featureId, layerId, wktGeometry, mode]);
			}
		},

		updateTileSyncingStatus: function(percent){
			cordova.exec(null, null, "ArbiterCordova",
					"updateTileSyncingStatus", [percent]);
		},

		updateMediaUploadingStatus: function(featureType,
				finishedMediaCount, totalMediaCount,
				finishedLayerCount, totalLayerCount){

			console.log("updateMediaUploadingStatus featureType = " + featureType
					+ ", finishedMediaCount = " + finishedMediaCount
					+ ", totalMediaCount = " + totalMediaCount
					+ ", finishedLayerCount = " + finishedLayerCount
					+ ", totalLayerCount = " + totalLayerCount);

			cordova.exec(null, null, "ArbiterCordova", "updateMediaUploadingStatus",
					[featureType, finishedMediaCount, totalMediaCount,
					 finishedLayerCount, totalLayerCount]);
		},

		updateMediaDownloadingStatus: function(featureType,
				finishedMediaCount, totalMediaCount,
				finishedLayerCount, totalLayerCount){

			console.log("updateMediaDownloadingStatus featureType = " + featureType
					+ ", finishedMediaCount = " + finishedMediaCount
					+ ", totalMediaCount = " + totalMediaCount
					+ ", finishedLayerCount = " + finishedLayerCount
					+ ", totalLayerCount = " + totalLayerCount);

			cordova.exec(null, null, "ArbiterCordova","updateMediaDownloadingStatus",
					[featureType, finishedMediaCount, totalMediaCount,
					 finishedLayerCount, totalLayerCount]);
		},

		createProjectTileSyncingStatus: function(percent){
			cordova.exec(null, null, "ArbiterCordova",
					"createProjectTileSyncingStatus", [percent]);
		},

		syncCompleted: function(){
			console.log("syncCompleted");
			cordova.exec(function(){

				Arbiter.Cordova.resetWebApp();

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova", "syncCompleted", []);
		},

		syncFailed: function(e){

			console.log("syncFailed");

			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova",
					"syncFailed", [e]);
		},

		errorUpdatingAOI: function(e){

			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova", "errorUpdatingAOI", [e]);
		},

		getState: function(){
			return state;
		},

		setState: function(_state){
			state = _state;

			if(isNeutral()){
				executeWaitingFuncs();
			}
		},

		addMediaToFeature: function(key, media, fileName){

			cordova.exec(null , null, "ArbiterCordova",
					"addMediaToFeature", [key, media, fileName]);

			Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
		},

		updateUploadingVectorDataProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateUploadingVectorDataProgress", [finished, total]);
		},

		updateDownloadingVectorDataProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateDownloadingVectorDataProgress", [finished, total]);
		},

		showDownloadingSchemasProgress: function(count){
			cordova.exec(null, null, "ArbiterCordova",
					"showDownloadingSchemasProgress", [count]);
		},

		updateDownloadingSchemasProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateDownloadingSchemasProgress", [finished, total]);
		},

		dismissDownloadingSchemasProgress: function(){

			cordova.exec(null, null, "ArbiterCordova",
					"dismissDownloadingSchemasProgress", []);
		},

		alertGeolocationError: function(msg){

			cordova.exec(null, null, "ArbiterCordova",
					"alertGeolocationError", [msg]);
		},

		setMultiPartBtnsEnabled: function(enable, enableCollection){

			cordova.exec(null, null, "ArbiterCordova", "setMultiPartBtnsEnabled", [enable, enableCollection]);
		},

		confirmPartRemoval: function(onConfirm){

			cordova.exec(onConfirm, null, "ArbiterCordova", "confirmPartRemoval", []);
		},

		confirmGeometryRemoval: function(onConfirm){

			cordova.exec(onConfirm, null, "ArbiterCordova", "confirmGeometryRemoval", []);
		},

		hidePartButtons: function(){
			cordova.exec(null, null, "ArbiterCordova", "hidePartButtons", []);
		},

		reportLayersWithUnsupportedCRS: function(layers){
			cordova.exec(null, null, "ArbiterCordova", "reportLayersWithUnsupportedCRS", [layers]);
		}
	};
})();<commit_msg>Fixed a bug caused by the controlPanels selectedFeature not getting cleared even if the feature is removed<commit_after>Arbiter.Cordova = (function() {

	var state = 0;

	var isNeutral = function(){
		return state === Arbiter.Cordova.STATES.NEUTRAL;
	};

	var waitForNeutralQueue = [];

	var waitingForReset = false;

	var waitForNeutral = function(func){
		if(!Arbiter.Util.funcExists(func)){
			return;
		}

		if(isNeutral()){
			func();
		}else{
			waitForNeutralQueue.push(func);
		}
	};

	var executeWaitingFuncs = function(){
		for(var func = waitForNeutralQueue.shift(); Arbiter.Util.funcExists(func);
			func = waitForNeutralQueue.shift()){

			func();
		}
	};

	return {

		STATES : {
				NEUTRAL: 0,
				CREATING_PROJECT: 1,
				UPDATING: 2,
				OUTSIDE_AOI_WARNING: 3,
				TAKING_PICTURE: 4
		},

		osmLinkClicked: function(){

			cordova.exec(null, null, "ArbiterCordova", "osmLinkClicked", []);
		},

		isAddingGeometryPart: function(isAddingPart){

			cordova.exec(null, null, "ArbiterCordova", "isAddingGeometryPart", [isAddingPart]);
		},

		gotPicture: function(){

			cordova.exec(null, null, "ArbiterCordova", "gotPicture", []);
		},

		featureNotInAOI: function(featureId, insertFeature, cancelInsertFeature){

			Arbiter.Cordova.setState(Arbiter.Cordova.STATES.OUTSIDE_AOI_WARNING);

			cordova.exec(function(){

				if(Arbiter.Util.existsAndNotNull(insertFeature)){

					insertFeature();
				}

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);

			}, function(){

				if(Arbiter.Util.existsAndNotNull(cancelInsertFeature)){
					cancelInsertFeature();
				}

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, "ArbiterCordova", "featureNotInAOI", [featureId]);
		},

		layersAlreadyInProject: function(layersAlreadyInProject){

			console.log("layersAlreadyInProject: " + JSON.stringify(layersAlreadyInProject));

			cordova.exec(null, null, "ArbiterCordova", "layersAlreadyInProject", [layersAlreadyInProject]);
		},

		appFinishedLoading: function(){

			cordova.exec(null, null, "ArbiterCordova", "appFinishedLoading", []);
		},

		gotNotifications: function(){

			cordova.exec(null, null, "ArbiterCordova", "gotNotifications", []);
		},

		finishedGettingLocation: function(){

			cordova.exec(null, null, "ArbiterCordova", "finishedGettingLocation", []);
		},

		/**
		 * Save the current maps extent
		 */
		resetWebApp : function(tx) {
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			var reset = function(){
				console.log("resetWebApp: " + JSON.stringify(bbox));
				cordova.exec(null, null, "ArbiterCordova",
						"resetWebApp", [bbox, zoom]);
			};

			if(waitingForReset !== true){
				// Don't reset while a sync is occurring.
				waitForNeutral(function(){
					Arbiter.SQLiteTransactionManager.executeAfterDone(reset);
				});

				waitingForReset = true;
			}
		},

		getTileCount: function(){
			var bbox = Arbiter.Map.getCurrentExtent();

			var count = Arbiter.getTileUtil().getTileCount(bbox);

			cordova.exec(null, null, "ArbiterCordova",
					"confirmTileCount", [count]);
		},

		/**
		 * Get the area of interest in the aoi map and call the native method to
		 * save it to be set when onResume gets called on the MapActivity
		 */
		setProjectsAOI : function(layers) {
			var bbox = Arbiter.Map.getCurrentExtent();

			var count = Arbiter.getTileUtil().getTileCount(bbox);

			cordova.exec(null, null, "ArbiterCordova",
					"setProjectsAOI", [bbox.toBBOX(), count]);
		},

		setNewProjectsAOI: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();
			console.log("setNewProjectsAOI: bbox = " + bbox);
			cordova.exec(null, null, "ArbiterCordova",
					"setNewProjectsAOI", [bbox]);
		},

		goToProjects: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			cordova.exec(null, null, "ArbiterCordova",
					"goToProjects", [bbox, zoom]);
		},

		createNewProject: function(){
			var bbox = Arbiter.Map.getCurrentExtent().toBBOX();

            var zoom = Arbiter.Map.getZoom();
			cordova.exec(null, null, "ArbiterCordova",
					"createNewProject", [bbox, zoom]);
		},

		errorCreatingProject: function(e){

			console.log("errorCreatingProject", e);
			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova",
					"errorCreatingProject", [e]);
		},

		errorLoadingFeatures: function(troublesomeFeatureTypes){
			var str = "";

			for(var i = 0; i < troublesomeFeatureTypes.length; i++){
				if(i > 0){
					str += troublesomeFeatureTypes[i];
				}else{
					str += ", " + troublesomeFeatureTypes[i];
				}
			}

			cordova.exec(null, null, "ArbiterCordova", "errorLoadingFeatures", [str]);
		},

		doneAddingLayers: function(){
			cordova.exec(null, null, "ArbiterCordova",
					"doneAddingLayers", []);
		},

		errorAddingLayers: function(e){
			cordova.exec(null, null, "ArbiterCordova",
					"errorAddingLayers", [e]);
		},

		// validate in here.
		getUpdatedGeometry: function(){

			console.log("getUpdatedGeometry");

			Arbiter.Controls.ControlPanel.finishInserting(function(){

				console.log("finished inserting");

				// Also finishes modifying the geometry
				Arbiter.Controls.ControlPanel.exitModifyMode(function(){

					try{
						var selectedFeature = Arbiter.Controls
							.ControlPanel.getSelectedFeature();

						console.log("selectedFeature", selectedFeature);

						if(!Arbiter.Util.existsAndNotNull(selectedFeature)){

							cordova.exec(null, null, "ArbiterCordova", "invalidGeometriesEntered", [null, null]);
						}else{
							console.log("selectedFeature isn't null");
							var featureId = null;

							if(selectedFeature.metadata !== null
									&& selectedFeature.metadata !== undefined){

								featureId = selectedFeature.metadata[
								    Arbiter.FeatureTableHelper.ID];
							}

							var layerId = Arbiter.Util.getLayerId(selectedFeature.layer);

							var schema = Arbiter.getLayerSchemas()[layerId];

							// Validate the feature and remove any invalid parts.
							var featureValidation = new Arbiter.Validation.Feature(selectedFeature, true);

							var invalidGeometries = featureValidation.validate();

							if(Arbiter.Util.existsAndNotNull(selectedFeature.metadata)
									&& selectedFeature.metadata[Arbiter.Validation.Feature.REMOVED_DURING_VALIDATION]){

								Arbiter.Controls.ControlPanel.setSelectedFeature(null);

								cordova.exec(null, null, "ArbiterCordova", "invalidGeometriesEntered", [schema.getFeatureType(), featureId]);
							}else{

								var insideAOI = featureValidation.checkFeatureAddedInsideAOI();

								var exec = function(){

									var wktGeometry = null;

									if(Arbiter.Util.existsAndNotNull(selectedFeature.geometry)){
										if(!Arbiter.Util.existsAndNotNull(featureId)){
											wktGeometry = Arbiter.Geometry.getNativeWKT(selectedFeature, layerId);
										}else{
											wktGeometry = Arbiter.Geometry.checkForGeometryCollection(layerId, featureId, schema.getSRID());
										}
									}

									cordova.exec(null, null, "ArbiterCordova", "showUpdatedGeometry",
											[schema.getFeatureType(), featureId, layerId, wktGeometry]);
								};

								if(insideAOI){
									exec();
								}else{

									Arbiter.Cordova.featureNotInAOI(featureId, exec, function(){

										// Using this to cancel the edit right now...
										Arbiter.Cordova.resetWebApp();
									});
								}

							}
						}
					}catch(e){
						console.log(e.stack);
					}
				});
			});
		},

		featureUnselected: function(){

			cordova.exec(null, null, "ArbiterCordova", "featureUnselected", []);
		},

		featureSelected : function(featureType, featureId, layerId,
				feature, mode, cancel){

			var featureValidator = new Arbiter.Validation.Feature(feature, false);

			featureValidator.validate();

			console.log("featureSelected featureValidator", featureValidator);

			if(featureValidator.hasValidGeometries === true){

				console.log("featureSelected: featureType = " + featureType
						+ ", featureId = " + featureId + ", layerId = "
						+ layerId + ", mode = " + mode + ", cancel = "
						+ cancel + ", feature = ", feature);

				var schemas = Arbiter.getLayerSchemas();

				var schema = schemas[layerId];

				var wktGeometry = null;

				if(cancel === false){

					if(!Arbiter.Util.existsAndNotNull(featureId)){
						wktGeometry = Arbiter.Geometry.getNativeWKT(feature, layerId);
					}else{
						wktGeometry = Arbiter.Geometry.checkForGeometryCollection(layerId, featureId, schema.getSRID());
					}
				}

				// Put check in place because its causing issues when modifying new features.
				// Don't want it to stop editing...
				if(Arbiter.Util.existsAndNotNull(featureId)){
					Arbiter.Controls.ControlPanel.exitModifyMode();
				}

				console.log("displayFeatureDialog selectedFeature: ", Arbiter.Controls.ControlPanel.getSelectedFeature());

				cordova.exec(null, null, "ArbiterCordova", "featureSelected",
						[featureType, featureId, layerId, wktGeometry, mode]);
			}
		},

		updateTileSyncingStatus: function(percent){
			cordova.exec(null, null, "ArbiterCordova",
					"updateTileSyncingStatus", [percent]);
		},

		updateMediaUploadingStatus: function(featureType,
				finishedMediaCount, totalMediaCount,
				finishedLayerCount, totalLayerCount){

			console.log("updateMediaUploadingStatus featureType = " + featureType
					+ ", finishedMediaCount = " + finishedMediaCount
					+ ", totalMediaCount = " + totalMediaCount
					+ ", finishedLayerCount = " + finishedLayerCount
					+ ", totalLayerCount = " + totalLayerCount);

			cordova.exec(null, null, "ArbiterCordova", "updateMediaUploadingStatus",
					[featureType, finishedMediaCount, totalMediaCount,
					 finishedLayerCount, totalLayerCount]);
		},

		updateMediaDownloadingStatus: function(featureType,
				finishedMediaCount, totalMediaCount,
				finishedLayerCount, totalLayerCount){

			console.log("updateMediaDownloadingStatus featureType = " + featureType
					+ ", finishedMediaCount = " + finishedMediaCount
					+ ", totalMediaCount = " + totalMediaCount
					+ ", finishedLayerCount = " + finishedLayerCount
					+ ", totalLayerCount = " + totalLayerCount);

			cordova.exec(null, null, "ArbiterCordova","updateMediaDownloadingStatus",
					[featureType, finishedMediaCount, totalMediaCount,
					 finishedLayerCount, totalLayerCount]);
		},

		createProjectTileSyncingStatus: function(percent){
			cordova.exec(null, null, "ArbiterCordova",
					"createProjectTileSyncingStatus", [percent]);
		},

		syncCompleted: function(){
			console.log("syncCompleted");
			cordova.exec(function(){

				Arbiter.Cordova.resetWebApp();

				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova", "syncCompleted", []);
		},

		syncFailed: function(e){

			console.log("syncFailed");

			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova",
					"syncFailed", [e]);
		},

		errorUpdatingAOI: function(e){

			cordova.exec(function(){
				Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
			}, null, "ArbiterCordova", "errorUpdatingAOI", [e]);
		},

		getState: function(){
			return state;
		},

		setState: function(_state){
			state = _state;

			if(isNeutral()){
				executeWaitingFuncs();
			}
		},

		addMediaToFeature: function(key, media, fileName){

			cordova.exec(null , null, "ArbiterCordova",
					"addMediaToFeature", [key, media, fileName]);

			Arbiter.Cordova.setState(Arbiter.Cordova.STATES.NEUTRAL);
		},

		updateUploadingVectorDataProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateUploadingVectorDataProgress", [finished, total]);
		},

		updateDownloadingVectorDataProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateDownloadingVectorDataProgress", [finished, total]);
		},

		showDownloadingSchemasProgress: function(count){
			cordova.exec(null, null, "ArbiterCordova",
					"showDownloadingSchemasProgress", [count]);
		},

		updateDownloadingSchemasProgress: function(finished, total){

			cordova.exec(null, null, "ArbiterCordova",
					"updateDownloadingSchemasProgress", [finished, total]);
		},

		dismissDownloadingSchemasProgress: function(){

			cordova.exec(null, null, "ArbiterCordova",
					"dismissDownloadingSchemasProgress", []);
		},

		alertGeolocationError: function(msg){

			cordova.exec(null, null, "ArbiterCordova",
					"alertGeolocationError", [msg]);
		},

		setMultiPartBtnsEnabled: function(enable, enableCollection){

			cordova.exec(null, null, "ArbiterCordova", "setMultiPartBtnsEnabled", [enable, enableCollection]);
		},

		confirmPartRemoval: function(onConfirm){

			cordova.exec(onConfirm, null, "ArbiterCordova", "confirmPartRemoval", []);
		},

		confirmGeometryRemoval: function(onConfirm){

			cordova.exec(onConfirm, null, "ArbiterCordova", "confirmGeometryRemoval", []);
		},

		hidePartButtons: function(){
			cordova.exec(null, null, "ArbiterCordova", "hidePartButtons", []);
		},

		reportLayersWithUnsupportedCRS: function(layers){
			cordova.exec(null, null, "ArbiterCordova", "reportLayersWithUnsupportedCRS", [layers]);
		}
	};
})();<|endoftext|>


<commit_before>import createClassComputed from 'ember-macro-helpers/create-class-computed';
import normalizeArrayKey from 'ember-macro-helpers/normalize-array-key';
import computed from 'ember-macro-helpers/computed';
import raw from 'ember-macro-helpers/raw';
import { module, test } from 'qunit';
import EmberObject from 'ember-object';
import { A as emberA } from 'ember-array/utils';
import compute from 'ember-macro-test-helpers/compute';
import WeakMap from 'ember-weakmap';
import destroy from '../helpers/destroy';

let PROPERTIES;
let filterBy;

module('Integration | create class computed', {
  beforeEach() {
    PROPERTIES = new WeakMap();

    filterBy = createClassComputed(
      [false, true, false],
      function(array, key, value) {
        if (!key) {
          PROPERTIES.set(this, array.split('.').reverse()[0]);
        }
        return computed(normalizeArrayKey(array, [key]), value, function(array, value) {
          if (array) {
            return emberA(emberA(array).filterBy(key || PROPERTIES.get(this), value));
          }
        });
      }
    );
  }
});

test('it initially calculates correctly', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 1);
});

test('it responds to array property value changes internally', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array property value changes externally', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array.@each.test', 'key', 'value'),
    properties: {
      array,
      value: 'val1'
    }
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array property value changes using raw array', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(array, raw('test'), raw('val1'))
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to property value changes using brace expansion', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy('obj.{array,key,value}'),
    properties: {
      obj: EmberObject.create({
        array,
        key: 'test',
        value: 'val2'
      })
    }
  });

  subject.set('obj.value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array length changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  array.pushObject(EmberObject.create({ test: 'val1' }));

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to property key changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test2',
      value: 'val1'
    }
  });

  subject.set('key', 'test');

  assert.equal(subject.get('computed.length'), 1);
});

test('it responds to property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val2'
    }
  });

  subject.set('value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: macros still compute inside', function(assert) {
  let array1 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);
  let array2 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed('innerKey', innerKey => innerKey ? array1 : array2), 'key', 'value'),
    properties: {
      innerKey: true,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 2);

  subject.set('innerKey', false);

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: it responds to array property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 1);

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: it responds to property key changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      array,
      key: 'test2',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 0);

  subject.set('key', 'test');

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: it responds to property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val2'
    }
  });

  assert.equal(subject.get('computed.length'), 0);

  subject.set('value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: macros still compute outside', function(assert) {
  let array1 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);
  let array2 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: computed(filterBy('array', 'key', 'value'), array => array),
    properties: {
      array: array1,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 2);

  subject.set('array', array2);

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: both macros are class computed', function(assert) {
  let array = emberA([
    EmberObject.create({ id: 1, test1: 'val1', test2: 'val1' }),
    EmberObject.create({ id: 2, test1: 'val2', test2: 'val1' }),
    EmberObject.create({ id: 3, test1: 'val2', test2: 'val2' }),
    EmberObject.create({ id: 3, test1: 'val1', test2: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(filterBy('array', 'key1', 'value1'), 'key2', 'value2'),
    properties: {
      array,
      key1: 'test1',
      key2: 'test2',
      value1: 'val1',
      value2: 'val1'
    }
  });

  assert.deepEqual(subject.get('computed').mapBy('id'), [1]);
});

test('it cleans up after destroy', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  destroy(subject, () => {
    array.pushObject(EmberObject.create({ test: 'val1' }));

    assert.ok(true);
  });
});
<commit_msg>fix test<commit_after>import createClassComputed from 'ember-macro-helpers/create-class-computed';
import normalizeArrayKey from 'ember-macro-helpers/normalize-array-key';
import computed from 'ember-macro-helpers/computed';
import raw from 'ember-macro-helpers/raw';
import { module, test } from 'qunit';
import EmberObject from 'ember-object';
import { A as emberA } from 'ember-array/utils';
import compute from 'ember-macro-test-helpers/compute';
import WeakMap from 'ember-weakmap';
import destroy from '../helpers/destroy';

let PROPERTIES;
let filterBy;

module('Integration | create class computed', {
  beforeEach() {
    PROPERTIES = new WeakMap();

    filterBy = createClassComputed(
      [false, true, false],
      function(array, key, value) {
        if (!key) {
          PROPERTIES.set(this, array.split('.').reverse()[0]);
        }
        return computed(normalizeArrayKey(array, [key]), value, function(array, value) {
          if (array) {
            return emberA(emberA(array).filterBy(key || PROPERTIES.get(this), value));
          }
        });
      }
    );
  }
});

test('it initially calculates correctly', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 1);
});

test('it responds to array property value changes internally', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array property value changes externally', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array.@each.test', 'key', 'value'),
    properties: {
      array,
      value: 'val1'
    }
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array property value changes using raw array', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(array, raw('test'), raw('val1'))
  });

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to property value changes using brace expansion', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy('obj.{array,key,value}'),
    properties: {
      obj: EmberObject.create({
        array,
        key: 'test',
        value: 'val2'
      })
    }
  });

  subject.set('obj.value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to array length changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  array.pushObject(EmberObject.create({ test: 'val1' }));

  assert.equal(subject.get('computed.length'), 2);
});

test('it responds to property key changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test2',
      value: 'val1'
    }
  });

  subject.set('key', 'test');

  assert.equal(subject.get('computed.length'), 1);
});

test('it responds to property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val2'
    }
  });

  subject.set('value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: macros still compute inside', function(assert) {
  let array1 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);
  let array2 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed('innerKey', innerKey => innerKey ? array1 : array2), 'key', 'value'),
    properties: {
      innerKey: true,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 2);

  subject.set('innerKey', false);

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: it responds to array property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 1);

  array.set('1.test', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: it responds to property key changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      array,
      key: 'test2',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 0);

  subject.set('key', 'test');

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: it responds to property value changes', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);

  let { subject } = compute({
    computed: filterBy(computed(() => array), 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val2'
    }
  });

  assert.equal(subject.get('computed.length'), 0);

  subject.set('value', 'val1');

  assert.equal(subject.get('computed.length'), 2);
});

test('composing: macros still compute outside', function(assert) {
  let array1 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val1' })
  ]);
  let array2 = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: computed(filterBy('array', 'key', 'value'), array => array),
    properties: {
      array: array1,
      key: 'test',
      value: 'val1'
    }
  });

  assert.equal(subject.get('computed.length'), 2);

  subject.set('array', array2);

  assert.equal(subject.get('computed.length'), 1);
});

test('composing: both macros are class computed', function(assert) {
  let array = emberA([
    EmberObject.create({ id: 1, test1: 'val1', test2: 'val1' }),
    EmberObject.create({ id: 2, test1: 'val2', test2: 'val1' }),
    EmberObject.create({ id: 3, test1: 'val2', test2: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy(filterBy('array', 'key1', 'value1'), 'key2', 'value2'),
    properties: {
      array,
      key1: 'test1',
      key2: 'test2',
      value1: 'val1',
      value2: 'val1'
    }
  });

  assert.deepEqual(subject.get('computed').mapBy('id'), [1]);

  subject.set('value1', 'val2');

  assert.deepEqual(subject.get('computed').mapBy('id'), [2]);

  subject.set('value2', 'val2');

  assert.deepEqual(subject.get('computed').mapBy('id'), [3]);
});

test('it cleans up after destroy', function(assert) {
  let array = emberA([
    EmberObject.create({ test: 'val1' }),
    EmberObject.create({ test: 'val2' })
  ]);

  let { subject } = compute({
    computed: filterBy('array', 'key', 'value'),
    properties: {
      array,
      key: 'test',
      value: 'val1'
    }
  });

  destroy(subject, () => {
    array.pushObject(EmberObject.create({ test: 'val1' }));

    assert.ok(true);
  });
});
<|endoftext|>


<commit_before>/**
 * matrix.js
 * http://github.com/sjkaliski/numbers.js
 *
 * Copyright 2012 Stephen Kaliski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var matrix = exports;

/**
 * Add two matrices together.  Matrices must be of same dimension.
 *
 * @param {Array} matrix A.
 * @param {Array} matrix B.
 * @return {Array} summed matrix.
 */
matrix.addition = function (arrA, arrB) {
  if ((arrA.length === arrB.length) && (arrA[0].length === arrB[0].length)) {
    var result = new Array(arrA.length);

    for (var i = 0; i < arrA.length; i++) {
      result[i] = new Array(arrA[i].length);

      for (var j = 0; j < arrA[i].length; j++) {
        result[i][j] = arrA[i][j] + arrB[i][j];
      }
    }

    return result;
  } else {
    throw new Error('Matrix mismatch');
  }
};

/**
 * Scalar multiplication on an matrix.
 *
 * @param {Array} matrix.
 * @param {Number} scalar.
 * @return {Array} updated matrix.
 */
matrix.scalar = function (arr, val) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      arr[i][j] = val * arr[i][j];
    }
  }

  return arr;
};

/**
 * Transpose a matrix.
 *
 * @param {Array} matrix.
 * @return {Array} transposed matrix.
 */
matrix.transpose = function (arr) {
  var result = new Array(arr[0].length);

  for (var i = 0; i < arr[0].length; i++) {
    result[i] = new Array(arr.length);

    for (var j = 0; j < arr.length; j++) {
      result[i][j] = arr[j][i];
    }
  }

  return result;
};

/**
 * Create an identity matrix of dimension n x n.
 *
 * @param {Number} dimension of the identity array to be returned.
 * @return {Array} n x n identity matrix.
 */
matrix.identity = function (n) {
  var result = new Array(n);
  for (var i = 0; i < n ; i++) {
    result[i] = new Array(n);
    for (var j = 0; j < n; j++) {
      result[i][j] = (i === j) ? 1 : 0;
    }
  }

  return result;
};

/**
 * Evaluate dot product of two vectors.  Vectors must be of same length.
 *
 * @param {Array} vector.
 * @param {Array} vector.
 * @return {Array} dot product.
 */
matrix.dotproduct = function (vectorA, vectorB) {
  if (vectorA.length === vectorB.length) {
    var result = 0;
    for (var i = 0; i < vectorA.length; i++) {
      result += vectorA[i] * vectorB[i];
    }
    return result;
  } else {
    throw new Error("Vector mismatch");
  }
};

/**
 * Multiply two matrices. They must abide by standard matching.
 *
 * e.g. A x B = (m x n) x (n x m), where n, m are integers who define
 * the dimensions of matrices A, B.
 *
 * @param {Array} matrix.
 * @param {Array} matrix.
 * @return {Array} result of multiplied matrices.
 */
matrix.multiply = function (arrA, arrB) {
  if (arrA[0].length === arrB.length) {
    var result = new Array(arrA.length);

    for (var x = 0; x < arrA.length; x++) {
      result[x] = new Array(arrB[0].length);
    }

    var arrB_T = matrix.transpose(arrB);

    for (var i = 0; i < result.length; i++) {
      for (var j = 0; j < result[i].length; j++) {
        result[i][j] = matrix.dotproduct(arrA[i],arrB_T[j]);
      }
    }
    return result;
  } else {
    throw new Error("Array mismatch");
  }
};

/**
 * Evaluate determinate of matrix.
 * Runtime: O(n!)
 *
 * @param {Array} matrix.
 * @return {Number} determinant.
 */
matrix.determinant = function (m) {
  var numRow = m.length;
  var numCol = m[0].length;
  var det = 0;
  var row, col;
  var diagLeft, diagRight;

  if (numRow !== numCol) {
    throw new Error("Not a square matrix.")
  }

  if (numRow === 1) {
    return m[0][0];
  }
  else if (numRow === 2) {
    return m[0][0] * m[1][1] - m[0][1] * m[1][0];
  }

  for (col = 0; col < numCol; col++) {
    diagLeft = m[0][col];
    diagRight = m[0][col];

    for( row=1; row < numRow; row++ ) {
      diagRight *= m[row][(((col + row) % numCol) + numCol) % numCol];
      diagLeft *= m[row][(((col - row) % numCol) + numCol) % numCol];
    }

    det += diagRight - diagLeft;
  }

  return det;
};

/**
 * Rotate a two dimensional vector by degree.
 *
 * @param {Array} point.
 * @param {Number} degree.
 * @param {String} direction - clockwise or counterclockwise.
 * @return {Array} vector.
 */
matrix.rotate = function (point, degree, direction) {
  if (point.length === 2) {
    var negate = direction === 'clockwise' ? -1 : 1;
    var radians = degree * (Math.PI / 180);

    var transformation = [
      [Math.cos(radians), -1 * negate * Math.sin(radians)],
      [negate * Math.sin(radians), Math.cos(radians)]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Scale a two dimensional vector by scale factor x and scale factor y.
 *
 * @param {Array} point.
 * @param {Number} sx.
 * @param {Number} sy.
 * @return {Array} vector.
 */
matrix.scale = function (point, sx, sy) {
  if (point.length === 2) {

    var transformation = [
      [sx, 0],
      [0, sy]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Shear a two dimensional vector by shear factor k.
 *
 * @param {Array} point.
 * @param {Number} k.
 * @param {String} direction - xaxis or yaxis.
 * @return {Array} vector.
 */
matrix.shear = function (point, k, direction) {
  if (point.length === 2) {
    var xplaceholder = direction === 'xaxis' ? k : 0;
    var yplaceholder = direction === 'yaxis' ? k : 0;

    var transformation = [
      [1, xplaceholder],
      [yplaceholder, 1]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Perform an affine transformation on the given vector.
 *
 * @param {Array} point.
 * @param {Number} tx.
 * @param {Number} ty.
 * @return {Array} vector.
 */
matrix.affine = function (point, tx, ty) {
  if (point.length === 2) {

    var transformation = [
      [1, 0, tx],
      [0, 1, ty],
      [0, 0, 1 ]
    ];

    var newpoint = [
      [point[0][0]],
      [point[1][0]],
      [1]
    ];

    var transformed = matrix.multiply(transformation, newpoint);

    return [
      [transformed[0][0]],
      [transformed[1][0]]
    ];

  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Scales a row of a matrix by a factor and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row.
 * @param {Number} scale.
 */
matrix.rowScale = function (m, row, scale) {
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === row) {
        result[i][j] = scale * m[i][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }

  return result;
};

/**
 * Swaps two rows of a matrix  and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row1.
 * @param {Number} row2.
 */
matrix.rowSwitch = function (m, row1, row2) {
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === row1) {
        result[i][j] = m[row2][j];
      } else if (i === row2) {
        result[i][j] = m[row1][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }
  return result;
};

/**
 * Adds a multiple of one row to another row
 * in a matrix and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row1.
 * @param {Number} row2.
 */
matrix.rowAddMultiple = function (m, from, to, scale){
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === to) {
        result[to][j] = m[to][j] + scale * m[from][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }

  return result;
};
<commit_msg>Fixed error from merge conflict<commit_after>/**
 * matrix.js
 * http://github.com/sjkaliski/numbers.js
 *
 * Copyright 2012 Stephen Kaliski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var matrix = exports;

/**
 * Add two matrices together.  Matrices must be of same dimension.
 *
 * @param {Array} matrix A.
 * @param {Array} matrix B.
 * @return {Array} summed matrix.
 */
matrix.addition = function (arrA, arrB) {
  if ((arrA.length === arrB.length) && (arrA[0].length === arrB[0].length)) {
    var result = new Array(arrA.length);

    for (var i = 0; i < arrA.length; i++) {
      result[i] = new Array(arrA[i].length);

      for (var j = 0; j < arrA[i].length; j++) {
        result[i][j] = arrA[i][j] + arrB[i][j];
      }
    }

    return result;
  } else {
    throw new Error('Matrix mismatch');
  }
};

/**
 * Scalar multiplication on an matrix.
 *
 * @param {Array} matrix.
 * @param {Number} scalar.
 * @return {Array} updated matrix.
 */
matrix.scalar = function (arr, val) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      arr[i][j] = val * arr[i][j];
    }
  }

  return arr;
};

/**
 * Transpose a matrix.
 *
 * @param {Array} matrix.
 * @return {Array} transposed matrix.
 */
matrix.transpose = function (arr) {
  var result = new Array(arr[0].length);

  for (var i = 0; i < arr[0].length; i++) {
    result[i] = new Array(arr.length);

    for (var j = 0; j < arr.length; j++) {
      result[i][j] = arr[j][i];
    }
  }

  return result;
};

/**
 * Create an identity matrix of dimension n x n.
 *
 * @param {Number} dimension of the identity array to be returned.
 * @return {Array} n x n identity matrix.
 */
matrix.identity = function (n) {
  var result = new Array(n);
  for (var i = 0; i < n ; i++) {
    result[i] = new Array(n);
    for (var j = 0; j < n; j++) {
      result[i][j] = (i === j) ? 1 : 0;
    }
  }

  return result;
};

/**
 * Evaluate dot product of two vectors.  Vectors must be of same length.
 *
 * @param {Array} vector.
 * @param {Array} vector.
 * @return {Array} dot product.
 */
matrix.dotproduct = function (vectorA, vectorB) {
  if (vectorA.length === vectorB.length) {
    var result = 0;
    for (var i = 0; i < vectorA.length; i++) {
      result += vectorA[i] * vectorB[i];
    }
    return result;
  } else {
    throw new Error("Vector mismatch");
  }
};

/**
 * Multiply two matrices. They must abide by standard matching.
 *
 * e.g. A x B = (m x n) x (n x m), where n, m are integers who define
 * the dimensions of matrices A, B.
 *
 * @param {Array} matrix.
 * @param {Array} matrix.
 * @return {Array} result of multiplied matrices.
 */
matrix.multiply = function (arrA, arrB) {
  if (arrA[0].length === arrB.length) {
    var result = new Array(arrA.length);

    for (var x = 0; x < arrA.length; x++) {
      result[x] = new Array(arrB[0].length);
    }

    var arrB_T = matrix.transpose(arrB);

    for (var i = 0; i < result.length; i++) {
      for (var j = 0; j < result[i].length; j++) {
        result[i][j] = matrix.dotproduct(arrA[i],arrB_T[j]);
      }
    }
    return result;
  } else {
    throw new Error("Array mismatch");
  }
};

/**
 * Evaluate determinate of matrix.  Expect speed
 * degradation for matrices over 4x4.
 *
 * @param {Array} matrix.
 * @return {Number} determinant.
 */
matrix.determinant = function (m) {
  var numRow = m.length;
  var numCol = m[0].length;
  var det = 0;
  var row, col;
  var diagLeft, diagRight;

  if (numRow !== numCol) {
    throw new Error("Not a square matrix.")
  }

  if (numRow === 1) {
    return m[0][0];
  }
  else if (numRow === 2) {
    return m[0][0] * m[1][1] - m[0][1] * m[1][0];
  }

  for (col = 0; col < numCol; col++) {
    diagLeft = m[0][col];
    diagRight = m[0][col];

    for( row=1; row < numRow; row++ ) {
      diagRight *= m[row][(((col + row) % numCol) + numCol) % numCol];
      diagLeft *= m[row][(((col - row) % numCol) + numCol) % numCol];
    }

    det += diagRight - diagLeft;
  }

  return det;
};

/**
 * Rotate a two dimensional vector by degree.
 *
 * @param {Array} point.
 * @param {Number} degree.
 * @param {String} direction - clockwise or counterclockwise.
 * @return {Array} vector.
 */
matrix.rotate = function (point, degree, direction) {
  if (point.length === 2) {
    var negate = direction === 'clockwise' ? -1 : 1;
    var radians = degree * (Math.PI / 180);

    var transformation = [
      [Math.cos(radians), -1 * negate * Math.sin(radians)],
      [negate * Math.sin(radians), Math.cos(radians)]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Scale a two dimensional vector by scale factor x and scale factor y.
 *
 * @param {Array} point.
 * @param {Number} sx.
 * @param {Number} sy.
 * @return {Array} vector.
 */
matrix.scale = function (point, sx, sy) {
  if (point.length === 2) {

    var transformation = [
      [sx, 0],
      [0, sy]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Shear a two dimensional vector by shear factor k.
 *
 * @param {Array} point.
 * @param {Number} k.
 * @param {String} direction - xaxis or yaxis.
 * @return {Array} vector.
 */
matrix.shear = function (point, k, direction) {
  if (point.length === 2) {
    var xplaceholder = direction === 'xaxis' ? k : 0;
    var yplaceholder = direction === 'yaxis' ? k : 0;

    var transformation = [
      [1, xplaceholder],
      [yplaceholder, 1]
    ];

    return matrix.multiply(transformation, point);
  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Perform an affine transformation on the given vector.
 *
 * @param {Array} point.
 * @param {Number} tx.
 * @param {Number} ty.
 * @return {Array} vector.
 */
matrix.affine = function (point, tx, ty) {
  if (point.length === 2) {

    var transformation = [
      [1, 0, tx],
      [0, 1, ty],
      [0, 0, 1 ]
    ];

    var newpoint = [
      [point[0][0]],
      [point[1][0]],
      [1]
    ];

    var transformed = matrix.multiply(transformation, newpoint);

    return [
      [transformed[0][0]],
      [transformed[1][0]]
    ];

  } else {
    throw new Error('Only two dimensional operations are supported at this time');
  }
};

/**
 * Scales a row of a matrix by a factor and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row.
 * @param {Number} scale.
 */
matrix.rowScale = function (m, row, scale) {
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === row) {
        result[i][j] = scale * m[i][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }

  return result;
};

/**
 * Swaps two rows of a matrix  and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row1.
 * @param {Number} row2.
 */
matrix.rowSwitch = function (m, row1, row2) {
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === row1) {
        result[i][j] = m[row2][j];
      } else if (i === row2) {
        result[i][j] = m[row1][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }
  return result;
};

/**
 * Adds a multiple of one row to another row
 * in a matrix and returns the updated matrix.
 * Used in row reduction functions.
 *
 * @param {Array} matrix.
 * @param {Number} row1.
 * @param {Number} row2.
 */
matrix.rowAddMultiple = function (m, from, to, scale){
  var result = new Array(m.length);

  for (var i = 0; i < m.length; i++) {
    result[i] = new Array(m[i].length);

    for (var j = 0; j < m[i].length; j++) {
      if (i === to) {
        result[to][j] = m[to][j] + scale * m[from][j];
      } else {
        result[i][j] = m[i][j];
      }
    }
  }

  return result;
};
<|endoftext|>


<commit_before>//LOADER
//******

function loader(){
	var topBinding = this;
	this.params = {
		GoogleFontListLoaded: false,
		GoogleFontsLoaded: false,
		genomeLoaded: false,
		genomeTranscribed: false,
		contentFilled: true,
		cssApplied: false
	}

	if(googleFontList) { this.params["GoogleFontsLoaded"]=true };

	this.setParamLoaded = function(param) {
		this.params[param] = true;

		$.event.trigger({
			type: param
		});

		triggerSweep();

		if(allLoaded()) {
			$.event.trigger({
				type: 'loaderFinished'
			});
		}
	};

	this.unsetParamLoaded = function(param) {
		this.params[param] = false;
	};

	this.isLoaded = function(param) {
		return this.params[param]
	}

	function allLoaded () {
		test = true;
		for(param in this.params) {
			test = test && this.params[param];
		}
		return test;
	}

	function triggerSweep() {
		if((topBinding.params["GoogleFontListLoaded"] && topBinding.params["genomeLoaded"]) && ( ! topBinding.params["genomeTranscribed"])) {
			$.event.trigger({
				type: "requestTranscribe"
			});
		}
	};

	//things to initialize here
	loadGoogleFontList();
};

function loadGoogleFontList() {
		$.getJSON("/lib/js/googleFonts.json",function(response){
			googleFontList = response;
			$.event.trigger({
				type: "paramLoaded",
				param: "GoogleFontListLoaded"
			});
		});
};

function loadGoogleFonts(familyNameArray) {
	var cleanArray = new Array()
	for (item in familyNameArray) {
		if(typeof(familyNameArray[item]) != "undefined") {
			cleanArray.push(familyNameArray[item]);
		}
	};

	//asynchronous loader
	WebFontConfig = {
		google: {families: cleanArray},
		timeout: 500,
		active: function(){
			$.event.trigger({
				type: "paramLoaded",
				param: "GoogleFontsLoaded"
			});
		}

	};
	(function() {
		var wf = document.createElement('script');
		wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
			'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
		wf.type = 'text/javascript';
		wf.async = 'true';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(wf, s);
  	})();
};<commit_msg>updated webfont loader<commit_after>//LOADER
//******

function loader(){
	var topBinding = this;
	this.params = {
		GoogleFontListLoaded: false,
		GoogleFontsLoaded: false,
		genomeLoaded: false,
		genomeTranscribed: false,
		contentFilled: true,
		cssApplied: false
	}

	if(googleFontList) { this.params["GoogleFontsLoaded"]=true };

	this.setParamLoaded = function(param) {
		this.params[param] = true;

		$.event.trigger({
			type: param
		});

		triggerSweep();

		if(allLoaded()) {
			$.event.trigger({
				type: 'loaderFinished'
			});
		}
	};

	this.unsetParamLoaded = function(param) {
		this.params[param] = false;
	};

	this.isLoaded = function(param) {
		return this.params[param]
	}

	function allLoaded () {
		test = true;
		for(param in this.params) {
			test = test && this.params[param];
		}
		return test;
	}

	function triggerSweep() {
		if((topBinding.params["GoogleFontListLoaded"] && topBinding.params["genomeLoaded"]) && ( ! topBinding.params["genomeTranscribed"])) {
			$.event.trigger({
				type: "requestTranscribe"
			});
		}
	};

	//things to initialize here
	loadGoogleFontList();
};

function loadGoogleFontList() {
		$.getJSON("/lib/js/googleFonts.json",function(response){
			googleFontList = response;
			$.event.trigger({
				type: "paramLoaded",
				param: "GoogleFontListLoaded"
			});
		});
};

function loadGoogleFonts(familyNameArray) {
	var cleanArray = new Array()
	for (item in familyNameArray) {
		if(typeof(familyNameArray[item]) != "undefined") {
			cleanArray.push(familyNameArray[item]);
		}
	};

	//asynchronous loader
	WebFontConfig = {
		google: {families: cleanArray},
		timeout: 500,
		active: function(){
			$.event.trigger({
				type: "paramLoaded",
				param: "GoogleFontsLoaded"
			});
		}

	};
	(function() {
		var wf = document.createElement('script');
		wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
			'://ajax.googleapis.com/ajax/libs/webfont/1.4.10/webfont.js';
		wf.type = 'text/javascript';
		wf.async = 'true';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(wf, s);
  	})();
};<|endoftext|>