<commit_before>var CouchClient = require('couch-client');
var Data = require('../data');
var _ = require('underscore');
var async = require('async');

var CouchAdapter = function(config, callback) {
  var db = CouchClient(config.url);
  var self = {};

  function serializeQuery(qry) {
    var queryHash = new Data.Hash(qry).sort(Data.Comparators.ASC);
    var queryProperties = [];
    queryHash.each(function(value, property) {
      queryProperties.push(property + "=" + value);
    });
    return queryProperties.join(":").replace(/\//g, '.');
  }

  // flush
  // --------------

  // Flush the database
  self.flush = function(callback) {
    // Delete DB if exists
    db.request("DELETE", db.uri.pathname, function (err) {
      db.request("PUT", db.uri.pathname, function(err) {
        err ? callback(err)
            : db.save({
                _id: '_design/queries',
                views: {}
              }, function (err, doc) {
                err ? callback(err) : callback();
              });
      });
    });
  };

  // writeGraph
  // --------------

  // Takes a Data.Graph and persists it to CouchDB

  self.writeGraph = function(graph, callback) {

    function writeNode(nodeId, callback) {
      var target = _.extend(graph[nodeId], {
        _id: nodeId
      });

      db.save(target, function (err, doc) {
        err ? callback(err) : callback();
      });
    }

    async.forEach(Object.keys(graph), writeNode, function(err) {
      err ? callback(err) : callback();
    });
  };

  // readGraph
  // --------------

  // Takes a query object and reads all matching nodes
  // If you'd like to make a deep fetch, you just need to specify
  // expand: true in the options hash

  self.readGraph = function(qry, targetGraph, options, callback) {

    // Collects the subgraph that will be returned as a result
    var result = {};

    // Reads a node and the related type node
    // --------

    function fetchNode(id, callback) {
      db.get(id, function(err, node) {
        if (err) return callback(err);

        // Attach to result graph
        result[node._id] = node;
        callback(null, node);
      });
    }

    // Performs a query and returns a list of matched nodes
    // --------

    function query(qry, callback) {

      if (!qry) throw "No query specified";

      function executeQuery(qry, callback) {
        var viewId = serializeQuery(qry);
        db.view(db.uri.pathname+'/_design/queries/_view/'+viewId, function(err, res) {
          // Bug-workarount related to https://github.com/creationix/couch-client/issues#issue/3
          // Normally we'd just use the err object in an error case
          res.error ? callback(res.error) : callback(null, _.map(res.rows, function(item) {
            return item.value;
          }));
        });
      };

      function createQuery(qry, callback) {
        var viewId = serializeQuery(qry);

        db.get('_design/queries', function(err, node) {
          if (!err) {
            // Dynamically generate a view function
            var conditions = [];
            var fn = "function(doc) { if (##conditions##) emit(doc._id, doc); }";

            _.each(qry, function(value, key) {
              // Extract operator
              var matches = key.match(/^([a-z_]{1,30})(!=|>|>=|<|<=|\|=)?$/),
                  property = matches[1],
                  operator = matches[2] || '==';

              if (operator === "|=") { // one of operator
                var values = _.isArray(value) ? value : [value];
                var subconditions = [];
                _.each(values, function(val) {
                  subconditions.push("doc."+property+".indexOf(\""+val+"\") >= 0");
                });
                conditions.push("("+subconditions.join(' || ')+")");
              } else { // regular operators
                conditions.push("doc."+property+" "+operator+" "+(typeof value === "string" ? "\""+value+"\"": value));
              }
            });

            fn = fn.replace('##conditions##', conditions.join(' && '));

            node.views[viewId] = { map: fn };
            db.save(node, function(err, doc) {
              err ? callback('Error during saving the view') : callback();
            });
          } else {
            throw('_design/queries not found.');
          }
        });
      }

      async.waterfall([
        // Query view
        function(callback) {
          executeQuery(qry, function(err, matchedNodes) {
            err ? callback(null,false, null) : callback(null, true, matchedNodes);
          });
        },

        // Create a view if not exists
        function(done, matchedNodes, callback) {
          if (done) return callback(null, matchedNodes);
          createQuery(qry, function(err) {
            if (err) return callback('Error during view creation');
            // And now execute it.
            executeQuery(qry, function(err, matchedNodes) {
              err ? callback(err) : callback(null, matchedNodes);
            });
          });
        }
      ], function(err, matchedNodes) {
        err ? callback(err) : callback(null, matchedNodes);
      });
    };

    // Fetches associated objects
    function fetchAssociated(nodeKey, callback) {

      // Assumes that corresponding type nodes are already there
      var node = result[nodeKey];
      var type = result[node.type];

      async.forEach(Object.keys(type.properties), function(propertyKey, callback) {
        var property = type.properties[propertyKey];

        if (!Data.isValueType(property.expected_type)) {
          nodes = _.isArray(node[propertyKey]) ? node[propertyKey] : [node[propertyKey]];
          async.forEach(nodes, function(item, callback) {

            if (!result[item]) {
              fetchNode(item, function(err, node) {
                if (err) return callback(err);
                result[node._id] = node;

                // Fetch corresponding type node
                if (!result[node.type]) {
                  fetchNode(node.type, function(err, typeNode) {
                    if (err) return callback(err);
                    result[typeNode._id] = typeNode;

                    // Go deeper
                    fetchAssociated(node._id, function(err) {
                      err ? callback(err) : callback();
                    });
                  });
                } else {
                  // Go deeper
                  fetchAssociated(node._id, function(err) {
                    err ? callback(err) : callback();
                  });
                }
              });
            } else {
              callback();
            }
          }, function(err) { callback(); });

        } else { callback(); }
      }, function(err) {
        // All properties resolved
        callback();
      });
    }

    // Start the fun
    query(qry, function(err, nodes) {
      types = {};

      if (err) return callback(err);

      _.each(nodes, function(node) {
        // Attach node to the result graph
        result[node._id] = node;

        // Unless type node, collect type for schema purposes
        if (node.type !== "type" && node.type !== "/type/type" && !result[node.type]) {
          types[node.type] = node.type;
        }
      });

      // Fetch all referenced type nodes in parallel
      async.forEach(Object.keys(types), function(item, callback) {
        fetchNode(item, function(err, typeNode) {
          if (err) return callback(err);
          result[typeNode._id] = typeNode;
          callback();
        });
      }, function(err) {
        if (err) return callback(err);

        // Prefetch associated nodes
        if (options.expand) {
          async.forEach(Object.keys(result), function(item, callback) {
            if (result[item].type !== 'type' && result[item].type !== '/type/type') {
              fetchAssociated(item, function(err) {
                err ? callback('error during fetching assciated nodes') : callback();
              });
            } else {
              callback();
            }
          }, function(err) { callback(null, result); });
        } else {
         callback(null, result);
        }
      });
    });
  };

  self.db = db;

  // Expose Public API
  return self;
};

module.exports = CouchAdapter;<commit_msg>CouchAdapter is now aware of Prototypal Inheritance.<commit_after>var CouchClient = require('couch-client');
var Data = require('../data');
var _ = require('underscore');
var async = require('async');

var CouchAdapter = function(config, callback) {
  var db = CouchClient(config.url);
  var self = {};

  function serializeQuery(qry) {
    var queryHash = new Data.Hash(qry).sort(Data.Comparators.ASC);
    var queryProperties = [];
    queryHash.each(function(value, property) {
      queryProperties.push(property + "=" + value);
    });
    return queryProperties.join(":").replace(/\//g, '.');
  }

  // flush
  // --------------

  // Flush the database
  self.flush = function(callback) {
    // Delete DB if exists
    db.request("DELETE", db.uri.pathname, function (err) {
      db.request("PUT", db.uri.pathname, function(err) {
        err ? callback(err)
            : db.save({
                _id: '_design/queries',
                views: {
                  "all_type_nodes": {
                    "map": "function(doc) { if (doc.type === \"/type/type\") emit(doc._id, doc); }"
                  }
                }
              }, function (err, doc) {
                err ? callback(err) : callback();
              });
      });
    });
  };

  // writeGraph
  // --------------

  // Takes a Data.Graph and persists it to CouchDB

  self.writeGraph = function(graph, callback) {

    function writeNode(nodeId, callback) {
      var target = _.extend(graph[nodeId], {
        _id: nodeId
      });

      db.save(target, function (err, doc) {
        err ? callback(err) : callback();
      });
    }

    async.forEach(Object.keys(graph), writeNode, function(err) {
      err ? callback(err) : callback();
    });
  };

  // readGraph
  // --------------

  // Takes a query object and reads all matching nodes
  // If you'd like to make a deep fetch, you just need to specify
  // expand: true in the options hash

  self.readGraph = function(qry, targetGraph, options, callback) {

    // Collects the subgraph that will be returned as a result
    var result = {};
    var sharedTypes = {};

    // Fetches a node from the DB
    // --------

    function fetchNode(id, callback) {
      db.get(id, function(err, node) {
        if (err) return callback(err);

        // Attach to result graph
        result[node._id] = node;
        callback(null, node);
      });
    }

    // Performs a query and returns a list of matched nodes
    // --------

    function query(qry, callback) {

      if (!qry) throw "No query specified";

      function executeQuery(qry, callback) {
        var viewId = serializeQuery(qry);
        db.view(db.uri.pathname+'/_design/queries/_view/'+viewId, function(err, res) {
          // Bug-workarount related to https://github.com/creationix/couch-client/issues#issue/3
          // Normally we'd just use the err object in an error case
          res.error ? callback(res.error) : callback(null, _.map(res.rows, function(item) {
            return item.value;
          }));
        });
      };

      function createQuery(qry, callback) {
        var viewId = serializeQuery(qry);

        db.get('_design/queries', function(err, node) {
          if (!err) {
            // Dynamically generate a view function
            var conditions = [];
            var fn = "function(doc) { if (##conditions##) emit(doc._id, doc); }";

            _.each(qry, function(value, key) {
              // Extract operator
              var matches = key.match(/^([a-z_]{1,30})(!=|>|>=|<|<=|\|=)?$/),
                  property = matches[1],
                  operator = matches[2] || '==';

              if (operator === "|=") { // one of operator
                var values = _.isArray(value) ? value : [value];
                var subconditions = [];
                _.each(values, function(val) {
                  subconditions.push("doc."+property+".indexOf(\""+val+"\") >= 0");
                });
                conditions.push("("+subconditions.join(' || ')+")");
              } else { // regular operators
                conditions.push("doc."+property+" "+operator+" "+(typeof value === "string" ? "\""+value+"\"": value));
              }
            });

            fn = fn.replace('##conditions##', conditions.join(' && '));

            node.views[viewId] = { map: fn };
            db.save(node, function(err, doc) {
              err ? callback('Error during saving the view') : callback();
            });
          } else {
            throw('_design/queries not found.');
          }
        });
      }

      async.waterfall([
        // Query view
        function(callback) {
          executeQuery(qry, function(err, matchedNodes) {
            err ? callback(null,false, null) : callback(null, true, matchedNodes);
          });
        },

        // Create a view if not exists
        function(done, matchedNodes, callback) {
          if (done) return callback(null, matchedNodes);
          createQuery(qry, function(err) {
            if (err) return callback('Error during view creation');
            // And now execute it.
            executeQuery(qry, function(err, matchedNodes) {
              err ? callback(err) : callback(null, matchedNodes);
            });
          });
        }
      ], function(err, matchedNodes) {
        err ? callback(err) : callback(null, matchedNodes);
      });
    };

    // Fetches associated objects
    function fetchAssociated(nodeKey, callback) {

      // Assumes that corresponding type nodes are already there
      var node = result[nodeKey];
      var types = _.isArray(node.type) ? node.type : [node.type];

      var properties = [];
      _.each(types, function(type) {
        _.each(result[type].properties, function(property, key) {
          properties.push({
            key: key,
            // Ensure that type property is always an array (of allowed types for the property)
            type: _.isArray(property.type) ? property.type : [property.type]
          });
        });
      });

      // Combine properties

      async.forEach(properties, function(property, callback) {
        // Assumes that a property allows either object types or value types
        if (!Data.isValueType(property.type[0])) {
          nodes = _.isArray(node[property.key]) ? node[property.key] : [node[property.key]];
          async.forEach(nodes, function(item, callback) {

            if (!result[item]) {
              fetchNode(item, function(err, node) {
                if (err) return callback(err);
                result[node._id] = node;
                fetchAssociated(node._id, function(err) {
                  err ? callback(err) : callback();
                });

              });
            } else {
              callback();
            }
          }, function(err) { callback(); });

        } else { callback(); }
      }, function(err) {
        // All properties resolved
        callback();
      });
    }

    // First of all fetch all type nodes
    db.view(db.uri.pathname+'/_design/queries/_view/all_type_nodes', function(err, res) {
      // Bug-workarount related to https://github.com/creationix/couch-client/issues#issue/3
      // Normally we'd just use the err object in an error case

      if (!res.error) {
        _.each(res.rows, function(item) {
          // return item.value;
          result[item.value._id] = item.value;
        });

        // Start the fun
        query(qry, function(err, nodes) {
          if (err) return callback(err);
          _.each(nodes, function(node) {
            result[node._id] = node; // Attach node to the result graph
          });

          // Prefetch associated nodes
          if (options.expand) {
            async.forEach(Object.keys(result), function(item, callback) {
              if (result[item].type !== 'type' && result[item].type !== '/type/type') {
                fetchAssociated(item, function(err) {
                  err ? callback('error during fetching assciated nodes') : callback();
                });
              } else {
                callback();
              }
            }, function(err) { callback(null, result); });
          } else {
           callback(null, result); // super ready
          }
        });
      } else {
        callback(res.error)
      }
    });

  };

  self.db = db;

  // Expose Public API
  return self;
};

module.exports = CouchAdapter;<|endoftext|>


<commit_before>define('editor-plugin-sticky-toolbar', [], function () {
  return function(toolbarNode, options) {
    return function() {
      var toolbarOffsetTop,
          scrolled = false;

      var getViewportOffsetTop = function(node) {
        var curTop = 0;

        while (node.tagName !== 'BODY') {
          curTop += node.offsetTop;
          node = node.offsetParent;
        }
        return curTop;
      };

      // Listen for scroll - TODO Debounce
      document.addEventListener('scroll', function () {
        if(!scrolled){
          toolbarOffsetTop = getViewportOffsetTop(toolbarNode);
          scrolled = true;
        }
        toolbarNode.classList.toggle('is-sticky', (toolbarOffsetTop <= window.scrollY));
      });
    };
  };
});
<commit_msg>Debounce scroll event<commit_after>define('editor-plugin-sticky-toolbar', [], function () {
  return function(toolbarNode, options) {
    return function() {
      var getViewportOffsetTop,
          toolbarOffsetTop,
          scrolled = false,
          debounce;

      getViewportOffsetTop = function(node) {
        var curTop = 0;

        while (node.tagName !== 'BODY') {
          curTop += node.offsetTop;
          node = node.offsetParent;
        }
        return curTop;
      };

      document.addEventListener('scroll', function () {
        clearTimeout(debounce);
        debounce = setTimeout(function() {
          if(!scrolled){
            toolbarOffsetTop = getViewportOffsetTop(toolbarNode);
            scrolled = true;
          }
          toolbarNode.classList.toggle('is-sticky', (toolbarOffsetTop <= window.scrollY));
        }, 120);
      });
    };
  };
});
<|endoftext|>


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

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, PathUtils */

/*
 * Adds a "find in files" command to allow the user to find all occurances of a string in all files in
 * the project.
 *
 * The keyboard shortcut is Cmd(Ctrl)-Shift-F.
 *
 * FUTURE:
 *  - Proper UI for both dialog and results
 *  - Refactor dialog class and share with Quick File Open
 *  - Search files in working set that are *not* in the project
 *  - Handle matches that span mulitple lines
 *  - Refactor UI from functionality to enable unit testing
 *  - Cache result of getLine()
 */

define(function (require, exports, module) {
    'use strict';

    var Async               = require("utils/Async"),
        CommandManager      = require("command/CommandManager"),
        Commands            = require("command/Commands"),
        DocumentManager     = require("document/DocumentManager"),
        EditorManager       = require("editor/EditorManager"),
        FileIndexManager    = require("project/FileIndexManager");

    // This dialog class was mostly copied from QuickFileOpen. We should have a common dialog
    // class that everyone can use.

    /**
    * FindInFilesDialog class
    * @constructor
    *
    */
    function FindInFilesDialog() {
        this.closed = false;
        this.result = null; // $.Deferred
    }

    /**
    * Creates a dialog div floating on top of the current code mirror editor
    */
    FindInFilesDialog.prototype._createDialogDiv = function (template) {
        var wrap = $("#editorHolder")[0];
        this.dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
        this.dialog.className = "CodeMirror-dialog";
        this.dialog.innerHTML = '
' + template + '
';
    };

    /**
    * Closes the search dialog and resolves the promise that showDialog returned
    */
    FindInFilesDialog.prototype._close = function (value) {
        if (this.closed) {
            return;
        }

        this.closed = true;

        this.dialog.parentNode.removeChild(this.dialog);

        this.result.resolve(value);
    };

    /**
    * Shows the search dialog
    * @param {?string} initialString Default text to prepopulate the search field with
    * @returns {$.Promise} that is resolved with the string to search for
    */
    FindInFilesDialog.prototype.showDialog = function (initialString) {
        var dialogHTML = 'Find in Files: <input type="text" id="findInFilesInput" style="width: 10em"> (Use /re/ syntax for regexp search)';
        this.result = new $.Deferred();
        this._createDialogDiv(dialogHTML);
        var searchField = $('input#findInFilesInput');
        var that = this;

        searchField.attr("value", initialString || "");
        searchField.get(0).select();

        searchField.bind("keydown", function (event) {
            if (event.keyCode === 13 || event.keyCode === 27) {  // Enter/Return key or Esc key
                event.stopPropagation();
                event.preventDefault();

                var query = searchField.val();

                if (event.keyCode === 27) {
                    query = null;
                }

                that._close(query);
            }
        })
            .blur(function () {
                that._close(null);
            })
            .focus();

        return this.result.promise();
    };

    function _getSearchMatches(contents, queryExpr) {
        // Quick exit if not found
        if (contents.search(queryExpr) === -1) {
            return null;
        }

        var trimmedContents = contents;
        var startPos = 0;
        var matchStart;
        var matches = [];

        function getLineNum(offset) {
            return contents.substr(0, offset).split("\n").length - 1; // 0 based linenum
        }

        function getLine(lineNum) {
            // Future: cache result
            return contents.split("\n")[lineNum];
        }

        var match;
        while ((match = queryExpr.exec(contents)) !== null) {
            var lineNum = getLineNum(match.index);
            var line = getLine(lineNum);
            var ch = match.index - contents.lastIndexOf("\n", match.index) - 1;  // 0-based index
            var matchLength = match[0].length;

            // Don't store more than 200 chars per line
            line = line.substr(0, Math.min(200, line.length));

            matches.push({
                start: {line: lineNum, ch: ch},
                end: {line: lineNum, ch: ch + matchLength},
                line: line
            });
        }

        return matches;
    }

    function _showSearchResults(searchResults) {
        var $searchResultsDiv = $("#search-results");

        if (searchResults && searchResults.length) {
            var resultTable = $("
")
                                .append("
");

            // Count the total number of matches
            var numMatches = 0;
            searchResults.forEach(function (item) {
                numMatches += item.matches.length;
            });

            // Show result summary in header
            $("#search-result-summary")
                .text(" - " + numMatches + " match" + (numMatches > 1 ? "es" : "") +
                      " in " + searchResults.length + " file" + (searchResults.length > 1 ? "s" : "") +
                     (numMatches > 100 ? " (showing the first 100 matches)" : ""));

            var resultsDisplayed = 0;

            searchResults.forEach(function (item) {
                if (item && resultsDisplayed < 100) {
                    var makeCell = function (content) {
                        return $("").html(content);
                    };

                    var esc = function (str) {
                        str = str.replace(/</g, "<");
                        str = str.replace(/>/g, ">");
                        return str;
                    };

                    var highlightMatch = function (line, start, end) {
                        return esc(line.substr(0, start)) + "" + esc(line.substring(start, end)) + "" + esc(line.substr(end));
                    };

                    // Add row for file name
                    $("
")
                        .append("File: " + item.fullPath + "	")
                        .appendTo(resultTable);

                    // Add row for each match in file
                    item.matches.forEach(function (match) {
                        if (resultsDisplayed < 100) {
                            var row = $("
")
                                .append(makeCell(" "))      // Indent
                                .append(makeCell("line: " + (match.start.line + 1)))
                                .append(makeCell(highlightMatch(match.line, match.start.ch, match.end.ch)))
                                .appendTo(resultTable);

                            row.click(function () {
                                CommandManager.execute(Commands.FILE_OPEN, {fullPath: item.fullPath})
                                    .done(function (doc) {
                                        // Opened document is now the current main editor
                                        EditorManager.getCurrentFullEditor().setSelection(match.start, match.end);
                                    });
                            });
                            resultsDisplayed++;
                        }
                    });

                }
            });

            $("#search-results .table-container")
                .empty()
                .append(resultTable);

            $("#search-results .close")
                .one("click", function () {
                    $searchResultsDiv.hide();
                    EditorManager.resizeEditor();
                });

            $searchResultsDiv.show();
        } else {
            $searchResultsDiv.hide();
        }

        EditorManager.resizeEditor();
    }

    function _getQueryRegExp(query) {
        // If query is a regular expression, use it directly
        var isRE = query.match(/^\/(.*)\/(g|i)*$/);
        if (isRE) {
            // Make sure the 'g' flag is set
            var flags = isRE[2] || "g";
            if (flags.search("g") === -1) {
                flags += "g";
            }
            return new RegExp(isRE[1], flags);
        }

        // Query is a string. Turn it into a case-insensitive regexp

        // Escape regex special chars
        query = query.replace(/(\(|\)|\{|\}|\[|\]|\.|\^|\$|\||\?|\+|\*)/g, "\\$1");
        return new RegExp(query, "gi");
    }

    /**
    * Displays a non-modal embedded dialog above the code mirror editor that allows the user to do
    * a find operation across all files in the project.
    */
    function doFindInFiles() {

        var dialog = new FindInFilesDialog();
        var searchResults = [];

        // Default to searching for the current selection
        var currentEditor = EditorManager.getFocusedEditor();
        var initialString = currentEditor && currentEditor.getSelectedText();

        dialog.showDialog(initialString)
            .done(function (query) {
                if (query) {
                    var queryExpr = _getQueryRegExp(query);
                    FileIndexManager.getFileInfoList("all")
                        .done(function (fileListResult) {
                            Async.doInParallel(fileListResult, function (fileInfo) {
                                var result = new $.Deferred();

                                DocumentManager.getDocumentForPath(fileInfo.fullPath)
                                    .done(function (doc) {
                                        var matches = _getSearchMatches(doc.getText(), queryExpr);

                                        if (matches && matches.length) {
                                            searchResults.push({
                                                fullPath: fileInfo.fullPath,
                                                matches: matches
                                            });
                                        }
                                        result.resolve();
                                    })
                                    .fail(function (error) {
                                        // Error reading this file. This is most likely because the file isn't a text file.
                                        // Resolve here so we move on to the next file.
                                        result.resolve();
                                    });

                                return result.promise();
                            })
                                .done(function () {
                                    console.dir(searchResults);
                                    _showSearchResults(searchResults);
                                })
                                .fail(function () {
                                    console.log("find in files failed.");
                                });
                        });
                }
            });
    }

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

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, PathUtils */

/*
 * Adds a "find in files" command to allow the user to find all occurances of a string in all files in
 * the project.
 *
 * The keyboard shortcut is Cmd(Ctrl)-Shift-F.
 *
 * FUTURE:
 *  - Proper UI for both dialog and results
 *  - Refactor dialog class and share with Quick File Open
 *  - Search files in working set that are *not* in the project
 *  - Handle matches that span mulitple lines
 *  - Refactor UI from functionality to enable unit testing
 *  - Cache result of getLine()
 */

define(function (require, exports, module) {
    'use strict';

    var Async               = require("utils/Async"),
        CommandManager      = require("command/CommandManager"),
        Commands            = require("command/Commands"),
        DocumentManager     = require("document/DocumentManager"),
        EditorManager       = require("editor/EditorManager"),
        FileIndexManager    = require("project/FileIndexManager");

    // This dialog class was mostly copied from QuickFileOpen. We should have a common dialog
    // class that everyone can use.

    /**
    * FindInFilesDialog class
    * @constructor
    *
    */
    function FindInFilesDialog() {
        this.closed = false;
        this.result = null; // $.Deferred
    }

    /**
    * Creates a dialog div floating on top of the current code mirror editor
    */
    FindInFilesDialog.prototype._createDialogDiv = function (template) {
        var wrap = $("#editorHolder")[0];
        this.dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
        this.dialog.className = "CodeMirror-dialog";
        this.dialog.innerHTML = '
' + template + '
';
    };

    /**
    * Closes the search dialog and resolves the promise that showDialog returned
    */
    FindInFilesDialog.prototype._close = function (value) {
        if (this.closed) {
            return;
        }

        this.closed = true;
        this.dialog.parentNode.removeChild(this.dialog);
        EditorManager.focusEditor();
        this.result.resolve(value);
    };

    /**
    * Shows the search dialog
    * @param {?string} initialString Default text to prepopulate the search field with
    * @returns {$.Promise} that is resolved with the string to search for
    */
    FindInFilesDialog.prototype.showDialog = function (initialString) {
        var dialogHTML = 'Find in Files: <input type="text" id="findInFilesInput" style="width: 10em"> (Use /re/ syntax for regexp search)';
        this.result = new $.Deferred();
        this._createDialogDiv(dialogHTML);
        var searchField = $('input#findInFilesInput');
        var that = this;

        searchField.attr("value", initialString || "");
        searchField.get(0).select();

        searchField.bind("keydown", function (event) {
            if (event.keyCode === 13 || event.keyCode === 27) {  // Enter/Return key or Esc key
                event.stopPropagation();
                event.preventDefault();

                var query = searchField.val();

                if (event.keyCode === 27) {
                    query = null;
                }

                that._close(query);
            }
        })
            .blur(function () {
                that._close(null);
            })
            .focus();

        return this.result.promise();
    };

    function _getSearchMatches(contents, queryExpr) {
        // Quick exit if not found
        if (contents.search(queryExpr) === -1) {
            return null;
        }

        var trimmedContents = contents;
        var startPos = 0;
        var matchStart;
        var matches = [];

        function getLineNum(offset) {
            return contents.substr(0, offset).split("\n").length - 1; // 0 based linenum
        }

        function getLine(lineNum) {
            // Future: cache result
            return contents.split("\n")[lineNum];
        }

        var match;
        while ((match = queryExpr.exec(contents)) !== null) {
            var lineNum = getLineNum(match.index);
            var line = getLine(lineNum);
            var ch = match.index - contents.lastIndexOf("\n", match.index) - 1;  // 0-based index
            var matchLength = match[0].length;

            // Don't store more than 200 chars per line
            line = line.substr(0, Math.min(200, line.length));

            matches.push({
                start: {line: lineNum, ch: ch},
                end: {line: lineNum, ch: ch + matchLength},
                line: line
            });
        }

        return matches;
    }

    function _showSearchResults(searchResults) {
        var $searchResultsDiv = $("#search-results");

        if (searchResults && searchResults.length) {
            var resultTable = $("
")
                                .append("
");

            // Count the total number of matches
            var numMatches = 0;
            searchResults.forEach(function (item) {
                numMatches += item.matches.length;
            });

            // Show result summary in header
            $("#search-result-summary")
                .text(" - " + numMatches + " match" + (numMatches > 1 ? "es" : "") +
                      " in " + searchResults.length + " file" + (searchResults.length > 1 ? "s" : "") +
                     (numMatches > 100 ? " (showing the first 100 matches)" : ""));

            var resultsDisplayed = 0;

            searchResults.forEach(function (item) {
                if (item && resultsDisplayed < 100) {
                    var makeCell = function (content) {
                        return $("").html(content);
                    };

                    var esc = function (str) {
                        str = str.replace(/</g, "<");
                        str = str.replace(/>/g, ">");
                        return str;
                    };

                    var highlightMatch = function (line, start, end) {
                        return esc(line.substr(0, start)) + "" + esc(line.substring(start, end)) + "" + esc(line.substr(end));
                    };

                    // Add row for file name
                    $("
")
                        .append("File: " + item.fullPath + "	")
                        .appendTo(resultTable);

                    // Add row for each match in file
                    item.matches.forEach(function (match) {
                        if (resultsDisplayed < 100) {
                            var row = $("
")
                                .append(makeCell(" "))      // Indent
                                .append(makeCell("line: " + (match.start.line + 1)))
                                .append(makeCell(highlightMatch(match.line, match.start.ch, match.end.ch)))
                                .appendTo(resultTable);

                            row.click(function () {
                                CommandManager.execute(Commands.FILE_OPEN, {fullPath: item.fullPath})
                                    .done(function (doc) {
                                        // Opened document is now the current main editor
                                        EditorManager.getCurrentFullEditor().setSelection(match.start, match.end);
                                    });
                            });
                            resultsDisplayed++;
                        }
                    });

                }
            });

            $("#search-results .table-container")
                .empty()
                .append(resultTable);

            $("#search-results .close")
                .one("click", function () {
                    $searchResultsDiv.hide();
                    EditorManager.resizeEditor();
                });

            $searchResultsDiv.show();
        } else {
            $searchResultsDiv.hide();
        }

        EditorManager.resizeEditor();
    }

    function _getQueryRegExp(query) {
        // If query is a regular expression, use it directly
        var isRE = query.match(/^\/(.*)\/(g|i)*$/);
        if (isRE) {
            // Make sure the 'g' flag is set
            var flags = isRE[2] || "g";
            if (flags.search("g") === -1) {
                flags += "g";
            }
            return new RegExp(isRE[1], flags);
        }

        // Query is a string. Turn it into a case-insensitive regexp

        // Escape regex special chars
        query = query.replace(/(\(|\)|\{|\}|\[|\]|\.|\^|\$|\||\?|\+|\*)/g, "\\$1");
        return new RegExp(query, "gi");
    }

    /**
    * Displays a non-modal embedded dialog above the code mirror editor that allows the user to do
    * a find operation across all files in the project.
    */
    function doFindInFiles() {

        var dialog = new FindInFilesDialog();
        var searchResults = [];

        // Default to searching for the current selection
        var currentEditor = EditorManager.getFocusedEditor();
        var initialString = currentEditor && currentEditor.getSelectedText();

        dialog.showDialog(initialString)
            .done(function (query) {
                if (query) {
                    var queryExpr = _getQueryRegExp(query);
                    FileIndexManager.getFileInfoList("all")
                        .done(function (fileListResult) {
                            Async.doInParallel(fileListResult, function (fileInfo) {
                                var result = new $.Deferred();

                                DocumentManager.getDocumentForPath(fileInfo.fullPath)
                                    .done(function (doc) {
                                        var matches = _getSearchMatches(doc.getText(), queryExpr);

                                        if (matches && matches.length) {
                                            searchResults.push({
                                                fullPath: fileInfo.fullPath,
                                                matches: matches
                                            });
                                        }
                                        result.resolve();
                                    })
                                    .fail(function (error) {
                                        // Error reading this file. This is most likely because the file isn't a text file.
                                        // Resolve here so we move on to the next file.
                                        result.resolve();
                                    });

                                return result.promise();
                            })
                                .done(function () {
                                    console.dir(searchResults);
                                    _showSearchResults(searchResults);
                                })
                                .fail(function () {
                                    console.log("find in files failed.");
                                });
                        });
                }
            });
    }

    CommandManager.register(Commands.EDIT_FIND_IN_FILES, doFindInFiles);
});<|endoftext|>


<commit_before><commit_msg>Fix for Cells when page scaled below 100%.<commit_after><|endoftext|>


<commit_before>import Analyzer from 'parser/core/Analyzer';
import SPELLS from "common/SPELLS/shaman";
import TALENTS from "common/SPELLS/talents/shaman";
import SpellUsable from 'parser/shared/modules/SpellUsable';

class StormFireElemental extends Analyzer {

  static dependencies = {
    spellUsable:SpellUsable,
  };
  elementalData = {
    FireElemental: {
      summon: SPELLS.FIRE_ELEMENTAL.id,
      damageSpells: [
        SPELLS.FIRE_ELEMENTAL_FIRE_BLAST.id,
        SPELLS.FIRE_ELEMENTAL_METEOR.id,
        SPELLS.FIRE_ELEMENTAL_IMMOLATE.id,
      ],
    },
    StormElemental: {
      summon: TALENTS.STORM_ELEMENTAL_TALENT,
      damageSpells: [
        SPELLS.EYE_OF_THE_STORM.id,
        SPELLS.WIND_GUST.id,
        SPELLS.CALL_LIGHTNING.id,
      ],
    },
  };

  last_pet_summon_timeStamp=null;

  relevantData = this.selectedCombatant.hasTalent(TALENTS.STORM_ELEMENTAL_TALENT.id) ? this.data.StormElemental : this.data.FireElemental;

  on_byPlayerPet_damage(event){
      if(this.last_pet_summon_timeStamp!==null) {
        return;
      }
      if(!this.relevant.damageSpells.includes(event.ability.guid)) {
        return;
      }
      this.spellUsable.beginCooldown(this.summon_spell, event.timestamp);
      this.last_pet_summon_timeStamp=event.timestamp;

  }
  on_byPlayer_summon(event) {
    const spellId = event.ability.guid;
    if (spellId !== this.relevant.summon) {
      return;
    }
    this.last_pet_summon_timeStamp=event.timestamp;
  }
}

export default StormFireElemental;
<commit_msg>fix variable name<commit_after>import Analyzer from 'parser/core/Analyzer';
import SPELLS from "common/SPELLS/shaman";
import TALENTS from "common/SPELLS/talents/shaman";
import SpellUsable from 'parser/shared/modules/SpellUsable';

class StormFireElemental extends Analyzer {

  static dependencies = {
    spellUsable:SpellUsable,
  };
  elementalData = {
    FireElemental: {
      summon: SPELLS.FIRE_ELEMENTAL.id,
      damageSpells: [
        SPELLS.FIRE_ELEMENTAL_FIRE_BLAST.id,
        SPELLS.FIRE_ELEMENTAL_METEOR.id,
        SPELLS.FIRE_ELEMENTAL_IMMOLATE.id,
      ],
    },
    StormElemental: {
      summon: TALENTS.STORM_ELEMENTAL_TALENT,
      damageSpells: [
        SPELLS.EYE_OF_THE_STORM.id,
        SPELLS.WIND_GUST.id,
        SPELLS.CALL_LIGHTNING.id,
      ],
    },
  };

  last_pet_summon_timeStamp=null;

  relevantData = this.selectedCombatant.hasTalent(TALENTS.STORM_ELEMENTAL_TALENT.id) ? this.data.StormElemental : this.data.FireElemental;

  on_byPlayerPet_damage(event){
      if(this.last_pet_summon_timeStamp!==null) {
        return;
      }
      if(!this.relevantData.damageSpells.includes(event.ability.guid)) {
        return;
      }
      this.spellUsable.beginCooldown(this.summon_spell, event.timestamp);
      this.last_pet_summon_timeStamp=event.timestamp;

  }
  on_byPlayer_summon(event) {
    const spellId = event.ability.guid;
    if (spellId !== this.relevant.summon) {
      return;
    }
    this.last_pet_summon_timeStamp=event.timestamp;
  }
}

export default StormFireElemental;
<|endoftext|>


<commit_before>import assert from "assert";
import { introspectStarwars } from './introspectStarwars';
import { initTemplateStringTransformer } from '../src/index';
import fs from 'fs';
import path from 'path';

// Uncomment the below to generate a new schema JSON
// describe("graphql", () => {
//   it("can introspect star wars", async () => {
//     const result = await introspectStarwars();
//
//     fs.writeFileSync(path.join(__dirname, "starwars.json"),
//       JSON.stringify(result, null, 2));
//
//     assert.ok(result.data);
//     assert.ok(result.data.__schema);
//   });
// });

describe("runtime query transformer", () => {
  it("can be initialized with an introspected query", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
  });

  it("can compile a Relay.QL query", () => {
    Relay.QL`
      query HeroNameQuery {
        hero {
          name
        }
      }
    `;
  });

  it("can transform a simple query", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
    const transformed = transformer(`
      query HeroNameAndFriendsQuery {
        hero {
          id
          name
          friends {
            name
          }
        }
      }
    `);

    const expected = Relay.QL`
      query HeroNameAndFriendsQuery {
        hero {
          id
          name
          friends {
            name
          }
        }
      }
    `;

    assert.deepEqual(transformed, expected);
  });

  it("can transform a query with arguments", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
    const transformed = transformer(`
      query FetchLukeQuery {
        human(id: "1000") {
          name
        }
      }
    `);

    const expected = Relay.QL`
      query FetchLukeQuery {
        human(id: "1000") {
          name
        }
      }
    `;

    assert.deepEqual(transformed, expected);
  })
});
<commit_msg>Add test for variables<commit_after>import assert from "assert";
import { introspectStarwars } from './introspectStarwars';
import { initTemplateStringTransformer } from '../src/index';
import fs from 'fs';
import path from 'path';

// Uncomment the below to generate a new schema JSON
// describe("graphql", () => {
//   it("can introspect star wars", async () => {
//     const result = await introspectStarwars();
//
//     fs.writeFileSync(path.join(__dirname, "starwars.json"),
//       JSON.stringify(result, null, 2));
//
//     assert.ok(result.data);
//     assert.ok(result.data.__schema);
//   });
// });

describe("runtime query transformer", () => {
  it("can be initialized with an introspected query", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
  });

  it("can compile a Relay.QL query", () => {
    Relay.QL`
      query HeroNameQuery {
        hero {
          name
        }
      }
    `;
  });

  it("can transform a simple query", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
    const transformed = transformer(`
      query HeroNameAndFriendsQuery {
        hero {
          id
          name
          friends {
            name
          }
        }
      }
    `);

    const expected = Relay.QL`
      query HeroNameAndFriendsQuery {
        hero {
          id
          name
          friends {
            name
          }
        }
      }
    `;

    assert.deepEqual(transformed, expected);
  });

  it("can transform a query with arguments", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
    const transformed = transformer(`
      query FetchLukeQuery {
        human(id: "1000") {
          name
        }
      }
    `);

    const expected = Relay.QL`
      query FetchLukeQuery {
        human(id: "1000") {
          name
        }
      }
    `;

    assert.deepEqual(transformed, expected);
  });

  it("can transform a query with variables", async () => {
    const result = await introspectStarwars();
    const transformer = initTemplateStringTransformer(result.data);
    const transformed = transformer(`
      query FetchSomeIDQuery($someId: String!) {
        human(id: $someId) {
          name
        }
      }
    `);

    const expected = Relay.QL`
      query FetchSomeIDQuery($someId: String!) {
        human(id: $someId) {
          name
        }
      }
    `;

    assert.deepEqual(transformed, expected);
  });
});
<|endoftext|>


<commit_before>function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // Normal
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE
      elem.attachEvent("on"+evnt, func);
   }
   else {
      elem[evnt] = func;
   }
}
addEvent("DOMContentLoaded", document, function(event) {
    (function(){
        var binder = {
            dataArrGlob:{},
            dataArrLoc:{},
            addValue:function(n, v, id){
                if (arguments.length == 3) {
                    if(this.dataArrLoc[id] == undefined){
                        this.dataArrLoc[id] = {};
                    }
                    this.dataArrLoc[id][n] = v;
                }
                else if(arguments.length == 2) {
                    this.dataArrGlob[n] = v;
                }
            },
            addArrValues: function(objVal){
                for (var name in objVal) {
                    this.addValue(name, objVal[name]);
                }
            },
            initData: function(){
                for (var keyGlob in this.dataArrGlob) {
                    insertValuesGlob(keyGlob, this.dataArrGlob[keyGlob]);
                }
                //TODO part for localized function
                for (var keyLoc in this.dataArrLoc) {

                }
            },
            printData: function(){
                for (var k in this.dataArrGlob) {
                    console.log( k +" --> "+ this.dataArrGlob[k]);
                }
                for (var j in this.dataArrLoc) {
                    console.log( j );//+" --> "+ this.dataArrLoc[j]["name"]+" : "+this.dataArrLoc[j]["value"]);
                    var propObj = this.dataArrLoc[j];
                    for (var g in propObj) {
                        console.log("-- "+g+" : "+propObj[g]);
                    }
                }
            }
            //TODO
            //sendHTML: function(ajaxReceiver){
            //
            //}
        };
        //TODO function localized replace "insertValuesLoc"
        function insertValuesLoc(id, name, value) {

            return true;
        }

        function insertValuesGlob(name, value) {
            var pattern = new RegExp('{{'+name+'}}', "gi");
            var body = document.getElementsByTagName("body")[0];
            var bodyText = body.innerHTML;
            bodyText = bodyText.replace(pattern, value);
            body.innerHTML = bodyText;
            return true;
        }

        window.Binder = binder;
        window.$B = window.Binder;
    })();
});<commit_msg>Add function to local replace<commit_after>function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // Normal
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE
      elem.attachEvent("on"+evnt, func);
   }
   else {
      elem[evnt] = func;
   }
}
addEvent("DOMContentLoaded", document, function(event) {
    (function(){
        var binder = {
            dataArrGlob:{},
            dataArrLoc:{},
            addValue:function(n, v, id){
                if (arguments.length == 3) {
                    if(this.dataArrLoc[id] == undefined){
                        this.dataArrLoc[id] = {};
                    }
                    this.dataArrLoc[id][n] = v;
                }
                else if(arguments.length == 2) {
                    this.dataArrGlob[n] = v;
                }
            },
            addArrValues: function(objVal){
                for (var name in objVal) {
                    this.addValue(name, objVal[name]);
                }
            },
            initData: function(){
                for (var keyGlob in this.dataArrGlob) {
                    insertValuesGlob(keyGlob, this.dataArrGlob[keyGlob]);
                }
                //TODO part for localized function
                for (var idLoc in this.dataArrLoc) {
                     dataObj = this.dataArrLoc[idLoc];
                     for(var nameLoc in dataObj){
                        insertValuesLoc(idLoc, nameLoc, dataObj[nameLoc]);
                     }
                }
            },
            printData: function(){
                for (var k in this.dataArrGlob) {
                    console.log( k +" --> "+ this.dataArrGlob[k]);
                }
                for (var j in this.dataArrLoc) {
                    console.log("#"+j );
                    var propObj = this.dataArrLoc[j];
                    for (var g in propObj) {
                        console.log("  --> "+g+" : "+propObj[g]);
                    }
                }
            }
            //TODO
            //sendHTML: function(ajaxReceiver){
            //
            //}
        };
        //TODO function localized replace "insertValuesLoc"
        function insertValuesLoc(id, name, value) {
            var pattern = new RegExp('{{'+name+'}}', "gi");
            var local = document.getElementById(id);
            var locText = local.innerHTML;
            locText = locText.replace(pattern, value);
            local.innerHTML = locText;
            return true;
        }
        function insertValuesGlob(name, value) {
            var pattern = new RegExp('{{'+name+'}}', "gi");
            var body = document.getElementsByTagName("body")[0];
            var bodyText = body.innerHTML;
            bodyText = bodyText.replace(pattern, value);
            body.innerHTML = bodyText;
            return true;
        }

        window.Binder = binder;
        window.$B = window.Binder;
    })();
});<|endoftext|>


<commit_before>const config = require("./../../config.json");

module.exports = function help(message) {
	var embed = new Discord.RichEmbed()
		.setFooter("MSS-Discord, " + config.MSS.version, "")
		.setTimestamp()
		.addField("MSS", config.MSS.version)
		.addField("Commands", "For a list of commands, please run the '" + config.MSS.prefix + "man' command.\nFor help on a specific command, please run '" + config.MSS.prefix + "man <command>'.")
		.addField("Links", "[Discord Server](http://moustacheminer.com/r/invite-server)\n[Invite Bot](http://moustacheminer.com/r/invite-bot)\n[GitHub](http://moustacheminer.com/r/github-bot)")
		.addField("Licence", "This software is released under the MIT Licence.");

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}
<commit_msg>Include Discord<commit_after>const config = require("./../../config.json");
const Discord = require("discord.js");

module.exports = function help(message) {
	var embed = new Discord.RichEmbed()
		.setFooter("MSS-Discord, " + config.MSS.version, "")
		.setTimestamp()
		.addField("MSS", config.MSS.version)
		.addField("Commands", "For a list of commands, please run the '" + config.MSS.prefix + "man' command.\nFor help on a specific command, please run '" + config.MSS.prefix + "man <command>'.")
		.addField("Links", "[Discord Server](http://moustacheminer.com/r/invite-server)\n[Invite Bot](http://moustacheminer.com/r/invite-bot)\n[GitHub](http://moustacheminer.com/r/github-bot)")
		.addField("Licence", "This software is released under the MIT Licence.");

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014-2020 Bjoern Kimminich.
 * SPDX-License-Identifier: MIT
 */

const frisby = require('frisby')
const API_URL = 'http://localhost:3000/metrics/'

describe('/metrics', () => {
  it('GET metrics via public API', () => {
    return frisby.get(API_URL)
      .expect('status', 200)
      .expect('header', 'content-type', /text\/plain/)
      .expect('bodyContains', /^.*_version_info{version="[0-9]+.[0-9]+.[0-9]+(-SNAPSHOT)?",major="[0-9]+",minor="[0-9]+",patch="[0-9]+",app=".*"} 1$/gm)
      .expect('bodyContains', /^.*_challenges_solved{difficulty="[1-6]",category=".*",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_challenges_total{difficulty="[1-6]",category=".*",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_orders_placed_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered{type="standard",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered{type="deluxe",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_wallet_balance_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="review",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="feedback",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="complaint",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^http_requests_count{status_code="[0-9]XX",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^file_uploads_count{file_type=".*",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^file_upload_errors{file_type=".*",app=".*"} [0-9]*$/gm)
  })
})
<commit_msg>Split metrics API tests to avoid race conditions<commit_after>/*
 * Copyright (c) 2014-2020 Bjoern Kimminich.
 * SPDX-License-Identifier: MIT
 */

const frisby = require('frisby')
const fs = require('fs')
const path = require('path')
const URL = 'http://localhost:3000'
const API_URL = 'http://localhost:3000/metrics'

describe('/metrics', () => {
  it('GET metrics via public API that are available instantaneously', () => {
    return frisby.get(API_URL)
      .expect('status', 200)
      .expect('header', 'content-type', /text\/plain/)
      .expect('bodyContains', /^.*_version_info{version="[0-9]+.[0-9]+.[0-9]+(-SNAPSHOT)?",major="[0-9]+",minor="[0-9]+",patch="[0-9]+",app=".*"} 1$/gm)
      .expect('bodyContains', /^.*_challenges_solved{difficulty="[1-6]",category=".*",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_challenges_total{difficulty="[1-6]",category=".*",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_orders_placed_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered{type="standard",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered{type="deluxe",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_users_registered_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_wallet_balance_total{app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="review",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="feedback",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^.*_user_social_interactions{type="complaint",app=".*"} [0-9]*$/gm)
      .expect('bodyContains', /^http_requests_count{status_code="[0-9]XX",app=".*"} [0-9]*$/gm)
  })

  it('GET file upload metrics via public API', () => {
    const file = path.resolve(__dirname, '../files/validSizeAndTypeForClient.pdf')
    const form = frisby.formData()
    form.append('file', fs.createReadStream(file))

    return frisby.post(URL + '/file-upload', { headers: { 'Content-Type': form.getHeaders()['content-type'] }, body: form })
      .expect('status', 204)
      .then(() => {
        return frisby.get(API_URL)
          .expect('status', 200)
          .expect('header', 'content-type', /text\/plain/)
          .expect('bodyContains', /^file_uploads_count{file_type=".*",app=".*"} [0-9]*$/gm)
      })
  })

  it('GET file upload error metrics via public API', () => {
    const file = path.resolve(__dirname, '../files/invalidSizeForServer.pdf')
    const form = frisby.formData()
    form.append('file', fs.createReadStream(file))

    return frisby.post(URL + '/file-upload', { headers: { 'Content-Type': form.getHeaders()['content-type'] }, body: form })
      .expect('status', 500)
      .then(() => {
        return frisby.get(API_URL)
          .expect('status', 200)
          .expect('header', 'content-type', /text\/plain/)
          .expect('bodyContains', /^file_upload_errors{file_type=".*",app=".*"} [0-9]*$/gm)
      })
  })
})
<|endoftext|>


<commit_before>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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.
 */

(function () {
    var win = Titanium.UI.currentWindow,
        app = win.app,
        activityIndicator = app.views.GlobalActivityIndicator,
        portletViewOpts,
        portletView,
        titleBar,
        initialized,
        pathToRoot = '../../';

    function init() {
        titleBar = new app.views.GenericTitleBar({
            windowKey: 'portlet',
            app: app,
            title: app.localDictionary.uMobile,
            settingsButton: true,
            homeButton: true
        });
        win.add(titleBar);

        portletViewOpts = app.styles.portletView;
        portletView = Titanium.UI.createWebView(portletViewOpts);
        win.add(portletView);

        portletView.addEventListener('load', onPortletLoad);
        portletView.addEventListener('beforeload', onBeforePortletLoad);
        Ti.App.addEventListener('includePortlet', onIncludePortlet);

        win.add(activityIndicator);

        win.initialized = true;
    }

    function onIncludePortlet (portlet) {
        if (portletView) {
            Ti.API.debug('portletView exists, removing it.');
            portletView.stopLoading();
            portletView.hide();
        }
        portletView.url = app.UPM.BASE_PORTAL_URL + portlet.url;
        titleBar.updateTitle(portlet.title);
    }

    function onBeforePortletLoad (e) {
        Ti.API.debug("Loading portlet");
        activityIndicator.message = app.localDictionary.loading;
        activityIndicator.show();
    }

    function onPortletLoad(e) {
        Ti.API.debug("Porlet loaded");
        activityIndicator.hide();
        portletView.show();
    }

    if(!win.initialized) {
        init();
    }

})();<commit_msg>UMOBILE-7 Adding navigation bar for URLs that appear to be outside the portal<commit_after>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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.
 */

(function () {
    var win = Titanium.UI.currentWindow,
        app = win.app,
        activityIndicator = app.views.GlobalActivityIndicator,
        portletViewOpts,
        portletView,
        titleBar,
        navBar,
        initialized,
        pathToRoot = '../../';

    function init() {
        titleBar = new app.views.GenericTitleBar({
            windowKey: 'portlet',
            app: app,
            title: app.localDictionary.uMobile,
            settingsButton: true,
            homeButton: true
        });
        win.add(titleBar);

        portletViewOpts = app.styles.portletView;
        portletView = Titanium.UI.createWebView(portletViewOpts);
        portletView.top = 40;
        win.add(portletView);

        portletView.addEventListener('load', onPortletLoad);
        portletView.addEventListener('beforeload', onBeforePortletLoad);
        Ti.App.addEventListener('includePortlet', onIncludePortlet);

        // initialize navigation back button for URLs outside of the portal
        navBarOptions = app.styles.secondaryNavBarButton;
        navBarOptions.title = app.localDictionary.back;
        navBackButton = Titanium.UI.createButton(navBarOptions);

        // initialize navigation bar for URLs outside the portal
        navBar = new app.views.SecondaryNavBar(app,{
            backButton: navBackButton
        });
        navBar.top = 40;
        navBar.visible = false;
        win.add(navBar);
        navBackButton.addEventListener('click', function() { portletView.goBack(); });

        win.add(activityIndicator);

        win.initialized = true;
    }

    function onIncludePortlet (portlet) {
        if (portletView) {
            Ti.API.debug('portletView exists, removing it.');
            portletView.stopLoading();
            portletView.hide();
        }
        portletView.url = app.UPM.BASE_PORTAL_URL + portlet.url;
        titleBar.updateTitle(portlet.title);
    }

    function onBeforePortletLoad (e) {
        Ti.API.debug("Loading portlet");
        activityIndicator.message = app.localDictionary.loading;
        activityIndicator.show();
    }

    function onPortletLoad(e) {
        Ti.API.debug("Porlet loaded");
        activityIndicator.hide();

        var newUrl = e.url;
        if (newUrl.indexOf('localhost:8080/uPortal') >= 0) {
            navBar.visible = false;
            portletView.top = 40;
        } else {
            Ti.API.info("making visible");
            navBar.visible = true;
            portletView.top = 80;
        }

        portletView.show();
    }

    if(!win.initialized) {
        init();
    }

})();<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Digital Services, University of Cambridge Licensed
 * under the Educational Community 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://opensource.org/licenses/ECL-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.
 */

define(['jquery', 'underscore', 'oae.core', 'jquery.typeahead', 'bootstrap.datepicker', 'globalize'], function($, _, oae) {

    return function(uid, showSettings, widgetData) {

        // The widget container
        var $rootel = $('#' + uid);

        /**
         * Initialise typeahead functionality on a given element, will fetch suggestions from the supplied endpoint with 'q' and 'limit' query parameters.
         *
         * @param  {jQuery}   $el   The element the typeahead functionality should be applied to
         * @param  {String}   name  The name which should be supplied to the typeahead plugin
         * @param  {String}   url   The endpoint to fetch results from
         */
        var initTypeahead = function($el, name, url) {
            $el.typeahead({
                'hint': true,
                'highlight': true
            }, {
                'name': name,
                'displayKey': 'displayName',
                'source': function(query, callback) {
                    $.ajax({
                        'url': url,
                        'data': {
                            'limit': 10,
                            'q': query
                        },
                        'success': function(data) {
                            callback(data.results);
                        }
                    });
                }
            });
        };

        /**
         * Initialise input validation on the form.
         */
        var initFormValidation = function() {
            // Revalidate the funders form section when the other-funders
            // value changes. This is required because other-funders isn't
            // considered part of the funders field by default.
            $('#input-other-funders', $rootel).on('change', function() {
                $('input[name=funders]', $rootel).first().valid();
            });

            // Add a custom validator method to validate the funders component.
            // Requires other-funders to have a value when the Other funder is checked
            $.validator.addMethod('oa-validate-other-funders', function(value, element) {
                if ($('input[name=funders][value=other]', $rootel).is(':checked')) {
                    return $('#input-other-funders', $rootel).val().trim() !== '';
                }
                return true;
            }, 'Enter your funder\'s name');

            // Adds another method to the validator plugin which checks whether a date is in the dd/mm/yyyy format
            $.validator.addMethod('oa-validate-date', function (value, element) {
                return Globalize.parseDate(value, 'dd/MM/yyyy') !== null;
            }, 'Please enter a correct date');

            // Initialise validation on the form
            oae.api.util.validation().validate($('form', $rootel), {
                'errorClass': 'help-block',
                'rules': {
                    'acceptanceDate': {
                        'oa-validate-date': {
                            'depends': function (element) {
                                // Only validate the field if it isn't empty
                                return $(element).val();
                            }
                        }
                    },
                    'funders': {
                        'required': true,
                        'oa-validate-other-funders': true
                    }
                },
                'submitHandler': function(form) {
                    var data = $(form).serializeObject();
                    // Ensure data.funders is an Array
                    data.funders = _.isArray(data.funders) ? data.funders : [data.funders];
                    var funders = _.without(data.funders, 'other');
                    var otherFunders = data['other-funders'];
                    // Prepend all other funders with 'other:' and add them to the funders array
                    _.each(otherFunders.split(','), function(otherFunder) {
                        otherFunder = $.trim(otherFunder);
                        if (otherFunder.length) {
                            funders.push('other:' + otherFunder);
                        }
                    });
                    data.funders = funders;
                    delete data['other-funders'];

                    // Convert the acceptance date to millieseconds
                    var acceptanceDate = Globalize.parseDate(data['acceptanceDate'], 'dd/MM/yyyy');
                    if (acceptanceDate) {
                        data['acceptanceDate'] = acceptanceDate.valueOf();
                    }
                    // Dispatch an event if the form is submitted
                    $(document).trigger('oa.publicationform.submit', data);
                }
            });
        };

        /**
         * Initialise the form
         */
        var initForm = function() {
            // Activate the tooltips on the funder <abbr>s.
            // These are used to explain the funder abbreviations
            $('abbr[data-toggle="tooltip"]', $rootel).tooltip({placement: 'right'});

            // Prefill the email field
            $('#input-email', $rootel).val(oae.data.me.email);

            // Show/hide the other-funders field when the "Other" funder box is checked
            $rootel.on('change', 'input[name=funders][value=other]', function() {
                if ($(this).is(':checked')) {
                    $('#input-other-funders', $rootel).show().focus();
                } else {
                    $('#input-other-funders', $rootel).hide();
                }
            });

            // Clear the comments textarea to avoid placeholder bug
            // @see https://github.com/CUL-DigitalServices/avocet-ui/issues/66
            $('#input-comments', $rootel).val('');

            // Only initialise typeahead and validation functionality if the form isn't disabled
            if (!widgetData || !widgetData.disabled) {
                // Initialise typeahead functionality on the journal and department fields
                initTypeahead($('#input-journal', $rootel), 'journals', '/api/search/journals');
                initTypeahead($('#input-department', $rootel), 'departments', '/api/search/departments');
                // Initialise the datepicker
                $('.input-group.date', $rootel).datepicker({
                    'format': 'dd/mm/yyyy',
                    'keyboardNavigation': false
                });
                // Initialise form validation
                initFormValidation();
            } else {
                // Disable the form
                $('input, textarea', $rootel).prop('disabled', true).attr('placeholder', '');
                $('.panel-footer', $rootel).hide();
            }

            if (widgetData) {
                // Prefill the form if a prefill object is provided
                if (widgetData.prefill) {
                    _.each(widgetData.prefill.fields, function(fieldValue, fieldName) {
                        $('[name="' + fieldName + '"]', $rootel).val(fieldValue).trigger('change');
                    });

                    _.each(widgetData.prefill.checkboxes, function(checked, checkboxName) {
                        // If checked is passed as an array we assume multiple values are selected for the checkboxName
                        if (_.isArray(checked)) {
                            // Select the checkboxes by name and value and mark them as checked
                            _.each(checked, function(checkboxValue) {
                                $('[name="' + checkboxName + '"][value="' + checkboxValue + '"]').prop('checked', true).trigger('change');
                            });
                        } else {
                            // Checked represents whether the checkbox is checked or not
                            $('[name="' + checkboxName + '"]').prop('checked', checked).trigger('change');
                        }
                    });
                }
            }
        };

        initForm();
    };
});
<commit_msg>Added line break<commit_after>/*!
 * Copyright 2014 Digital Services, University of Cambridge Licensed
 * under the Educational Community 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://opensource.org/licenses/ECL-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.
 */

define(['jquery', 'underscore', 'oae.core', 'jquery.typeahead', 'bootstrap.datepicker', 'globalize'], function($, _, oae) {

    return function(uid, showSettings, widgetData) {

        // The widget container
        var $rootel = $('#' + uid);

        /**
         * Initialise typeahead functionality on a given element, will fetch suggestions from the supplied endpoint with 'q' and 'limit' query parameters.
         *
         * @param  {jQuery}   $el   The element the typeahead functionality should be applied to
         * @param  {String}   name  The name which should be supplied to the typeahead plugin
         * @param  {String}   url   The endpoint to fetch results from
         */
        var initTypeahead = function($el, name, url) {
            $el.typeahead({
                'hint': true,
                'highlight': true
            }, {
                'name': name,
                'displayKey': 'displayName',
                'source': function(query, callback) {
                    $.ajax({
                        'url': url,
                        'data': {
                            'limit': 10,
                            'q': query
                        },
                        'success': function(data) {
                            callback(data.results);
                        }
                    });
                }
            });
        };

        /**
         * Initialise input validation on the form.
         */
        var initFormValidation = function() {
            // Revalidate the funders form section when the other-funders
            // value changes. This is required because other-funders isn't
            // considered part of the funders field by default.
            $('#input-other-funders', $rootel).on('change', function() {
                $('input[name=funders]', $rootel).first().valid();
            });

            // Add a custom validator method to validate the funders component.
            // Requires other-funders to have a value when the Other funder is checked
            $.validator.addMethod('oa-validate-other-funders', function(value, element) {
                if ($('input[name=funders][value=other]', $rootel).is(':checked')) {
                    return $('#input-other-funders', $rootel).val().trim() !== '';
                }
                return true;
            }, 'Enter your funder\'s name');

            // Adds another method to the validator plugin which checks whether a date is in the dd/mm/yyyy format
            $.validator.addMethod('oa-validate-date', function (value, element) {
                return Globalize.parseDate(value, 'dd/MM/yyyy') !== null;
            }, 'Please enter a correct date');

            // Initialise validation on the form
            oae.api.util.validation().validate($('form', $rootel), {
                'errorClass': 'help-block',
                'rules': {
                    'acceptanceDate': {
                        'oa-validate-date': {
                            'depends': function (element) {
                                // Only validate the field if it isn't empty
                                return $(element).val();
                            }
                        }
                    },
                    'funders': {
                        'required': true,
                        'oa-validate-other-funders': true
                    }
                },
                'submitHandler': function(form) {
                    var data = $(form).serializeObject();
                    // Ensure data.funders is an Array
                    data.funders = _.isArray(data.funders) ? data.funders : [data.funders];
                    var funders = _.without(data.funders, 'other');
                    var otherFunders = data['other-funders'];
                    // Prepend all other funders with 'other:' and add them to the funders array
                    _.each(otherFunders.split(','), function(otherFunder) {
                        otherFunder = $.trim(otherFunder);
                        if (otherFunder.length) {
                            funders.push('other:' + otherFunder);
                        }
                    });
                    data.funders = funders;
                    delete data['other-funders'];

                    // Convert the acceptance date to millieseconds
                    var acceptanceDate = Globalize.parseDate(data['acceptanceDate'], 'dd/MM/yyyy');
                    if (acceptanceDate) {
                        data['acceptanceDate'] = acceptanceDate.valueOf();
                    }

                    // Dispatch an event if the form is submitted
                    $(document).trigger('oa.publicationform.submit', data);
                }
            });
        };

        /**
         * Initialise the form
         */
        var initForm = function() {
            // Activate the tooltips on the funder <abbr>s.
            // These are used to explain the funder abbreviations
            $('abbr[data-toggle="tooltip"]', $rootel).tooltip({placement: 'right'});

            // Prefill the email field
            $('#input-email', $rootel).val(oae.data.me.email);

            // Show/hide the other-funders field when the "Other" funder box is checked
            $rootel.on('change', 'input[name=funders][value=other]', function() {
                if ($(this).is(':checked')) {
                    $('#input-other-funders', $rootel).show().focus();
                } else {
                    $('#input-other-funders', $rootel).hide();
                }
            });

            // Clear the comments textarea to avoid placeholder bug
            // @see https://github.com/CUL-DigitalServices/avocet-ui/issues/66
            $('#input-comments', $rootel).val('');

            // Only initialise typeahead and validation functionality if the form isn't disabled
            if (!widgetData || !widgetData.disabled) {
                // Initialise typeahead functionality on the journal and department fields
                initTypeahead($('#input-journal', $rootel), 'journals', '/api/search/journals');
                initTypeahead($('#input-department', $rootel), 'departments', '/api/search/departments');
                // Initialise the datepicker
                $('.input-group.date', $rootel).datepicker({
                    'format': 'dd/mm/yyyy',
                    'keyboardNavigation': false
                });
                // Initialise form validation
                initFormValidation();
            } else {
                // Disable the form
                $('input, textarea', $rootel).prop('disabled', true).attr('placeholder', '');
                $('.panel-footer', $rootel).hide();
            }

            if (widgetData) {
                // Prefill the form if a prefill object is provided
                if (widgetData.prefill) {
                    _.each(widgetData.prefill.fields, function(fieldValue, fieldName) {
                        $('[name="' + fieldName + '"]', $rootel).val(fieldValue).trigger('change');
                    });

                    _.each(widgetData.prefill.checkboxes, function(checked, checkboxName) {
                        // If checked is passed as an array we assume multiple values are selected for the checkboxName
                        if (_.isArray(checked)) {
                            // Select the checkboxes by name and value and mark them as checked
                            _.each(checked, function(checkboxValue) {
                                $('[name="' + checkboxName + '"][value="' + checkboxValue + '"]').prop('checked', true).trigger('change');
                            });
                        } else {
                            // Checked represents whether the checkbox is checked or not
                            $('[name="' + checkboxName + '"]').prop('checked', checked).trigger('change');
                        }
                    });
                }
            }
        };

        initForm();
    };
});
<|endoftext|>


<commit_before>angular.module('emixApp',
    ['ngRoute',
    'emixApp.controllers',
    'emixApp.directives',
    'emixApp.services',
    'mgcrea.ngStrap',
    'ngMorris',
    //'ngGoogleMap'
    'pascalprecht.translate'
    ])
    .config(['$routeProvider', function ($routeProvider) {

        $routeProvider
            .when('/dashboard', {
                controller: 'dashboard_index',
                templateUrl: 'ngApp/pages/dashboard/index.html'
            })
            .when('/section', {
                controller: 'section_index',
                templateUrl: 'ngApp/pages/section/index.html'
            })
            .otherwise({
                redirectTo: '/dashboard'
            });

    }])
    .config(['$translateProvider', function ($translateProvider) {

        $translateProvider.useStaticFilesLoader({
            prefix: Emix.Web.translationsFolder,
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('it_IT');

        $translateProvider.storageKey('lang');
        $translateProvider.storagePrefix('emix');

        // $translateProvider.useLocalStorage();
    }]);

angular.module('emixApp.services', []);
angular.module('emixApp.controllers', []);
angular.module('emixApp.directives', []);
<commit_msg>Allow translator plugin to store selected language in sessionStorage/cookie and remember the settings<commit_after>angular.module('emixApp',
    ['ngRoute',
    'ngCookies',
    'emixApp.controllers',
    'emixApp.directives',
    'emixApp.services',
    'mgcrea.ngStrap',
    'ngMorris',
    'pascalprecht.translate'
    ])
    .config(['$routeProvider', function ($routeProvider) {

        $routeProvider
            .when('/dashboard', {
                controller: 'dashboard_index',
                templateUrl: 'ngApp/pages/dashboard/index.html'
            })
            .when('/section', {
                controller: 'section_index',
                templateUrl: 'ngApp/pages/section/index.html'
            })
            .otherwise({
                redirectTo: '/dashboard'
            });

    }])
    .config(['$translateProvider', function ($translateProvider) {

        $translateProvider.useStaticFilesLoader({
            prefix: Emix.Web.translationsFolder,
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('it_IT');

        $translateProvider.storageKey('lang');
        $translateProvider.storagePrefix('emix');
        $translateProvider.useLocalStorage();
    }]);

angular.module('emixApp.services', []);
angular.module('emixApp.controllers', []);
angular.module('emixApp.directives', []);
<|endoftext|>


<commit_before>// <script type="module"> support
export function loadModuleScripts(loader) {
  if (typeof document != 'undefined' && document.getElementsByTagName) {
    function ready() {
      document.removeEventListener('DOMContentLoaded', completed, false );

      var anonCnt = 0;

      var scripts = document.getElementsByTagName('script');
      for (var i = 0; i < scripts.length; i++) {
        var script = scripts[i];
        if (script.type == 'module' && !script.loaded) {
          script.loaded = true;
          if (script.src)
            loader.import(script.src);

          // anonymuos modules supported by a loader ".module" interface
          else if (loader.define)
            loader.define('anon' + ++anonCnt, script.innerHTML);
        }
      }
    }

    // simple DOM ready
    if (document.readyState === 'complete')
      setTimeout(ready);
    else
      document.addEventListener('DOMContentLoaded', ready, false);
  }
}<commit_msg>Fix module-scripts.js removeListener<commit_after>// <script type="module"> support
export function loadModuleScripts(loader) {
  if (typeof document != 'undefined' && document.getElementsByTagName) {
    function ready() {
      document.removeEventListener('DOMContentLoaded', ready, false );

      var anonCnt = 0;

      var scripts = document.getElementsByTagName('script');
      for (var i = 0; i < scripts.length; i++) {
        var script = scripts[i];
        if (script.type == 'module' && !script.loaded) {
          script.loaded = true;
          if (script.src)
            loader.import(script.src);

          // anonymuos modules supported by a loader ".module" interface
          else if (loader.define)
            loader.define('anon' + ++anonCnt, script.innerHTML);
        }
      }
    }

    // simple DOM ready
    if (document.readyState === 'complete')
      setTimeout(ready);
    else
      document.addEventListener('DOMContentLoaded', ready, false);
  }
}
<|endoftext|>