<commit_before>var file = require("file"),
    os = require("os")
    objj = require("./objj");

require("objj/regexp-rhino-patch");

var OBJJ_PREPROCESSOR_DEBUG_SYMBOLS   = exports.OBJJ_PREPROCESSOR_DEBUG_SYMBOLS   = objj.OBJJ_PREPROCESSOR_DEBUG_SYMBOLS;
var OBJJ_PREPROCESSOR_TYPE_SIGNATURES = exports.OBJJ_PREPROCESSOR_TYPE_SIGNATURES = objj.OBJJ_PREPROCESSOR_TYPE_SIGNATURES;
var OBJJ_PREPROCESSOR_PREPROCESS      = exports.OBJJ_PREPROCESSOR_PREPROCESS      = 1 << 10;
var OBJJ_PREPROCESSOR_COMPRESS        = exports.OBJJ_PREPROCESSOR_COMPRESS        = 1 << 11;
var OBJJ_PREPROCESSOR_SYNTAX          = exports.OBJJ_PREPROCESSOR_SYNTAX          = 1 << 12;

var SHRINKSAFE_PATH = file.join(objj.OBJJ_HOME, "shrinksafe", "shrinksafe.jar"),
    RHINO_PATH = file.join(objj.OBJJ_HOME, "shrinksafe", "js.jar")

function compress(/*String*/ aCode, /*Object*/ flags, /*String*/ tmpFile)
{
    file.write(tmpFile, aCode, { charset:"UTF-8" });

    return os.command(["java", "-Dfile.encoding=UTF-8", "-classpath", [RHINO_PATH, SHRINKSAFE_PATH].join(":"), "org.dojotoolkit.shrinksafe.Main", tmpFile]);
}

exports.preprocess = function(inFile, outFile, flags, gccArgs)
{
    with(objj)
    {

    print("Statically Preprocessing " + inFile);

    if (flags === undefined)
        flags = OBJJ_PREPROCESSOR_PREPROCESS | OBJJ_PREPROCESSOR_SYNTAX;

    var shouldObjjPreprocess = flags & OBJJ_PREPROCESSOR_PREPROCESS,
        shouldCheckSyntax = flags & OBJJ_PREPROCESSOR_SYNTAX,
        shouldCompress = flags & OBJJ_PREPROCESSOR_COMPRESS;

    // FIXME: figure out why this doesn't work on Windows/Cygwin
    //var tmpFile = java.io.File.createTempFile("OBJJC", "");
    var tmpFile = new java.io.File(outFile + ".tmp");
    tmpFile.deleteOnExit();
    tmpFile = tmpFile.getAbsolutePath();

    // -E JUST preprocess.
    // -x c Interpret language as C -- closest thing to JavaScript.
    // -P Don't generate #line directives
    var gccComponents = ["gcc"]
        .concat("-E", "-x", "c", "-P", inFile)
        .concat(gccArgs || [])
        .concat("-o", shouldObjjPreprocess ? tmpFile : outFile);

    os.system(gccComponents);

    if (!shouldObjjPreprocess)
        return;

    // Read file and preprocess it.
    var fileContents = file.read(tmpFile, { charset: "UTF-8" });

    // Preprocess contents into fragments.
    var fragments = objj_preprocess(fileContents, { path : "/x" }, { path: file.basename(inFile) }, flags),
        preprocessed = "";

    // Writer preprocessed fragments out.
    for (var index = 0; index < fragments.length; index++)
    {
        var fragment = fragments[index];

        if (IS_FILE(fragment))
            preprocessed += (IS_LOCAL(fragment) ? MARKER_IMPORT_LOCAL : MARKER_IMPORT_STD) + ';' + GET_PATH(fragment).length + ';' + GET_PATH(fragment);
        else
        {
            var code = GET_CODE(fragment);

            if (shouldCheckSyntax)
            {
                try
                {
                    new Function(GET_CODE(fragment));
                }
                catch (e)
                {
                    var lines = code.split("\n"),
                        PAD = 3;

                    print("Syntax error in "+GET_FILE(fragment).path+
                            " on preprocessed line number "+e.lineNumber+"\n"+
                            "\t"+lines.slice(Math.max(0, e.lineNumber - 1 - PAD), e.lineNumber+PAD).join("\n\t"));

                    os.exit(1);
                }
            }

            if (shouldCompress)
            {
                code = compress("function(){" + code + '}', 0, tmpFile);

                code = code.substr("function(){".length, code.length - "function(){};\n\n".length);
            }

            preprocessed += MARKER_CODE + ';' + code.length + ';' + code;
        }
    }

    // Write file.
    file.write(outFile, preprocessed, { charset: "UTF-8" });

    }
}

exports.main = function(args)
{
    // FIXME: ARGS
    args.shift();

    var filePaths = [],
        outFilePaths = [],

        index = 0,
        count = args.length,

        gccArgs = [],

        flags = OBJJ_PREPROCESSOR_PREPROCESS | OBJJ_PREPROCESSOR_SYNTAX;

    for (; index < count; ++index)
    {
        var argument = args[index];

        if (argument === "-o")
        {
            if (++index < count)
                outFilePaths.push(args[index]);
        }

        else if (argument.indexOf("-D") === 0)
            gccArgs.push(argument)

        else if (argument.indexOf("-U") === 0)
            gccArgs.push(argument);

        else if (argument.indexOf("-E") === 0)
            flags &= ~OBJJ_PREPROCESSOR_PREPROCESS;

        else if (argument.indexOf("-S") === 0)
            flags &= ~OBJJ_PREPROCESSOR_SYNTAX;

        else if (argument.indexOf("-g") === 0)
            flags |= OBJJ_PREPROCESSOR_DEBUG_SYMBOLS;

        else if (argument.indexOf("-O") === 0)
            flags |= OBJJ_PREPROCESSOR_COMPRESS;

        else
            filePaths.push(argument);
    }

    for (index = 0, count = filePaths.length; index < count; ++index)
        exports.preprocess(filePaths[index], outFilePaths[index], flags, gccArgs);
}

if (require.main == module.id)
    exports.main(system.args);<commit_msg>Update to support new narwhal.<commit_after>var FILE = require("file"),
    OS = require("os"),
    objj = require("./objj"),
    objj_preprocess = objj.objj_preprocess,
    IS_FILE = objj.IS_FILE,
    GET_CODE = objj.GET_CODE,
    IS_LOCAL = objj.IS_LOCAL,
    MARKER_IMPORT_STD = objj.MARKER_IMPORT_STD,
    MARKER_IMPORT_LOCAL = objj.MARKER_IMPORT_LOCAL,
    MARKER_CODE = objj.MARKER_CODE,
    GET_PATH = objj.GET_PATH;

require("objj/regexp-rhino-patch");

var OBJJ_PREPROCESSOR_DEBUG_SYMBOLS   = exports.OBJJ_PREPROCESSOR_DEBUG_SYMBOLS   = objj.OBJJ_PREPROCESSOR_DEBUG_SYMBOLS;
var OBJJ_PREPROCESSOR_TYPE_SIGNATURES = exports.OBJJ_PREPROCESSOR_TYPE_SIGNATURES = objj.OBJJ_PREPROCESSOR_TYPE_SIGNATURES;
var OBJJ_PREPROCESSOR_PREPROCESS      = exports.OBJJ_PREPROCESSOR_PREPROCESS      = 1 << 10;
var OBJJ_PREPROCESSOR_COMPRESS        = exports.OBJJ_PREPROCESSOR_COMPRESS        = 1 << 11;
var OBJJ_PREPROCESSOR_SYNTAX          = exports.OBJJ_PREPROCESSOR_SYNTAX          = 1 << 12;

var SHRINKSAFE_PATH = FILE.join(objj.OBJJ_HOME, "shrinksafe", "shrinksafe.jar"),
    RHINO_PATH = FILE.join(objj.OBJJ_HOME, "shrinksafe", "js.jar")

function compress(/*String*/ aCode, /*String*/ FIXME)
{
    // FIXME: figure out why this doesn't work on Windows/Cygwin
    //var tmpFile = java.io.File.createTempFile("OBJJC", "");
    var tmpFile = new java.io.File(FIXME + ".tmp");
    tmpFile.deleteOnExit();
    tmpFile = tmpFile.getAbsolutePath();

    FILE.write(tmpFile, aCode, { charset:"UTF-8" });

    return OS.command(["java", "-Dfile.encoding=UTF-8", "-classpath", [RHINO_PATH, SHRINKSAFE_PATH].join(":"), "org.dojotoolkit.shrinksafe.Main", tmpFile]);
}

exports.preprocess = function(inFile, outFile, flags, gccArgs)
{
    print("Statically Preprocessing " + inFile);

    if (flags === undefined)
        flags = OBJJ_PREPROCESSOR_PREPROCESS | OBJJ_PREPROCESSOR_SYNTAX;

    var shouldObjjPreprocess = flags & OBJJ_PREPROCESSOR_PREPROCESS,
        shouldCheckSyntax = flags & OBJJ_PREPROCESSOR_SYNTAX,
        shouldCompress = flags & OBJJ_PREPROCESSOR_COMPRESS;

    var gccCommand = "gcc -E -x c -P " + (gccArgs.join(" ") || "") + " " + inFile;

    if (!shouldObjjPreprocess)
    {
        OS.system(gccCommand + " -o" + outFile);
        return;
    }

    var gcc = OS.popen(gccCommand);

    // Read file and preprocess it.
    var fileContents = "",
        chunk = "";

    while (chunk = gcc.stdout.read())
        fileContents += chunk;

    // Preprocess contents into fragments.
    var fragments = objj_preprocess(fileContents, { path : "/x" }, { path: FILE.basename(inFile) }, flags),
        preprocessed = "";

    // Writer preprocessed fragments out.
    for (var index = 0; index < fragments.length; index++)
    {
        var fragment = fragments[index];

        if (IS_FILE(fragment))
            preprocessed += (IS_LOCAL(fragment) ? MARKER_IMPORT_LOCAL : MARKER_IMPORT_STD) + ';' + GET_PATH(fragment).length + ';' + GET_PATH(fragment);
        else
        {
            var code = GET_CODE(fragment);

            if (shouldCheckSyntax)
            {
                try
                {
                    new Function(GET_CODE(fragment));
                }
                catch (e)
                {
                    var lines = code.split("\n"),
                        PAD = 3;

                    print("Syntax error in "+GET_FILE(fragment).path+
                            " on preprocessed line number "+e.lineNumber+"\n"+
                            "\t"+lines.slice(Math.max(0, e.lineNumber - 1 - PAD), e.lineNumber+PAD).join("\n\t"));

                    OS.exit(1);
                }
            }

            if (shouldCompress)
            {
                code = compress("function(){" + code + '}', outFile);

                code = code.substr("function(){".length, code.length - "function(){};\n\n".length);
            }

            preprocessed += MARKER_CODE + ';' + code.length + ';' + code;
        }
    }

    // Write file.
    FILE.write(outFile, preprocessed, { charset: "UTF-8" });
}

exports.main = function(args)
{
    // FIXME: ARGS
    args.shift();

    var filePaths = [],
        outFilePaths = [],

        index = 0,
        count = args.length,

        gccArgs = [],

        flags = OBJJ_PREPROCESSOR_PREPROCESS | OBJJ_PREPROCESSOR_SYNTAX;

    for (; index < count; ++index)
    {
        var argument = args[index];

        if (argument === "-o")
        {
            if (++index < count)
                outFilePaths.push(args[index]);
        }

        else if (argument.indexOf("-D") === 0)
            gccArgs.push(argument)

        else if (argument.indexOf("-U") === 0)
            gccArgs.push(argument);

        else if (argument.indexOf("-E") === 0)
            flags &= ~OBJJ_PREPROCESSOR_PREPROCESS;

        else if (argument.indexOf("-S") === 0)
            flags &= ~OBJJ_PREPROCESSOR_SYNTAX;

        else if (argument.indexOf("-g") === 0)
            flags |= OBJJ_PREPROCESSOR_DEBUG_SYMBOLS;

        else if (argument.indexOf("-O") === 0)
            flags |= OBJJ_PREPROCESSOR_COMPRESS;

        else
            filePaths.push(argument);
    }

    for (index = 0, count = filePaths.length; index < count; ++index)
        exports.preprocess(filePaths[index], outFilePaths[index], flags, gccArgs);
}

if (require.main == module.id)
    exports.main(system.args);<|endoftext|>


<commit_before>'use strict'

var Bench = require('bench')
var Seneca = require('seneca')
var Transport = require('./')

var color = function () {
  this.add('color:red', function (args, callback) {
    callback(null, { hex: '#FF0000' })
  })
}

var publishedServer = Seneca({ log: 'silent', default_plugins: { tranport: true }, transport: { port: 9998 } })
  .use(color).listen()
var publishedClient = Seneca({ log: 'silent', default_plugins: { tranport: true }, transport: { port: 9998 } })
  .client()

var localServer = Seneca({ log: 'silent', default_plugins: { tranport: false }, transport: { port: 9999 } })
  .use(color).use(Transport).listen()
var localClient = Seneca({ log: 'silent', default_plugins: { tranport: false }, transport: { port: 9999 } })
  .use(Transport).client()

exports.compare = {
  'published transport': function (done) {
    publishedClient.act('color:red', done)
  },
  'local transport': function (done) {
    localClient.act('color:red', done)
  }
}

Bench.runMain()

// Baseline before refactor is 2872 ms on mid 2015 retina pro
<commit_msg>Fix bench style<commit_after>'use strict'

var Bench = require('bench')
var Seneca = require('seneca')
var Transport = require('./')

var color = function () {
  this.add('color:red', function (args, callback) {
    callback(null, { hex: '#FF0000' })
  })
}

Seneca({ log: 'silent', default_plugins: { tranport: true }, transport: { port: 9998 } }).use(color).listen()
var publishedClient = Seneca({ log: 'silent', default_plugins: { tranport: true }, transport: { port: 9998 } })
  .client()

Seneca({ log: 'silent', default_plugins: { tranport: false }, transport: { port: 9999 } }).use(color).use(Transport).listen()
var localClient = Seneca({ log: 'silent', default_plugins: { tranport: false }, transport: { port: 9999 } })
  .use(Transport).client()

exports.compare = {
  'published transport': function (done) {
    publishedClient.act('color:red', done)
  },
  'local transport': function (done) {
    localClient.act('color:red', done)
  }
}

Bench.runMain()
<|endoftext|>


<commit_before>(function($){

  /* Adapted from http://www.kryogenix.org/code/browser/searchhi/ */
  $.fn.highlightText = function(text, className) {
    function highlight(node) {
      if (node.nodeType == 3) { // Node.TEXT_NODE
        var val = node.nodeValue;
        var pos = val.toLowerCase().indexOf(text);
        if (pos >= 0 && !$(node.parentNode).hasClass(className)) {
          var span = document.createElement("span");
          span.className = className;
          var txt = document.createTextNode(val.substr(pos, text.length));
          span.appendChild(txt);
          node.parentNode.insertBefore(span, node.parentNode.insertBefore(
            document.createTextNode(val.substr(pos + text.length)),
              node.nextSibling));
          node.nodeValue = val.substr(0, pos);
        }
      } else if (!$(node).is("button, select, textarea")) {
        $.each(node.childNodes, function() { highlight(this) });
      }
    }
    return this.each(function() { highlight(this) });
  }

  $(document).ready(function() {
    var elems = $(".searchable");
    if (!elems.length) return;

    function getSearchTerms(url) {
      if (url.indexOf("?") == -1) return [];
      var params = url.substr(url.indexOf("?") + 1).split("&");
      for (var p in params) {
        var param = params[p].split("=");
        if (param.length < 2) continue;
        if (param[0] == "q" || param[0] == "p") {// q= for Google, p= for Yahoo
          var query = decodeURIComponent(param[1].replace(/\+/g, " "));
          if (query[0] == "!") query = query.slice(1);
          var terms = [];
          $.each(query.split(/(".*?"|'.*?'|\s+)/), function() {
            if (terms.length < 10) {
              term = this.replace(/^\s+$/, "")
                         .replace(/^['"]/, "")
                         .replace(/['"]$/, "");
              if (term.length >= 3)
                terms.push(term);
            }
          });
          return terms;
        }
      }
      return [];
    }

    var terms = getSearchTerms(document.URL);
    if (!terms.length) terms = getSearchTerms(document.referrer);
    $.each(terms, function(idx) {
      elems.highlightText(this.toLowerCase(), "searchword" + (idx % 5));
    });
  });

})(jQuery);
<commit_msg>0.13dev: Scroll to first (or last) URL fragment identifier search `#/term` (or `#?term`) occurrence. Append `/i` for case insensitive search.<commit_after>(function($){

  /* Adapted from http://www.kryogenix.org/code/browser/searchhi/ */
  $.fn.highlightText = function(text, className, caseSensitive) {
    function highlight(node) {
      if (node.nodeType == 3) { // Node.TEXT_NODE
        var val = node.nodeValue;
        var pos = (caseSensitive ? val : val.toLowerCase()).indexOf(text);
        if (pos >= 0 && !$(node.parentNode).hasClass(className)) {
          var span = document.createElement("span");
          span.className = className;
          var txt = document.createTextNode(val.substr(pos, text.length));
          span.appendChild(txt);
          node.parentNode.insertBefore(span, node.parentNode.insertBefore(
            document.createTextNode(val.substr(pos + text.length)),
              node.nextSibling));
          node.nodeValue = val.substr(0, pos);
        }
      } else if (!$(node).is("button, select, textarea")) {
        $.each(node.childNodes, function() { highlight(this) });
      }
    }
    return this.each(function() { highlight(this) });
  }

  $(document).ready(function() {
    var elems = $(".searchable");
    if (!elems.length) return;

    function getSearchTerms(url) {
      if (url.indexOf("?") == -1) return [];
      var params = url.substr(url.indexOf("?") + 1).split("&");
      for (var p in params) {
        var param = params[p].split("=");
        if (param.length < 2) continue;
        if (param[0] == "q" || param[0] == "p") {// q= for Google, p= for Yahoo
          var query = decodeURIComponent(param[1].replace(/\+/g, " "));
          if (query[0] == "!") query = query.slice(1);
          var terms = [];
          $.each(query.split(/(".*?"|'.*?'|\s+)/), function() {
            if (terms.length < 10) {
              term = this.replace(/^\s+$/, "")
                         .replace(/^['"]/, "")
                         .replace(/['"]$/, "");
              if (term.length >= 3)
                terms.push(term);
            }
          });
          return terms;
        }
      }
      return [];
    }

    var terms = getSearchTerms(document.URL);
    if (!terms.length) terms = getSearchTerms(document.referrer);
    if (terms.length) {
      $.each(terms, function(idx) {
        elems.highlightText(this.toLowerCase(), "searchword" + (idx % 5));
      });
    } else {
      function scrollToHashSearchMatch() {
        var h = window.location.hash;
        var direction = h[1];
        var case_insensitive = h.match(/\/i$/);
        if (direction == '/' || direction == '?') {
          var hterm = h.substr(2);
          if (case_insensitive)
            hterm = hterm.substr(0, hterm.length - 2).toLowerCase();
          $('.searchword0').each(function() {
            $(this).after($(this).html()).remove();
          });
          elems.highlightText(hterm, "searchword0", !case_insensitive);
          var hmatches = $('.searchword0');
          if (direction == '?')
            hmatches = hmatches.last();
          hmatches.first().each(function() {
            var offset = $(this).offset().top;
            window.scrollTo(0, offset);
          });
        }
      }
      window.onhashchange = scrollToHashSearchMatch;
      scrollToHashSearchMatch();
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>/**
 * typed-function
 *
 * Type checking for JavaScript functions
 *
 * https://github.com/josdejong/typed-function
 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.typed = factory();
  }
}(this, function () {
  'use strict';

  // order types
  // anytype (*) will be ordered last, and then object, as other types may be
  // an object too.
  function compareTypes(a, b) {
    if (a === '*') return 1;
    if (b === '*') return -1;

    if (a === 'Object') return 1;
    if (b === 'Object') return -1;

    return 0;
  }

  /**
   * Get a type test function for a specific data type
   * @param {string} type                   A data type like 'number' or 'string'
   * @returns {function(obj: *) : boolean}  Returns a type testing function.
   *                                        Throws an error for an unknown type.
   */
  function getTypeTest(type) {
    var test = typed.types[type];
    if (!test) {
      var matches = Object.keys(typed.types)
          .filter(function (t) {
            return t.toLowerCase() == type.toLowerCase();
          })
          .map(function (t) {
            return '"' + t + '"';
          });

      throw new Error('Unknown type "' + type + '"' +
          (matches.length ? ('. Did you mean ' + matches.join(', or ') + '?') : ''));
    }
    return test;
  }

  // order numbers
  function compareNumbers(a, b) {
    return a > b;
  }

  /**
   * Collection with function definitions (local shortcuts to functions)
   * @constructor
   */
  function Defs() {}

  /**
   * Add a function definition.
   * @param {function} fn
   * @param {string} [type='fn']    A function category, like 'fn' or 'signature'
   * @returns {string} Returns the function name, for example 'fn0' or 'signature2'
   */
  Defs.prototype.add = function (fn, type) {
    type = type || 'fn';
    if (!this[type]) this[type] = [];

    var index = this[type].indexOf(fn);
    if (index == -1) {
      index = this[type].length;
      this[type].push(fn);
    }
    return type + index;
  };

  /**
   * Create code lines for all definitions
   * @param [name='defs']
   * @returns {Array} Returns the code lines containing all function definitions
   */
  Defs.prototype.code = function (name) {
    var me = this;
    var code = [];
    name = name || 'defs';

    Object.keys(this).forEach(function (type) {
      var def = me[type];
      def.forEach(function (def, index) {
        code.push('var ' + type + index + ' = ' + name + '[\'' + type + '\'][' + index + '];');
      });
    });

    return code;
  };

  /**
   * A function parameter
   * @param {string | string[] | Param} types    A parameter type like 'string',
   *                                             'number | boolean'
   * @constructor
   */
  function Param(types) {
    if (typeof types === 'string') {
      this.types = types.split('|').map(function (type) {
        return type.trim();
      })
    }
    else if (Array.isArray(types)) {
      this.types = types;
    }
    else if (types instanceof Param) {
      this.types = types.types;
    }
    else {
      throw new Error('string or Array expected');
    }
  }

  /**
   * Return a string representation of this params types, like 'string' or
   * 'number | boolean'
   * @returns {string}
   */
  Param.prototype.toString = function () {
    return this.types.join('|');
  };

  /**
   * A function signature
   * @param {string | Array.<string>} params  Array with the type(s) of each parameter,
   *                                          or a comma separated string with types
   * @param {function} fn                     The actual function
   * @constructor
   */
  function Signature(params, fn) {
    if (typeof params === 'string') {
      this.params = (params !== '') ? params.split(',').map(function (types) {
        return new Param(types);
      }) : [];
    }
    else if (Array.isArray(params)) {
      this.params = params.map(function (types) {
        return new Param(types);
      });
    }
    else {
      throw new Error('string or Array expected');
    }
    this.fn = fn;
  }

  // TODO: implement function Signature.merge
  // TODO: implement function Signature.toString

  /**
   * Split params with multiple types in separate signatures
   * @return {Signature[]} Returns an array with signatures (at least one)
   */
  Signature.prototype.split = function () {
    var signatures = [];

    function _iterate(signature, types, index) {
      if (index < signature.params.length) {
        var param = signature.params[index];
        param.types.forEach(function (type) {
          _iterate(signature, types.concat(type), index + 1);
        });
      }
      else {
        signatures.push(new Signature(types, signature.fn));
      }
    }
    _iterate(this, [], 0);

    return signatures;
  };

  /**
   * Split all raw signatures into an array with splitted params
   * @param {Object.<string, function>} rawSignatures
   * @return {Array.<Signature>} Returns an array with splitted signatures
   */
  function splitSignatures(rawSignatures) {
    return Object.keys(rawSignatures).reduce(function (signatures, params) {
      var fn = rawSignatures[params];
      var signature = new Signature(params, fn);

      return signatures.concat(signature.split());
    }, []);
  }

  /**
   * create a map with normalized signatures as key and the function as value
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @return {{}} Returns a map with normalized signatures
   */
  function normalizeSignatures(signatures) {
    var normalized = {};

    signatures.map(function (entry) {
      var signature = entry.params.join(',');
      if (signature in normalized) {
        throw new Error('Error: signature "' + signature + '" defined twice');
      }
      normalized[signature] = entry.fn;
    });

    return normalized
  }

  /**
   * create an array with for every parameter an array with possible types
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @return {Array.<Array.<string>>} Returns an array with allowed types per parameter
   */
  function splitTypes(signatures) {
    var types = [];

    signatures.forEach(function (entry) {
      entry.params.forEach(function (param, i) {
        param.types.forEach(function (type) {
          if (!types[i]) {
            types[i] = [];
          }
          if (types[i].indexOf(type) == -1) {
            types[i].push(type);
          }
        });
      });
    });

    return types;
  }

  /**
   * create a recursive tree for traversing the number and type of parameters
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @returns {{}}
   */
  function createParamsTree(signatures) {
    var tree = {};

    signatures.forEach(function (entry) {
      var params = entry.params.concat([]);

      // get the tree entry for the current number of arguments
      var obj = tree[params.length];
      if (!obj) {
        obj = tree[params.length] = {
          signature: [],
          fn: null,
          types: {}
        };
      }

      // loop over all parameters, create a nested structure
      while(params.length > 0) {
        var param = params.shift();
        if (param.types.length != 1) {
          throw new Error('Parameters should have one type. Split the signatures first.')
        }
        var type = param.types[0];

        if (!obj.types[type]) {
          obj.types[type] = {
            signature: obj.signature.concat(type),
            fn: null,
            types: {}
          };
        }
        obj = obj.types[type];
      }

      // add the function as leaf
      obj.fn = entry.fn;
    });

    return tree;
  }

  /**
   * Compose a function from sub-functions each handling a single type signature.
   * Signatures:
   *   typed(signature: string, fn: function)
   *   typed(name: string, signature: string, fn: function)
   *   typed(signatures: Object.<string, function>)
   *   typed(name: string, signatures: Object.<string, function>)
   *
   * @param {string | null} name
   * @param {Object.<string, function>} signatures
   * @return {function} Returns the typed function
   * @private
   */
  function _typed(name, signatures) {
    var defs = new Defs();
    var structure = splitSignatures(signatures);

    function switchTypes(signature, args, prefix) {
      var code = [];

      if (signature.fn !== null) {
        var def = defs.add(signature.fn, 'signature');
        code.push(prefix + 'return ' + def + '(' + args.join(', ') +'); // signature: ' + signature.signature);
      }
      else {
        // add entries for the provided types
        Object.keys(signature.types)
            .sort(compareTypes)
            .forEach(function (type, index) {
              var arg = 'arg' + args.length;

              var before;
              var after;
              var nextPrefix = prefix + '  ';
              if (type == '*') {
                before = (index > 0 ? 'else {' : '');
                after  = (index > 0 ? '}' : '');
                if (index == 0) {nextPrefix = prefix;}
              }
              else {
                var def = defs.add(getTypeTest(type), 'test') + '(' + arg + ')';
                before = 'if (' + def + ') { // type: ' + type;
                after  = '}';
              }

              if (before) code.push(prefix + before);
              code = code.concat(switchTypes(signature.types[type], args.concat(arg), nextPrefix));
              if (after) code.push(prefix + after);
            });

        // add entries for type conversions
        var added = {};
        typed.conversions
            .filter(function (conversion) {
              return signature.types[conversion.to] &&
                  !signature.types[conversion.from];
            })
            .forEach(function (conversion) {
              if (!added[conversion.from]) {
                added[conversion.from] = true;

                var arg = 'arg' + args.length;
                var test = defs.add(getTypeTest(conversion.from), 'test') + '(' + arg + ')';
                var convert = defs.add(conversion.convert, 'convert') + '(' + arg + ')';

                code.push(prefix + 'if (' + test + ') { // type: ' + conversion.from + ', convert to ' + conversion.to);
                code = code.concat(switchTypes(signature.types[conversion.to], args.concat(convert), prefix + '  '));
                code.push(prefix + '}');
              }
            });
      }

      return code;
    }

    var types = splitTypes(structure);
    var params = [];
    for (var i = 0; i < types.length; i++) { // we can't use .map here, some entries may be undefined
      params.push('arg' + i);
    }

    var code = [];
    var tree = createParamsTree(structure);
    var paramCounts = Object.keys(tree);
    code.push('return function ' + (name || '') + '(' + params.join(', ') + ') {');
    paramCounts
        .sort(compareNumbers)
        .forEach(function (count, index) {
          var signature = tree[count];
          var args = [];
          var statement = (index == 0) ? 'if' : 'else if';
          code.push('  ' + statement + ' (arguments.length == ' + count +  ') {');
          code = code.concat(switchTypes(signature, args, '    '));

          code.push('  }');
          if (index == paramCounts.length - 1) {
            code.push('  else {');
            code.push('    throw new TypeError(\'Wrong number of arguments\');'); // TODO: output the allowed numbers
            code.push('  }');
          }
        });
    code.push('  throw new TypeError(\'Wrong function signature\');');  // TODO: output the actual signature
    code.push('}');

    var factory = [];
    factory.push('(function (defs) {');
    factory = factory.concat(defs.code('defs'));
    factory = factory.concat(code);
    factory.push('})');

    var fn = eval(factory.join('\n'))(defs);

    // attach the signatures with sub-functions to the constructed function
    fn.signatures = normalizeSignatures(structure); // normalized signatures

    return fn;
  }

  // data type tests
  var types = {
    'null':     function (x) {return x === null},
    'boolean':  function (x) {return typeof x === 'boolean'},
    'number':   function (x) {return typeof x === 'number'},
    'string':   function (x) {return typeof x === 'string'},
    'function': function (x) {return typeof x === 'function'},
    'Array':    function (x) {return Array.isArray(x)},
    'Date':     function (x) {return x instanceof Date},
    'RegExp':   function (x) {return x instanceof RegExp},
    'Object':   function (x) {return typeof x === 'object'}
  };

  // type conversions. Order is important
  var conversions = [];

  // temporary object for holding types and conversions, for constructing
  // the `typed` function itself
  // TODO: find a more elegant solution for this
  var typed = {
    types: types,
    conversions: conversions
  };

  /**
   * Construct the typed function itself with various signatures
   *
   * Signatures:
   *
   *   typed(signature: string, fn: function)
   *   typed(name: string, signature: string, fn: function)
   *   typed(signatures: Object.<string, function>)
   *   typed(name: string, signatures: Object.<string, function>)
   */
  typed = _typed('typed', {
    'Object': function (signatures) {
      return _typed(null, signatures);
    },
    'string, Object': _typed,
    'string, function': function (signature, fn) {
      var signatures = {};
      signatures[signature] = fn;
      return _typed(null, signatures);
    },
    'string, string, function': function(name, signature, fn) {
      var signatures = {};
      signatures[signature] = fn;
      return _typed(name, signatures);
    }
  });

  // attach types and conversions to the final `typed` function
  typed.types = types;
  typed.conversions = conversions;

  return typed;
}));

<commit_msg>Replaced for with map<commit_after>/**
 * typed-function
 *
 * Type checking for JavaScript functions
 *
 * https://github.com/josdejong/typed-function
 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.typed = factory();
  }
}(this, function () {
  'use strict';

  // order types
  // anytype (*) will be ordered last, and then object, as other types may be
  // an object too.
  function compareTypes(a, b) {
    if (a === '*') return 1;
    if (b === '*') return -1;

    if (a === 'Object') return 1;
    if (b === 'Object') return -1;

    return 0;
  }

  /**
   * Get a type test function for a specific data type
   * @param {string} type                   A data type like 'number' or 'string'
   * @returns {function(obj: *) : boolean}  Returns a type testing function.
   *                                        Throws an error for an unknown type.
   */
  function getTypeTest(type) {
    var test = typed.types[type];
    if (!test) {
      var matches = Object.keys(typed.types)
          .filter(function (t) {
            return t.toLowerCase() == type.toLowerCase();
          })
          .map(function (t) {
            return '"' + t + '"';
          });

      throw new Error('Unknown type "' + type + '"' +
          (matches.length ? ('. Did you mean ' + matches.join(', or ') + '?') : ''));
    }
    return test;
  }

  // order numbers
  function compareNumbers(a, b) {
    return a > b;
  }

  /**
   * Collection with function definitions (local shortcuts to functions)
   * @constructor
   */
  function Defs() {}

  /**
   * Add a function definition.
   * @param {function} fn
   * @param {string} [type='fn']    A function category, like 'fn' or 'signature'
   * @returns {string} Returns the function name, for example 'fn0' or 'signature2'
   */
  Defs.prototype.add = function (fn, type) {
    type = type || 'fn';
    if (!this[type]) this[type] = [];

    var index = this[type].indexOf(fn);
    if (index == -1) {
      index = this[type].length;
      this[type].push(fn);
    }
    return type + index;
  };

  /**
   * Create code lines for all definitions
   * @param [name='defs']
   * @returns {Array} Returns the code lines containing all function definitions
   */
  Defs.prototype.code = function (name) {
    var me = this;
    var code = [];
    name = name || 'defs';

    Object.keys(this).forEach(function (type) {
      var def = me[type];
      def.forEach(function (def, index) {
        code.push('var ' + type + index + ' = ' + name + '[\'' + type + '\'][' + index + '];');
      });
    });

    return code;
  };

  /**
   * A function parameter
   * @param {string | string[] | Param} types    A parameter type like 'string',
   *                                             'number | boolean'
   * @constructor
   */
  function Param(types) {
    if (typeof types === 'string') {
      this.types = types.split('|').map(function (type) {
        return type.trim();
      })
    }
    else if (Array.isArray(types)) {
      this.types = types;
    }
    else if (types instanceof Param) {
      this.types = types.types;
    }
    else {
      throw new Error('string or Array expected');
    }
  }

  /**
   * Return a string representation of this params types, like 'string' or
   * 'number | boolean'
   * @returns {string}
   */
  Param.prototype.toString = function () {
    return this.types.join('|');
  };

  /**
   * A function signature
   * @param {string | Array.<string>} params  Array with the type(s) of each parameter,
   *                                          or a comma separated string with types
   * @param {function} fn                     The actual function
   * @constructor
   */
  function Signature(params, fn) {
    if (typeof params === 'string') {
      this.params = (params !== '') ? params.split(',').map(function (types) {
        return new Param(types);
      }) : [];
    }
    else if (Array.isArray(params)) {
      this.params = params.map(function (types) {
        return new Param(types);
      });
    }
    else {
      throw new Error('string or Array expected');
    }
    this.fn = fn;
  }

  // TODO: implement function Signature.merge
  // TODO: implement function Signature.toString

  /**
   * Split params with multiple types in separate signatures
   * @return {Signature[]} Returns an array with signatures (at least one)
   */
  Signature.prototype.split = function () {
    var signatures = [];

    function _iterate(signature, types, index) {
      if (index < signature.params.length) {
        var param = signature.params[index];
        param.types.forEach(function (type) {
          _iterate(signature, types.concat(type), index + 1);
        });
      }
      else {
        signatures.push(new Signature(types, signature.fn));
      }
    }
    _iterate(this, [], 0);

    return signatures;
  };

  /**
   * Split all raw signatures into an array with splitted params
   * @param {Object.<string, function>} rawSignatures
   * @return {Array.<Signature>} Returns an array with splitted signatures
   */
  function splitSignatures(rawSignatures) {
    return Object.keys(rawSignatures).reduce(function (signatures, params) {
      var fn = rawSignatures[params];
      var signature = new Signature(params, fn);

      return signatures.concat(signature.split());
    }, []);
  }

  /**
   * create a map with normalized signatures as key and the function as value
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @return {{}} Returns a map with normalized signatures
   */
  function normalizeSignatures(signatures) {
    var normalized = {};

    signatures.map(function (entry) {
      var signature = entry.params.join(',');
      if (signature in normalized) {
        throw new Error('Error: signature "' + signature + '" defined twice');
      }
      normalized[signature] = entry.fn;
    });

    return normalized
  }

  /**
   * create an array with for every parameter an array with possible types
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @return {Array.<Array.<string>>} Returns an array with allowed types per parameter
   */
  function splitTypes(signatures) {
    var types = [];

    signatures.forEach(function (entry) {
      entry.params.forEach(function (param, i) {
        param.types.forEach(function (type) {
          if (!types[i]) {
            types[i] = [];
          }
          if (types[i].indexOf(type) == -1) {
            types[i].push(type);
          }
        });
      });
    });

    return types;
  }

  /**
   * create a recursive tree for traversing the number and type of parameters
   * @param {Array.<Signature>} signatures   An array with splitted signatures
   * @returns {{}}
   */
  function createParamsTree(signatures) {
    var tree = {};

    signatures.forEach(function (entry) {
      var params = entry.params.concat([]);

      // get the tree entry for the current number of arguments
      var obj = tree[params.length];
      if (!obj) {
        obj = tree[params.length] = {
          signature: [],
          fn: null,
          types: {}
        };
      }

      // loop over all parameters, create a nested structure
      while(params.length > 0) {
        var param = params.shift();
        if (param.types.length != 1) {
          throw new Error('Parameters should have one type. Split the signatures first.')
        }
        var type = param.types[0];

        if (!obj.types[type]) {
          obj.types[type] = {
            signature: obj.signature.concat(type),
            fn: null,
            types: {}
          };
        }
        obj = obj.types[type];
      }

      // add the function as leaf
      obj.fn = entry.fn;
    });

    return tree;
  }

  /**
   * Compose a function from sub-functions each handling a single type signature.
   * Signatures:
   *   typed(signature: string, fn: function)
   *   typed(name: string, signature: string, fn: function)
   *   typed(signatures: Object.<string, function>)
   *   typed(name: string, signatures: Object.<string, function>)
   *
   * @param {string | null} name
   * @param {Object.<string, function>} signatures
   * @return {function} Returns the typed function
   * @private
   */
  function _typed(name, signatures) {
    var defs = new Defs();
    var structure = splitSignatures(signatures);

    function switchTypes(signature, args, prefix) {
      var code = [];

      if (signature.fn !== null) {
        var def = defs.add(signature.fn, 'signature');
        code.push(prefix + 'return ' + def + '(' + args.join(', ') +'); // signature: ' + signature.signature);
      }
      else {
        // add entries for the provided types
        Object.keys(signature.types)
            .sort(compareTypes)
            .forEach(function (type, index) {
              var arg = 'arg' + args.length;

              var before;
              var after;
              var nextPrefix = prefix + '  ';
              if (type == '*') {
                before = (index > 0 ? 'else {' : '');
                after  = (index > 0 ? '}' : '');
                if (index == 0) {nextPrefix = prefix;}
              }
              else {
                var def = defs.add(getTypeTest(type), 'test') + '(' + arg + ')';
                before = 'if (' + def + ') { // type: ' + type;
                after  = '}';
              }

              if (before) code.push(prefix + before);
              code = code.concat(switchTypes(signature.types[type], args.concat(arg), nextPrefix));
              if (after) code.push(prefix + after);
            });

        // add entries for type conversions
        var added = {};
        typed.conversions
            .filter(function (conversion) {
              return signature.types[conversion.to] &&
                  !signature.types[conversion.from];
            })
            .forEach(function (conversion) {
              if (!added[conversion.from]) {
                added[conversion.from] = true;

                var arg = 'arg' + args.length;
                var test = defs.add(getTypeTest(conversion.from), 'test') + '(' + arg + ')';
                var convert = defs.add(conversion.convert, 'convert') + '(' + arg + ')';

                code.push(prefix + 'if (' + test + ') { // type: ' + conversion.from + ', convert to ' + conversion.to);
                code = code.concat(switchTypes(signature.types[conversion.to], args.concat(convert), prefix + '  '));
                code.push(prefix + '}');
              }
            });
      }

      return code;
    }

    var types = splitTypes(structure);
    var params = types.map(function (value, index) {
      return 'arg' + index;
    });

    var code = [];
    var tree = createParamsTree(structure);
    var paramCounts = Object.keys(tree);
    code.push('return function ' + (name || '') + '(' + params.join(', ') + ') {');
    paramCounts
        .sort(compareNumbers)
        .forEach(function (count, index) {
          var signature = tree[count];
          var args = [];
          var statement = (index == 0) ? 'if' : 'else if';
          code.push('  ' + statement + ' (arguments.length == ' + count +  ') {');
          code = code.concat(switchTypes(signature, args, '    '));

          code.push('  }');
          if (index == paramCounts.length - 1) {
            code.push('  else {');
            code.push('    throw new TypeError(\'Wrong number of arguments\');'); // TODO: output the allowed numbers
            code.push('  }');
          }
        });
    code.push('  throw new TypeError(\'Wrong function signature\');');  // TODO: output the actual signature
    code.push('}');

    var factory = [];
    factory.push('(function (defs) {');
    factory = factory.concat(defs.code('defs'));
    factory = factory.concat(code);
    factory.push('})');

    var fn = eval(factory.join('\n'))(defs);

    // attach the signatures with sub-functions to the constructed function
    fn.signatures = normalizeSignatures(structure); // normalized signatures

    return fn;
  }

  // data type tests
  var types = {
    'null':     function (x) {return x === null},
    'boolean':  function (x) {return typeof x === 'boolean'},
    'number':   function (x) {return typeof x === 'number'},
    'string':   function (x) {return typeof x === 'string'},
    'function': function (x) {return typeof x === 'function'},
    'Array':    function (x) {return Array.isArray(x)},
    'Date':     function (x) {return x instanceof Date},
    'RegExp':   function (x) {return x instanceof RegExp},
    'Object':   function (x) {return typeof x === 'object'}
  };

  // type conversions. Order is important
  var conversions = [];

  // temporary object for holding types and conversions, for constructing
  // the `typed` function itself
  // TODO: find a more elegant solution for this
  var typed = {
    types: types,
    conversions: conversions
  };

  /**
   * Construct the typed function itself with various signatures
   *
   * Signatures:
   *
   *   typed(signature: string, fn: function)
   *   typed(name: string, signature: string, fn: function)
   *   typed(signatures: Object.<string, function>)
   *   typed(name: string, signatures: Object.<string, function>)
   */
  typed = _typed('typed', {
    'Object': function (signatures) {
      return _typed(null, signatures);
    },
    'string, Object': _typed,
    'string, function': function (signature, fn) {
      var signatures = {};
      signatures[signature] = fn;
      return _typed(null, signatures);
    },
    'string, string, function': function(name, signature, fn) {
      var signatures = {};
      signatures[signature] = fn;
      return _typed(name, signatures);
    }
  });

  // attach types and conversions to the final `typed` function
  typed.types = types;
  typed.conversions = conversions;

  return typed;
}));

<|endoftext|>


<commit_before>// Remove the webpack-dev-server grunt task since we do not use it
var fs = require('fs');
var path = require('path');

var taskFile = path.join(__dirname, '..', 'node_modules', 'grunt-webpack', 'tasks', 'webpack-dev-server.js');

if (fs.existsSync(taskFile)) {
    console.log('Removing unused task file ' + taskFile);
    fs.unlinkSync(taskFile);
}
<commit_msg>Use require.resolve for more robust path lookup<commit_after>// Remove the webpack-dev-server grunt task since we do not use it

var fs = require('fs');
var taskFile = null;

try {
    taskFile = require.resolve('grunt-webpack/tasks/webpack-dev-server.js');
} catch(e) {}

if (taskFile) {
    console.log('Removing unused task file ' + taskFile);
    fs.unlinkSync(taskFile);
}
<|endoftext|>


<commit_before>/**
 * Define Sp Site Object constructor
 * @params  url  url of Sharepoint site
 * @author  Martin Pomeroy <mpomeroy@wearearchitect.com>
 * @return  void
 */
SPOC.SPSite = function(url) {

    // Set URL to current site if no url passed in.
    this.url = url ? url : _spPageContextInfo.webAbsoluteUrl;
};
<commit_msg>chore(core): return set url<commit_after>/**
 * Define Sp Site Object constructor
 * @params  url  url of Sharepoint site
 * @author  Martin Pomeroy <mpomeroy@wearearchitect.com>
 * @return  void
 */
SPOC.SPSite = function(url) {

    // Set URL to current site if no url passed in.
    return this.url = url ? url : _spPageContextInfo.webAbsoluteUrl;
};
<|endoftext|>


<commit_before>/**
 * Copyright 2015-2021 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utilsNew.js";
import LitUtils from "../utils/lit-utils.js";
import "../../job/job-monitor.js";

export default class CustomNavBar extends LitElement {

    constructor() {
        super();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            loggedIn: {
                type: Boolean
            },
            app: {
                type: Object
            },
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    onSideBarToggle(e) {
        LitUtils.dispatchEventCustom(this, "sideBarToggle", "", null, {event: e});
    }

    onChangeTool(e) {
        LitUtils.dispatchEventCustom(this, "changeTool", e);
    }

    onChangeApp(e, toggle) {
        LitUtils.dispatchEventCustom(this, "changeApp", "", null, {event: e, toggle: toggle});
    }

    onStudySelect(e, study) {
        e.preventDefault(); // prevents the hash change to "#" and allows to manipulate the hash fragment as needed
        LitUtils.dispatchEventCustom(this, "studySelect", "", null, {event: e, study: study});
    }

    createAboutLink(link, button) {
        const url = link.url ? `${link.url}` : `#${link.id}`;
        const iconHtml = link.icon ? html`<i class="${link.icon} icon-padding" aria-hidden="true"></i>` : null;
        if (link.url) {
            return html`
                ${iconHtml} ${link.name}`;
        } else {
            return html`
                ${iconHtml} ${link.name}`;
        }
    }

    logout() {
        LitUtils.dispatchEventCustom(this, "logout");
    }

    render() {
        return html `

                    ${this.config.apps?.filter(app => UtilsNew.isAppVisible(app, this.opencgaSession)).length > 1 ? html`

                    ` : null}

                        ${this.config?.companyLogo ? html`

                        ` : null}
                        ${this.app?.logo ? html`

                                ${this.config.version}

                        ` : null}

                            ${this.app?.menu?.filter?.(item => UtilsNew.isAppVisible(item, this.opencgaSession)).map(item => html`

                                ${item.submenu && item.submenu.some(sm => UtilsNew.isAppVisible(sm, this.opencgaSession)) ? html`

                                            ${item.name}

                                            ${item.submenu
                                                    .filter(subItem => UtilsNew.isAppVisible(subItem, this.opencgaSession))
                                                    .map(subItem => subItem.category ? html`

                                                            ${subItem.name}

                                                    ` : subItem.separator ? html`

                                                    ` : html`

                                                            ${subItem.name}

                                                  `)}

                                ` : html`

                                        ${item.name}

`
                                }`
                            )}

                            ${this.opencgaSession && this.opencgaSession.projects && this.opencgaSession.projects.length ? html`

${this.opencgaSession.project?.name}

${this.opencgaSession.study.name}

                                        ${this.opencgaSession.projects.filter(project => project?.studies.length > 0).map(project => html`

${project.name} [${project.fqn.split("@")[0]}]

                                            ${project.studies && project.studies.length && project.studies.map(study => html`

                                                    <a href="javascript: void 0"
                                                       data-cy-fqn="${study.fqn}"
                                                       data-study="${study.id}"
                                                       data-project="${project.id}"
                                                       data-project-name="${project.name}"
                                                       data-study-name="${study.name}"
                                                       title="${study.fqn}"
                                                       @click="${e => this.onStudySelect(e, study)}">${study.name}

                                            `)}
                                        `)}

                            ` : null}

                            ${UtilsNew.isAppVisible(this.app?.jobMonitor, this.opencgaSession) ? html`
                                <job-monitor .opencgaSession="${this.opencgaSession}"></job-monitor>
                            ` : null}

                            ${UtilsNew.isAppVisible(this.app?.fileExplorer, this.opencgaSession) ? html`

                            ` : null}

                            ${this.app?.about.dropdown ? html`

                                        About

                                        ${this.app.about.links && this.app.about.links.map(link => html`

${this.createAboutLink(link, false)}

                                        `)}

                            ` : this.app?.about.links && this.app.about.links.map(link => html`

${this.createAboutLink(link, true)}

                            `) }

                            ${this.config.login.visible && !this.loggedIn ? html`

                                        Login

                            ` : null}

                            ${this.loggedIn ? html`

                                        ${this.opencgaSession.user?.name ?? this.opencgaSession.user?.email}

                                        ${this.app?.userMenu?.length ? this.app.userMenu.filter(item => UtilsNew.isAppVisible(item, this.opencgaSession)).map(item => html`

                                                 ${item.name}

                                        `) : null}

                                                 Logout

                            ` : null}

            `;
    }

}

customElements.define("custom-navbar", CustomNavBar);
<commit_msg>wc: display app name if no logo is provided #189<commit_after>/**
 * Copyright 2015-2021 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utilsNew.js";
import LitUtils from "../utils/lit-utils.js";
import "../../job/job-monitor.js";

export default class CustomNavBar extends LitElement {

    constructor() {
        super();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            loggedIn: {
                type: Boolean
            },
            app: {
                type: Object
            },
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    onSideBarToggle(e) {
        LitUtils.dispatchEventCustom(this, "sideBarToggle", "", null, {event: e});
    }

    onChangeTool(e) {
        LitUtils.dispatchEventCustom(this, "changeTool", e);
    }

    onChangeApp(e, toggle) {
        LitUtils.dispatchEventCustom(this, "changeApp", "", null, {event: e, toggle: toggle});
    }

    onStudySelect(e, study) {
        e.preventDefault(); // prevents the hash change to "#" and allows to manipulate the hash fragment as needed
        LitUtils.dispatchEventCustom(this, "studySelect", "", null, {event: e, study: study});
    }

    createAboutLink(link, button) {
        const url = link.url ? `${link.url}` : `#${link.id}`;
        const iconHtml = link.icon ? html`<i class="${link.icon} icon-padding" aria-hidden="true"></i>` : null;
        if (link.url) {
            return html`
                ${iconHtml} ${link.name}`;
        } else {
            return html`
                ${iconHtml} ${link.name}`;
        }
    }

    logout() {
        LitUtils.dispatchEventCustom(this, "logout");
    }

    render() {
        return html `

                    ${this.config.apps?.filter(app => UtilsNew.isAppVisible(app, this.opencgaSession)).length > 1 ? html`

                    ` : null}

                            ${this.app?.logo ? html`

                                ${this.config.version}
                            ` : null}

                            ${!this.app?.logo && this.app?.name ? html`

                                    ${this.app.name}

                                ${this.config.version}
                            `: null}

                            ${this.app?.menu?.filter?.(item => UtilsNew.isAppVisible(item, this.opencgaSession)).map(item => html`

                                ${item.submenu && item.submenu.some(sm => UtilsNew.isAppVisible(sm, this.opencgaSession)) ? html`

                                            ${item.name}

                                            ${item.submenu
                                                    .filter(subItem => UtilsNew.isAppVisible(subItem, this.opencgaSession))
                                                    .map(subItem => subItem.category ? html`

                                                            ${subItem.name}

                                                    ` : subItem.separator ? html`

                                                    ` : html`

                                                            ${subItem.name}

                                                  `)}

                                ` : html`

                                        ${item.name}

`
                                }`
                            )}

                            ${this.opencgaSession && this.opencgaSession.projects && this.opencgaSession.projects.length ? html`

${this.opencgaSession.project?.name}

${this.opencgaSession.study.name}

                                        ${this.opencgaSession.projects.filter(project => project?.studies.length > 0).map(project => html`

${project.name} [${project.fqn.split("@")[0]}]

                                            ${project.studies && project.studies.length && project.studies.map(study => html`

                                                    <a href="javascript: void 0"
                                                       data-cy-fqn="${study.fqn}"
                                                       data-study="${study.id}"
                                                       data-project="${project.id}"
                                                       data-project-name="${project.name}"
                                                       data-study-name="${study.name}"
                                                       title="${study.fqn}"
                                                       @click="${e => this.onStudySelect(e, study)}">${study.name}

                                            `)}
                                        `)}

                            ` : null}

                            ${UtilsNew.isAppVisible(this.app?.jobMonitor, this.opencgaSession) ? html`
                                <job-monitor .opencgaSession="${this.opencgaSession}"></job-monitor>
                            ` : null}

                            ${UtilsNew.isAppVisible(this.app?.fileExplorer, this.opencgaSession) ? html`

                            ` : null}

                            ${this.app?.about.dropdown ? html`

                                        About

                                        ${this.app.about.links && this.app.about.links.map(link => html`

${this.createAboutLink(link, false)}

                                        `)}

                            ` : this.app?.about.links && this.app.about.links.map(link => html`

${this.createAboutLink(link, true)}

                            `) }

                            ${this.config.login.visible && !this.loggedIn ? html`

                                        Login

                            ` : null}

                            ${this.loggedIn ? html`

                                        ${this.opencgaSession.user?.name ?? this.opencgaSession.user?.email}

                                        ${this.app?.userMenu?.length ? this.app.userMenu.filter(item => UtilsNew.isAppVisible(item, this.opencgaSession)).map(item => html`

                                                 ${item.name}

                                        `) : null}

                                                 Logout

                            ` : null}

            `;
    }

}

customElements.define("custom-navbar", CustomNavBar);
<|endoftext|>


<commit_before>module.exports = function (grunt) {
	return {
		options: {
			separator: Array(3).join(grunt.util.linefeed),
			sourceRoot: process.env.CI ? 'http://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
		},
		all: {
			files: {
				'dist/<%= pkgName %>.js': [
					'umd/header.js',

					'src/shim.js',
					'src/utils.js',
					'src/core.js',
					'src/proto/cache.js',
					'src/proto/context.js',
					'src/type.js',
					'src/template.js',
					'src/proto/as.js',
					'src/proto/position.js',
					'src/proto/props.js',
					'src/typeSet/*.js',
					'src/io/toURI.js',
					'src/io/load.js',
					'src/io/save.js',

					'umd/footer.js'
				]
			}
		}
	};
};<commit_msg>Fix sources protocol to HTTPS.<commit_after>module.exports = function (grunt) {
	return {
		options: {
			separator: Array(3).join(grunt.util.linefeed),
			sourceRoot: process.env.CI ? 'https://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
		},
		all: {
			files: {
				'dist/<%= pkgName %>.js': [
					'umd/header.js',

					'src/shim.js',
					'src/utils.js',
					'src/core.js',
					'src/proto/cache.js',
					'src/proto/context.js',
					'src/type.js',
					'src/template.js',
					'src/proto/as.js',
					'src/proto/position.js',
					'src/proto/props.js',
					'src/typeSet/*.js',
					'src/io/toURI.js',
					'src/io/load.js',
					'src/io/save.js',

					'umd/footer.js'
				]
			}
		}
	};
};<|endoftext|>


<commit_before>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * 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.
 */
'use strict';

module.exports = function(context) {
  function stripComments(text) {
    // Multi-line comments
    text = text.replace(/\/\*(?!.*\*\/)(.|\n)*?\*\//g, function(match) {
      // Preserve the newlines
      const newlines = [];
      for (let i = 0; i < match.length; i++) {
        if (match[i] === '\n') {
          newlines.push('\n');
        }
      }
      return newlines.join('');
    });
    // Single line comments either on its own line or following a space,
    // semi-colon, or closing brace
    return text.replace(/( |}|;|^) *\/\/.*/g, '$1');
  }

  function checkClassUse(node, name) {
    if (!name.endsWith('_')) {
      return;
    }

    const comments = context.getCommentsBefore(node);
    const testing = comments.some(comment => {
      return /@(visibleForTesting|protected|override)\b/.test(comment.value);
    });
    if (testing) {
      return;
    }

    const ancestors = context.getAncestors(node);
    const body = ancestors.reverse().find(node => node.type === 'ClassBody');

    if (!body) {
      return;
    }

    // Yah, I know, we're not using the AST anymore.
    // But there's no good way to do inner traversals, so this is all we got.
    const source = context.getSourceCode();
    const bodyText = stripComments(source.getText(body));

    // Requires two uses of the name to qualify;
    const index = bodyText.indexOf(name);
    if (!bodyText.includes(name, index + 1)) {
      context.report(node, `Unused private "${name}".\n` +
        '\tIf this is used for testing, annotate with "@visibleForTesting"\n' +
        '\tIf this is a protected definition in a base class,' +
        ' annotate with "@protected"\n' +
        '\tIf this is an override of a protected, annotate with "@override"\n');
    }
  }

  return {
    MemberExpression(node) {
      if (/\btest\b/.test(context.getFilename())) {
        return;
      }

      const {property} = node;
      if (property.type !== 'Identifier') {
        return;
      }

      const {name} = property;
      checkClassUse(node, name);
    },

    MethodDefinition(node) {
      if (/\btest\b/.test(context.getFilename())) {
        return;
      }

      const {computed, key} = node;
      if (computed) {
        return;
      }

      const {name} = key;
      checkClassUse(node, name);
    },
  };
};
<commit_msg>🏗 Be a little more lenient with Unused Private Linting (#14807)<commit_after>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * 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.
 */
'use strict';

module.exports = function(context) {
  const stack = [];
  function current() {
    return stack[stack.length - 1];
  }

  function shouldIgnoreFile() {
    return /\b(test|examples)\b/.test(context.getFilename());
  }

  function shouldIgnoreDueToAnnotation(node) {
    const comments = context.getCommentsBefore(node);
    const annotated = comments.some(comment => {
      return /@(visibleForTesting|protected|override)\b/.test(comment.value);
    });
    return annotated;
  }

  function shouldCheckMember(node, needsThis = true) {
    const {computed, object, property} = node;
    if (computed ||
        (needsThis && object.type !== 'ThisExpression') ||
        property.type !== 'Identifier') {
      return false;
    }

    return isPrivateName(property);
  }

  function isAssignment(node) {
    const {parent} = node;
    return parent.type === 'AssignmentExpression' && parent.left === node;
  }

  function isPrivateName(node) {
    return node.name.endsWith('_');
  }

  return {
    ClassBody() {
      if (shouldIgnoreFile()) {
        return;
      }

      stack.push({used: new Set(), declared: new Map()});
    },

    'ClassBody:exit': function() {
      if (shouldIgnoreFile()) {
        return;
      }

      const {used, declared} = stack.pop();

      declared.forEach((node, name) => {
        if (used.has(name)) {
          return;
        }

        context.report(node, [
          `Unused private "${name}".`,
          'If this is used for testing, annotate with `@visibleForTesting`.',
          'If this is used in a subclass, annotate with `@protected`.',
          'If this is an override of a protected, annotate with `@override`.',
          'If none of these exceptions applies, please contact @jridgewell.',
        ].join('\n\t'));
      });
    },

    'ClassBody > MethodDefinition': function(node) {
      if (shouldIgnoreFile()) {
        return;
      }

      const {computed, key} = node;
      if (computed ||
          !isPrivateName(key) ||
          shouldIgnoreDueToAnnotation(node)) {
        return;
      }

      const {name} = node.key;
      const {declared} = current();
      declared.set(name, node);
    },

    'MethodDefinition[kind="constructor"] MemberExpression': function(node) {
      if (shouldIgnoreFile() ||
         !shouldCheckMember(node) ||
         !isAssignment(node)) {
        return;
      }

      const {name} = node.property;
      const {declared} = current();
      declared.set(name, node);
    },

    'ClassBody MemberExpression': function(node) {
      if (shouldIgnoreFile() ||
         !shouldCheckMember(node, false) ||
         isAssignment(node)) {
        return;
      }

      const {name} = node.property;
      const {used} = current();
      used.add(name);
    },
  };
};
<|endoftext|>


<commit_before>import express from 'express'
import chalk from 'chalk'
import webpack from 'webpack'
import devMiddleware from 'webpack-dev-middleware'
import hotMiddleware from 'webpack-hot-middleware'
import historyApiFallback from 'connect-history-api-fallback'
import { config, resolvePath } from '../config'
import webpackConfig from './webpack'

const app = express()
const compiler = webpack(webpackConfig)
const devMiddlewareInstance = devMiddleware(compiler, {
  publicPath: config.public,
  index: config.index,
  quiet: true,
  historyApiFallback: true
})

const hotMiddlewareInstance = hotMiddleware(compiler, {
  log: false
})

compiler.plugin('compilation', (compilation) => {
  compilation.plugin('html-webpack-plugin-after-emit', (data, done) => {
    hotMiddlewareInstance.publish({ action: 'reload' })
    done()
  })
})

app.use(historyApiFallback())
app.use(devMiddlewareInstance)
app.use(hotMiddlewareInstance)
app.use('/', express.static(resolvePath(config.dist)))
app.use('/assets', express.static(resolvePath(config.assets)))

devMiddlewareInstance.waitUntilValid(() => {
  let uri = 'http://localhost:' + config.server.port

  console.log(chalk.blue('> Listening at ' + uri + '\n'))
})

export default app.listen(config.server.port, (error) => {
  if (error) {
    console.log(chalk.red(error))
  }
})
<commit_msg>fix scss files watcher<commit_after>import express from 'express'
import chalk from 'chalk'
import webpack from 'webpack'
import devMiddleware from 'webpack-dev-middleware'
import hotMiddleware from 'webpack-hot-middleware'
import historyApiFallback from 'connect-history-api-fallback'
import { config, resolvePath } from '../config'
import webpackConfig from './webpack'

const app = express()
const compiler = webpack(webpackConfig)
const devMiddlewareInstance = devMiddleware(compiler, {
  publicPath: config.public,
  index: config.index,
  quiet: true,
  historyApiFallback: true,
  watchOptions: {
    aggregateTimeout: 10,
    poll: 10
  }
})

const hotMiddlewareInstance = hotMiddleware(compiler, {
  log: false
})

compiler.plugin('compilation', (compilation) => {
  compilation.plugin('html-webpack-plugin-after-emit', (data, done) => {
    hotMiddlewareInstance.publish({ action: 'reload' })
    done()
  })
})

app.use(historyApiFallback())
app.use(devMiddlewareInstance)
app.use(hotMiddlewareInstance)
app.use('/', express.static(resolvePath(config.dist)))
app.use('/assets', express.static(resolvePath(config.assets)))

devMiddlewareInstance.waitUntilValid(() => {
  let uri = 'http://localhost:' + config.server.port

  console.log(chalk.blue('> Listening at ' + uri + '\n'))
})

export default app.listen(config.server.port, (error) => {
  if (error) {
    console.log(chalk.red(error))
  }
})
<|endoftext|>


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

var Util = require("../modules/util");

var cfg = {
    font: "16px Open Sans",
    align: "left",
    weight: "normal",
    fills: [
        "#f94b3c",
        "#e38e34",
        "#eeda3f",
        "#65737e",
        "#7d8b96",
        "#6c7f8c",
        "#5a7080",
        "#425d6f",
    ],
    selfFill: "#96c938",
    width: 180,
    updateFrame: 30,
};

function LeaderBoardUI(world)
{
    this.world = world;

    this.topCount = cfg.fills.length;
    this.lastUpdateFrame = 0;
    this.labels = {};
    this.expLabels = {};
    this.exps = {};

    this.ui = new PIXI.Container();
    this.ui.x = this.world.viewW - cfg.width;
    this.ui.y = 0;
    this.world.stage.addChild(this.ui);
}

LeaderBoardUI.prototype = {
    constructor: LeaderBoardUI
};

LeaderBoardUI.prototype.addLabel = function(player, rank)
{
    if (!player || rank < 0 || rank >= this.topCount) {
        Util.logError("invald player rank=" + rank + 1);
        return null;
    }
    var labelCfg = {
        fill: cfg.fills[rank],
        font: cfg.font,
        fontWeight: cfg.weight,
        align: cfg.align
    };
    var nameLabel = new PIXI.Text(String(Number(rank) + 1) + " " + player.name, labelCfg);
    var expLabel = new PIXI.Text(String(player.tank.exp), labelCfg);
    var label = new PIXI.Container();
    label.addChild(nameLabel);
    label.addChild(expLabel);
    expLabel.x = 140;

    this.labels[player.connid] = label;
    this.ui.addChild(label);
    return label;
};

LeaderBoardUI.prototype.update = function()
{
    if (this.world.playerCount <= 0) {
        return;
    }
    this.ui.visible = true;

    if (this.world.frame < this.lastUpdateFrame + cfg.updateFrame) {
        return;
    }
    this.lastUpdateFrame = this.world.frame;

    var label;
    for (var idx in this.labels) {
        label = this.labels[idx];
        if (label) {
            this.ui.removeChild(label);
        }
    }
    this.labels = [];

    for (var rank in this.world.rankPlayers) {
        var player = this.world.rankPlayers[rank];
        if (!player || !player.tank) {
            continue;
        }
        label = this.addLabel(player, rank);
        if (!label) {
            break;
        }
        label.x = 0;
        label.y = rank * label.height + 10;
    }
};

module.exports = LeaderBoardUI;

})();

<commit_msg>add self rank background<commit_after>(function(){ 'use strict';

var Util = require("../modules/util");

var cfg = {
    font: "16px Open Sans",
    align: "left",
    weight: "normal",
    fills: [
        "#f94b3c",
        "#e38e34",
        "#eeda3f",
        "#65737e",
        "#7d8b96",
        "#6c7f8c",
        "#5a7080",
        "#425d6f",
    ],
    selfbg: "#176687",
    selfbgAlpha: 0.3,
    selfbgRadius: 8,
    width: 200,
    nameWidth: 160,
    height: 18,
    paddingX: 12,
    paddingY: 3,
    updateFrame: 30,
};

function LeaderBoardUI(world)
{
    this.world = world;

    this.topCount = cfg.fills.length;
    this.lastUpdateFrame = 0;
    this.labels = {};
    this.expLabels = {};
    this.exps = {};

    this.ui = new PIXI.Container();
    this.ui.x = this.world.viewW - cfg.width - cfg.paddingX;
    this.ui.y = 0;
    this.world.stage.addChild(this.ui);
}

LeaderBoardUI.prototype = {
    constructor: LeaderBoardUI
};

LeaderBoardUI.prototype.addLabel = function(player, rank)
{
    if (!player || rank < 0 || rank >= this.topCount) {
        Util.logError("invald player rank=" + rank + 1);
        return null;
    }
    var labelCfg = {
        fill: cfg.fills[rank],
        font: cfg.font,
        fontWeight: cfg.weight,
        align: cfg.align
    };

    var label = new PIXI.Container();

    if (player === this.world.getSelf()) {
        var graphics = new PIXI.Graphics();
        graphics.beginFill(cfg.selfbg);
        graphics.drawRoundedRect(0, 0, cfg.width - cfg.paddingX, cfg.height, cfg.selfbgRadius);
        graphics.endFill();
        var bgSprite = new PIXI.Sprite(graphics.generateTexture());
        bgSprite.alpha = cfg.selfbgAlpha;
        label.addChild(bgSprite);
    }

    var nameLabel = new PIXI.Text(String(Number(rank) + 1) + "  " + player.name, labelCfg);
    nameLabel.x = cfg.paddingX;
    label.addChild(nameLabel);

    var expLabel = new PIXI.Text(String(player.tank.exp), labelCfg);
    expLabel.x = cfg.nameWidth;
    label.addChild(expLabel);

    label.scale.x = 1;
    label.scale.y = cfg.height / label.height;

    this.labels[player.connid] = label;
    this.ui.addChild(label);
    return label;
};

LeaderBoardUI.prototype.update = function()
{
    if (this.world.playerCount <= 0) {
        return;
    }
    this.ui.visible = true;

    if (this.world.frame < this.lastUpdateFrame + cfg.updateFrame) {
        return;
    }
    this.lastUpdateFrame = this.world.frame;

    var label;
    for (var idx in this.labels) {
        label = this.labels[idx];
        if (label) {
            this.ui.removeChild(label);
        }
    }
    this.labels = [];

    for (var rank in this.world.rankPlayers) {
        var player = this.world.rankPlayers[rank];
        if (!player || !player.tank) {
            continue;
        }
        label = this.addLabel(player, rank);
        if (!label) {
            break;
        }
        label.x = cfg.paddingX;
        label.y = rank * (cfg.height + cfg.paddingY) + cfg.paddingY;
    }
};

module.exports = LeaderBoardUI;

})();

<|endoftext|>


<commit_before>angular.module('TrackerApp', [])
.factory('LocationService', function($http, $q){
	var apiUrl = "http://localhost:3000/api"
	var o = {};

	o.getCurrLocation = function(){
		var deferred = $q.defer();

		$http.get(apiUrl + '/tracker/location/data').then(function(response){
			console.log(response.data[0]);
			deferred.resolve({ status: 'SUCCESS', location: response.data[0]});
		}, function(err){
			console.log(err);
			deferred.reject({ status: 'ERROR', error: err });
		});

		return deferred.promise;
	}

	return o;
})
.controller('MainCtrl', function($scope, $interval, LocationService){
	var initializeMap = function(centerPos){
		console.log(centerPos);
		var center = new google.maps.LatLng(centerPos.coords.latitude, centerPos.coords.longitude);

		var mapProp = {
			center: center,
    		zoom:14,
    		mapTypeId:google.maps.MapTypeId.ROADMAP
		}

		$scope.map = new google.maps.Map($("#googleMap")[0], mapProp);
		$scope.locations = [];

		var marker = new google.maps.Marker({
    		position: center,
    		map: $scope.map,
    		title: 'GZ'
  		});
	}

	var geoCenter = {
		coords: {
			latitude: 6.9344,
			longitude: 79.8428
		}
	}

	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(initializeMap);
	}
	else{
		initializeMap(geoCenter);
	}

	$interval(function(){
		LocationService.getCurrLocation().then(function(result){
			var lastLoc = $scope.locations[$scope.locations.length - 1];
			console.log(lastLoc);
			if($scope.locations.length == 0 || result.location.timestamp > lastLoc.timestamp){
				$scope.locations.push(result.location);
				console.log($scope.locations);
			}
		});
	}, 2000);
});<commit_msg>Visualize path on the map<commit_after>angular.module('TrackerApp', [])
.factory('LocationService', function($http, $q){
	var apiUrl = "http://localhost:3000/api"
	var o = {};

	o.getCurrLocation = function(){
		var deferred = $q.defer();

		$http.get(apiUrl + '/tracker/location/data').then(function(response){
			console.log(response.data[0]);
			deferred.resolve({ status: 'SUCCESS', location: response.data[0].location});
		}, function(err){
			console.log(err);
			deferred.reject({ status: 'ERROR', error: err });
		});

		return deferred.promise;
	}

	return o;
})
.controller('MainCtrl', function($scope, $interval, LocationService){
	var initializeMap = function(centerPos){
		console.log(centerPos);
		var center = new google.maps.LatLng(centerPos.coords.latitude, centerPos.coords.longitude);

		var mapProp = {
			center: center,
    		zoom:14,
    		mapTypeId:google.maps.MapTypeId.ROADMAP
		}

		$scope.map = new google.maps.Map($("#googleMap")[0], mapProp);
		$scope.trackerPath = new Array();

		$scope.path = new google.maps.Polyline({
			path: $scope.trackerPath,
			geodesic: true,
          	strokeColor: '#FF0000',
          	strokeOpacity: 1.0,
          	strokeWeight: 2
		});

		$scope.path.setMap($scope.map);

		$scope.locations = [];

		var marker = new google.maps.Marker({
    		position: center,
    		map: $scope.map,
    		title: 'GZ'
  		});
	}

	var geoCenter = {
		coords: {
			latitude: 6.9344,
			longitude: 79.8428
		}
	}

	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(initializeMap);
	}
	else{
		initializeMap(geoCenter);
	}

	$interval(function(){
		LocationService.getCurrLocation().then(function(result){
			var lastLoc = $scope.locations[$scope.locations.length - 1];
			if($scope.locations.length == 0 || result.location.timestamp > lastLoc.timestamp){
				console.log(result);
				$scope.locations.push(result.location);
				$scope.trackerPath.push(new google.maps.LatLng(result.location.lat, result.location.log));
				$scope.path.setPath($scope.trackerPath);
			}
		});
	}, 2000);
});<|endoftext|>


<commit_before>/* Initial sidebar toc toggle button*/
$(document).ready(function () {
    var allEntry = $("div.sphinxsidebarwrapper li");
    var subEntry = $("div.sphinxsidebarwrapper").children("ul").first().children("li");
    if(subEntry.length == 1) {
        allEntry = subEntry.find("li");
        subEntry.children("a").hide();
        subEntry.children("ul").css("padding-left", "0");
        subEntry.parent().css("margin-left", "-20px");
    }
    allEntry.each(function () {
        $(this).prepend("");
        var childUL = $(this).find("ul");
        if(childUL.length && childUL.first().children().length) {
            $(this).addClass("closed");
            $(this).find("ul").first().hide();
        }
        else
            $(this).addClass("leaf");
    });
    $('body').show();
});

/*Sidebar toc toggle button behavior*/
function toggle(elem) {
    if($(elem).parent().hasClass("closed")) {
        $(elem).parent().find("ul").first().show();
        $(elem).parent().removeClass("closed").addClass("opened");
    }
    else if($(elem).parent().hasClass("opened")) {
        $(elem).parent().find("ul").first().hide();
        $(elem).parent().removeClass("opened").addClass("closed");
    }
}<commit_msg>Sidebar auto expand (#3956)<commit_after>/* Initial sidebar toc toggle button*/
$(document).ready(function () {
    var allEntry = $("div.sphinxsidebarwrapper li");
    var subEntry = $("div.sphinxsidebarwrapper").children("ul").first().children("li");
    if(subEntry.length == 1) {
        allEntry = subEntry.find("li");
        subEntry.children("a").hide();
        subEntry.children("ul").css("padding-left", "0");
        subEntry.parent().css("margin-left", "-20px");
    }
    allEntry.each(function () {
        $(this).prepend("");
        var childUL = $(this).find("ul");
        if(childUL.length && childUL.first().children().length) {
            $(this).addClass("closed");
            $(this).find("ul").first().hide();
        }
        else
            $(this).addClass("leaf");
        var anchor = $(this).children("a").first();
        anchor.click(function () {
            autoExpand(anchor);
        });
    });
    $('body').show();
});

/*Sidebar toc toggle button behavior*/
function toggle(elem) {
    if($(elem).parent().hasClass("closed")) {
        $(elem).parent().find("ul").first().show();
        $(elem).parent().removeClass("closed").addClass("opened");
    }
    else if($(elem).parent().hasClass("opened")) {
        $(elem).parent().find("ul").first().hide();
        $(elem).parent().removeClass("opened").addClass("closed");
    }
}

/*Automatically expand child level while cilcking an entry*/
function autoExpand(elem) {
    elem.parent().removeClass("closed").addClass("opened");
    elem.parent().children("ul").first().show();
}<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var template = require('./time-series-header.tpl');
var d3 = require('d3');

/**
 * View to reset render range.
 */
module.exports = cdb.core.View.extend({
  className: 'CDB-Widget-header--timeSeries js-header CDB-Widget-contentSpaced',
  events: {
    'click .js-clear': '_onClick'
  },

  initialize: function () {
    this._dataviewModel = this.options.dataviewModel;
    this._rangeFilter = this.options.rangeFilter;
    this._rangeFilter.bind('change', this.render, this);
    this._setupScales();
  },

  render: function () {
    this.$el.empty();
    if (!this._rangeFilter.isEmpty()) {
      this.$el.html(
        template({
          timeFormatter: this._timeFormatter,
          dateFormatter: this._dateFormatter,
          startDate: new Date(this._scale.invert(this._rangeFilter.get('min'))),
          endDate: new Date(this._scale.invert(this._rangeFilter.get('max')))
        })
      );
    }
    return this;
  },

  _setupScales: function () {
    var data = this._dataviewModel.get('data');
    this._scale = d3.time.scale()
      .domain([data[0].start * 1000, data[data.length - 1].end * 1000])
      .nice()
      .range([0, this._dataviewModel.get('bins')]);

    // for format rules see https://github.com/mbostock/d3/wiki/Time-Formatting
    this._timeFormatter = d3.time.format('%H:%M');
    this._dateFormatter = d3.time.format('%x');
  },

  _onClick: function () {
    this.trigger('resetFilter', this);
  }
});
<commit_msg>Fixing time series header scale<commit_after>var cdb = require('cartodb.js');
var template = require('./time-series-header.tpl');
var d3 = require('d3');

/**
 * View to reset render range.
 */
module.exports = cdb.core.View.extend({
  className: 'CDB-Widget-header--timeSeries js-header CDB-Widget-contentSpaced',
  events: {
    'click .js-clear': '_onClick'
  },

  initialize: function () {
    this._dataviewModel = this.options.dataviewModel;
    this._rangeFilter = this.options.rangeFilter;
    this._rangeFilter.bind('change', this.render, this);
    this._setupScales();
  },

  render: function () {
    this.$el.empty();
    if (!this._rangeFilter.isEmpty()) {
      this.$el.html(
        template({
          timeFormatter: this._timeFormatter,
          dateFormatter: this._dateFormatter,
          startDate: new Date(this._scale.invert(this._rangeFilter.get('min'))),
          endDate: new Date(this._scale.invert(this._rangeFilter.get('max')))
        })
      );
    }
    return this;
  },

  _setupScales: function () {
    var data = this._dataviewModel.get('data');
    this._scale = d3.time.scale()
      .domain([data[0].start * 1000, data[data.length - 1].end * 1000])
      .nice()
      .range([this._dataviewModel.get('start'), this._dataviewModel.get('end')]);

    // for format rules see https://github.com/mbostock/d3/wiki/Time-Formatting
    this._timeFormatter = d3.time.format('%H:%M');
    this._dateFormatter = d3.time.format('%x');
  },

  _onClick: function () {
    this.trigger('resetFilter', this);
  }
});
<|endoftext|>


<commit_before>$(function() {
	// this will hold the JSON array of all units
	var units;
	// total items in the carousel (needs to be odd)
	var carouselLength = 7;
	// essentially, the amount on each side after you remove the middle
	var modValue = (carouselLength - 1) / 2;

	// Get the units data as an array
	$.getJSON("data.json", function(results) {
		// set the global var
		units = results;
		// draw the carousel
		drawCarousel();
		// preload all the images
		preloadImages(units);
		// add an EL for any carousel divs
		// it's important to note that the EL is bound to document on purpose
		// since the events are on dom elements not added at runtime, we have to do this
		$(document).on("click", ".unit-carousel-div", function(e) {
			selectedUnit = $(e.target).data("id");
			updateCarousel();
			updateCard(selectedUnit);
		});

	});

	function drawCarousel() {
		clearCarousel();
		// start at -mod
		var i = modValue * -1;
		// go until positive mod, should result in carouselLength iterations
		while (i <= modValue) {
			// grabs a spot from the unit array
			var index = Math.abs((units.length + selectedUnit + i) % units.length);
			// add in the div we'll build on
			var unitDiv = document.createElement("div");
			// add the class and data id (index)
			$(unitDiv).addClass("unit-carousel-div");
			$(unitDiv).data("id", index);
			// add in the background images
			$(unitDiv).css("background", "url('../images/frame.png'), url('avatars/" + units[index].name + ".jpg')");
			// add it to the carousel
			$("#carousel").append(unitDiv);
			i++;
		}
	}

	function updateCarousel() {
		var i = modValue * -1;
		$(".unit-carousel-div").each(function(index) {
			// grabs a spot from the unit array
			var unitIndex = Math.abs((units.length + selectedUnit + i) % units.length);
			// add in the data id
			$(this).data("id", unitIndex);
			// add in the background images
			$(this).css("background", "url('../images/frame.png'), url('avatars/" + units[unitIndex].name + ".jpg')");
			i++;
		});
	}

	function clearCarousel() {
		// remove all the data from the carousel and that's about it
		$("#carousel").html("");
	}

	function preloadImages(unitArr) {
		var images = [];
		var i = 0;
		while (i < unitArr.length) {
			images[i] = new Image();
			images[i].src = "avatars/" + unitArr[i].name + ".jpg";
			i++;
		}
	}

	function updateCard(unitIndex) {
		// set the unit to the selected unit
		var unit = units[unitIndex];
		// update side a
		$(".sideA").css("background-image", "url('/images/cards/margin.png'), url('/units/artwork/" + unit.name + ".jpg')");
		$(".sideA .section.info").removeClass("sin- sinA sinE sinG sinL sinP sinS sinW").addClass("sin" + unit.type.substring(0, 1));
		$(".sideA .type").text(unit.type);
		$(".sideA .name").text(unit.name);
		$(".sideA .hexs").text(unit.size+"H");
	}
});
<commit_msg>made side b start populating stats<commit_after>$(function() {
	// this will hold the JSON array of all units
	var units;
	// total items in the carousel (needs to be odd)
	var carouselLength = 7;
	// essentially, the amount on each side after you remove the middle
	var modValue = (carouselLength - 1) / 2;

	// Get the units data as an array
	$.getJSON("data.json", function(results) {
		// set the global var
		units = results;
		// draw the carousel
		drawCarousel();
		// preload all the images
		preloadImages(units);
		// add an EL for any carousel divs
		// it's important to note that the EL is bound to document on purpose
		// since the events are on dom elements not added at runtime, we have to do this
		$(document).on("click", ".unit-carousel-div", function(e) {
			selectedUnit = $(e.target).data("id");
			updateCarousel();
			updateCard(selectedUnit);
		});

	});

	function drawCarousel() {
		clearCarousel();
		// start at -mod
		var i = modValue * -1;
		// go until positive mod, should result in carouselLength iterations
		while (i <= modValue) {
			// grabs a spot from the unit array
			var index = Math.abs((units.length + selectedUnit + i) % units.length);
			// add in the div we'll build on
			var unitDiv = document.createElement("div");
			// add the class and data id (index)
			$(unitDiv).addClass("unit-carousel-div");
			$(unitDiv).data("id", index);
			// add in the background images
			$(unitDiv).css("background", "url('../images/frame.png'), url('avatars/" + units[index].name + ".jpg')");
			// add it to the carousel
			$("#carousel").append(unitDiv);
			i++;
		}
	}

	function updateCarousel() {
		var i = modValue * -1;
		$(".unit-carousel-div").each(function(index) {
			// grabs a spot from the unit array
			var unitIndex = Math.abs((units.length + selectedUnit + i) % units.length);
			// add in the data id
			$(this).data("id", unitIndex);
			// add in the background images
			$(this).css("background", "url('../images/frame.png'), url('avatars/" + units[unitIndex].name + ".jpg')");
			i++;
		});
	}

	function clearCarousel() {
		// remove all the data from the carousel and that's about it
		$("#carousel").html("");
	}

	function preloadImages(unitArr) {
		var images = [];
		var i = 0;
		while (i < unitArr.length) {
			images[i] = new Image();
			images[i].src = "avatars/" + unitArr[i].name + ".jpg";
			i++;
		}
	}

	function updateCard(unitIndex) {
		// set the unit to the selected unit
		var unit = units[unitIndex];
		// update side a
		$(".sideA").css("background-image", "url('/images/cards/margin.png'), url('/units/artwork/" + unit.name + ".jpg')");
		$(".sideA .section.info").removeClass("sin- sinA sinE sinG sinL sinP sinS sinW").addClass("sin" + unit.type.substring(0, 1));
		$(".sideA .type").text(unit.type);
		$(".sideA .name").text(unit.name);
		$(".sideA .hexs").text(unit.size+"H");
		// update side b
		$(".sideB").css("background-image", "url('/images/cards/margin.png'), url('/images/cards/" + unit.type.substring(0, 1) + ".jpg')");
		for (var property in unit.stats) {
			if (unit.stats.hasOwnProperty(property)) {
				var stat = ".sideB ." + property + " .value";
				$(stat).text(unit.stats[property]);
			}
		}
	}
});
<|endoftext|>