<commit_before>/* Conway's Game of Life */

// [].fill polyfill (by me).
// Does not include start / end parameters because I'm not using that here.
if (!Array.prototype.fill) {
  /* eslint-disable no-extend-native */
  Array.prototype.fill = function fill2(value) {
    /* eslint-enable no-extend-native */
    for (let i = 0; i < this.length; i += 1) {
      this[i] = value;
    }
    return this;
  };
}

// CONTROLS GAME LOGIC =============================================================================

class Game {
  constructor(width, height) {
    this.board = [[]];
    this.changeSize(width, height);
  }

  // HELPER FUNCTIONS

  getBlankBoard() {
    return new Array(this.boardSize[0]).fill(0).map(
      () => new Array(this.boardSize[1]).fill(false)
    );
  }

  getRandomRow() {
    return new Array(this.boardSize[0]).fill(0).map(() => Math.random() < 0.125);
  }

  get boardSize() {
    return [this.board.length, this.board[0].length];
  }

  // GAME MANIPULATION

  clear() {
    this.board = this.getBlankBoard();
    return this;
  }

  randomize() {
    this.board = this.getBlankBoard().map(() => this.getRandomRow());
    return this;
  }

  turnOn(x, y) {
    this.board[x][y] = true;
    return this;
  }

  turnOff(x, y) {
    this.board[x][y] = false;
    return this;
  }

  setState(x, y, state) {
    this.board[x][y] = state;
    return this;
  }

  // GAME LOGIC

  countLiveNeighbors(x, y) {
    // Is there room in directions of:
    //   - negative x
    //   - negative y
    //   - positive x
    //   - positive y
    const xroomneg = x > 0;
    const yroomneg = y > 0;
    const xroompos = x < this.boardSize[0] - 1;
    const yroompos = y < this.boardSize[1] - 1;

    const neighbors = [
      // above
      yroomneg && this.board[x][y - 1],
      // above right
      xroompos && yroomneg && this.board[x + 1][y - 1],
      // right
      xroompos && this.board[x + 1][y],
      // below right
      xroompos && yroompos && this.board[x + 1][y + 1],
      // below
      yroompos && this.board[x][y + 1],
      // below left
      xroomneg && yroompos && this.board[x - 1][y + 1],
      // left
      xroomneg && this.board[x - 1][y],
      // above and left
      xroomneg && yroompos && this.board[x - 1][y - 1],
    ];

    // Number of true values in neighbors array
    return neighbors.filter(n => n).length;
  }

  static judgeFate(isLive, liveNeighbors) {
    if (isLive) {
      // Any live cell with fewer than 2 live neighbors
      // dies of underpopulation; any live cell with more
      // than three dies of overpopulation.
      return (liveNeighbors === 2 || liveNeighbors === 3);
    }
    // Any dead cell with exactly 3 neighbors is born
    return liveNeighbors === 3;
  }

  // GAME CONTROLS

  step() {
    const newState = this.getBlankBoard();

    for (let x = 0; x < this.boardSize[0]; x += 1) {
      for (let y = 0; y < this.boardSize[1]; y += 1) {
        newState[x][y] = Game.judgeFate(
          this.board[x][y],
          this.countLiveNeighbors(x, y)
        );
      }
    }

    this.board = newState;
    return this;
  }

  changeSize(width, height) {
    // Store old board size
    const oldBoardSize = this.boardSize;
    const newBoardSize = [width, height];
    // Calculate size difference
    const diff = [
      newBoardSize[0] - oldBoardSize[0],
      newBoardSize[1] - oldBoardSize[1],
    ];

    // Kill dead cells

    if (diff[0] < 0) { // if x shrinks
      this.board = this.board.slice(0, newBoardSize[0]);
    }
    if (diff[1] < 0) { // if y shrinks
      this.board = this.board.map(row => row.slice(0, newBoardSize[1]));
    }

    // Populate new cells

    // Add new rows filled with random cells
    for (let i = 0; i < diff[0]; i += 1) {
      this.board.push(this.getRandomRow());
    }
    // Add new random cells to existing rows (new columns)
    for (let i = 0; i < diff[1]; i += 1) {
      for (let k = 0; k < this.board.length; k += 1) {
        this.board[k].push(Math.random() < 0.125);
      }
    }

    return this;
  }

  // GAME DEBUG FUNCTIONS

  toString() {
    function boolToAscii(n) { return n ? '*' : ' '; }
    return this.board.map(row => row.map(boolToAscii).join('')).join('\n');
  }

  print() {
    /* eslint-disable no-console */
    console.log(this.toString());
    /* eslint-enable no-console */
  }
}

// BINDS `Game` OBJECT TO A CANVAS =================================================================

document.addEventListener('DOMContentLoaded', () => {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    cellColor: '#37474f',
    canvas: document.getElementById('gol'),
    ctx: document.getElementById('gol').getContext('2d'),

    fps: 15,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    game: new Game(),

    // RENDERING FUNCTIONS

    // These functions connect the simulation to the browser

    // Called to update the game if the canvas size
    // changes.
    sizeChanged() {
      const width = window.gol.canvas.offsetWidth;
      const height = window.gol.canvas.offsetHeight;

      // Update canvas coordinate system
      window.gol.canvas.setAttribute('width', width);
      window.gol.canvas.setAttribute('height', height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.

      window.gol.cellSize = [
        width / Math.round(width / window.gol.idealCellSize),
        height / Math.round(height / window.gol.idealCellSize),
      ];

      // When board size changes, kill cells that are
      // cut off and randomize new terrain.

      window.gol.game.changeSize(
        Math.round(width / window.gol.cellSize[0]),
        Math.round(height / window.gol.cellSize[1]),
      );

      window.gol.redraw();
    },

    redraw() {
      const width = this.canvas.getAttribute('width');
      const height = this.canvas.getAttribute('height');

      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = this.cellColor;
      // Render board
      for (let x = 0; x < this.game.board.length; x += 1) {
        for (let y = 0; y < this.game.board[0].length; y += 1) {
          if (this.game.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    // USER INTERACTION

    // On a desktop computer, cells are born
    // when moused over. On a mobile device
    // it's wherever a touch occurs or is dragged.
    interacted(e) {
      // Position of the canvas in the viewport
      const bbox = window.gol.canvas.getBoundingClientRect();
      // Position of the mouse in the viewport
      const absx = e.clientX;
      const absy = e.clientY;

      // If these two positions intersect:
      if (absx > bbox.left &&
          absy > bbox.top &&
          absx < bbox.right &&
          absy < bbox.bottom
      ) {
        // Calculate mouse position relative to canvas
        const relx = absx - bbox.left;
        const rely = absy - bbox.top;
        // Calculate cell position
        const cellx = Math.floor(relx / window.gol.cellSize[0]);
        const celly = Math.floor(rely / window.gol.cellSize[1]);

        window.gol.game.turnOn(cellx, celly);
      }
    },

    // CONTROL FUNCTIONS

    // Begin the loop

    start() {
      window.gol.game.step();
      window.gol.redraw();
      setTimeout(() => {
        requestAnimationFrame(window.gol.start);
      }, 1000 / window.gol.fps);
    },

    // Initialize and begin

    init() {
      this.sizeChanged();
      this.game.randomize();
      this.start();
    },
  };

  window.addEventListener('resize', window.gol.sizeChanged);
  document.addEventListener('mousemove', window.gol.interacted);
  window.gol.init();
});
<commit_msg>Begin GameRenderer class<commit_after>/* Conway's Game of Life */

// [].fill polyfill (by me).
// Does not include start / end parameters because I'm not using that here.
if (!Array.prototype.fill) {
  /* eslint-disable no-extend-native */
  Array.prototype.fill = function fill2(value) {
    /* eslint-enable no-extend-native */
    for (let i = 0; i < this.length; i += 1) {
      this[i] = value;
    }
    return this;
  };
}

// CONTROLS GAME LOGIC =============================================================================

class Game {
  constructor(width, height) {
    this.board = [[]];
    this.changeSize(width, height);
  }

  // HELPER FUNCTIONS

  getBlankBoard() {
    return new Array(this.boardSize[0]).fill(0).map(
      () => new Array(this.boardSize[1]).fill(false)
    );
  }

  getRandomRow() {
    return new Array(this.boardSize[0]).fill(0).map(() => Math.random() < 0.125);
  }

  get boardSize() {
    return [this.board.length, this.board[0].length];
  }

  // GAME MANIPULATION

  clear() {
    this.board = this.getBlankBoard();
    return this;
  }

  randomize() {
    this.board = this.getBlankBoard().map(() => this.getRandomRow());
    return this;
  }

  turnOn(x, y) {
    this.board[x][y] = true;
    return this;
  }

  turnOff(x, y) {
    this.board[x][y] = false;
    return this;
  }

  setState(x, y, state) {
    this.board[x][y] = state;
    return this;
  }

  // GAME LOGIC

  countLiveNeighbors(x, y) {
    // Is there room in directions of:
    //   - negative x
    //   - negative y
    //   - positive x
    //   - positive y
    const xroomneg = x > 0;
    const yroomneg = y > 0;
    const xroompos = x < this.boardSize[0] - 1;
    const yroompos = y < this.boardSize[1] - 1;

    const neighbors = [
      // above
      yroomneg && this.board[x][y - 1],
      // above right
      xroompos && yroomneg && this.board[x + 1][y - 1],
      // right
      xroompos && this.board[x + 1][y],
      // below right
      xroompos && yroompos && this.board[x + 1][y + 1],
      // below
      yroompos && this.board[x][y + 1],
      // below left
      xroomneg && yroompos && this.board[x - 1][y + 1],
      // left
      xroomneg && this.board[x - 1][y],
      // above and left
      xroomneg && yroompos && this.board[x - 1][y - 1],
    ];

    // Number of true values in neighbors array
    return neighbors.filter(n => n).length;
  }

  static judgeFate(isLive, liveNeighbors) {
    if (isLive) {
      // Any live cell with fewer than 2 live neighbors
      // dies of underpopulation; any live cell with more
      // than three dies of overpopulation.
      return (liveNeighbors === 2 || liveNeighbors === 3);
    }
    // Any dead cell with exactly 3 neighbors is born
    return liveNeighbors === 3;
  }

  // GAME CONTROLS

  step() {
    const newState = this.getBlankBoard();

    for (let x = 0; x < this.boardSize[0]; x += 1) {
      for (let y = 0; y < this.boardSize[1]; y += 1) {
        newState[x][y] = Game.judgeFate(
          this.board[x][y],
          this.countLiveNeighbors(x, y)
        );
      }
    }

    this.board = newState;
    return this;
  }

  changeSize(width, height) {
    // Store old board size
    const oldBoardSize = this.boardSize;
    const newBoardSize = [width, height];
    // Calculate size difference
    const diff = [
      newBoardSize[0] - oldBoardSize[0],
      newBoardSize[1] - oldBoardSize[1],
    ];

    // Kill dead cells

    if (diff[0] < 0) { // if x shrinks
      this.board = this.board.slice(0, newBoardSize[0]);
    }
    if (diff[1] < 0) { // if y shrinks
      this.board = this.board.map(row => row.slice(0, newBoardSize[1]));
    }

    // Populate new cells

    // Add new rows filled with random cells
    for (let i = 0; i < diff[0]; i += 1) {
      this.board.push(this.getRandomRow());
    }
    // Add new random cells to existing rows (new columns)
    for (let i = 0; i < diff[1]; i += 1) {
      for (let k = 0; k < this.board.length; k += 1) {
        this.board[k].push(Math.random() < 0.125);
      }
    }

    return this;
  }

  // GAME DEBUG FUNCTIONS

  toString() {
    function boolToAscii(n) { return n ? '*' : ' '; }
    return this.board.map(row => row.map(boolToAscii).join('')).join('\n');
  }

  print() {
    /* eslint-disable no-console */
    console.log(this.toString());
    /* eslint-enable no-console */
  }
}

// BINDS `Game` OBJECT TO A CANVAS =================================================================

class GameRenderer {
  constructor(selector) {
    this.elem = document.querySelector(selector);
    if (!(this.elem instanceof window.HTMLCanvasElement)) {
      throw new Error('Selector passed to GameRenderer must match a canvas element');
    }
    this.context = this.elem.getContext('2d');
  }
}

document.addEventListener('DOMContentLoaded', () => {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    cellColor: '#37474f',
    canvas: document.getElementById('gol'),
    ctx: document.getElementById('gol').getContext('2d'),

    fps: 15,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    game: new Game(),

    // RENDERING FUNCTIONS

    // These functions connect the simulation to the browser

    // Called to update the game if the canvas size
    // changes.
    sizeChanged() {
      const width = window.gol.canvas.offsetWidth;
      const height = window.gol.canvas.offsetHeight;

      // Update canvas coordinate system
      window.gol.canvas.setAttribute('width', width);
      window.gol.canvas.setAttribute('height', height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.

      window.gol.cellSize = [
        width / Math.round(width / window.gol.idealCellSize),
        height / Math.round(height / window.gol.idealCellSize),
      ];

      // When board size changes, kill cells that are
      // cut off and randomize new terrain.

      window.gol.game.changeSize(
        Math.round(width / window.gol.cellSize[0]),
        Math.round(height / window.gol.cellSize[1]),
      );

      window.gol.redraw();
    },

    redraw() {
      const width = this.canvas.getAttribute('width');
      const height = this.canvas.getAttribute('height');

      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = this.cellColor;
      // Render board
      for (let x = 0; x < this.game.board.length; x += 1) {
        for (let y = 0; y < this.game.board[0].length; y += 1) {
          if (this.game.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    // USER INTERACTION

    // On a desktop computer, cells are born
    // when moused over. On a mobile device
    // it's wherever a touch occurs or is dragged.
    interacted(e) {
      // Position of the canvas in the viewport
      const bbox = window.gol.canvas.getBoundingClientRect();
      // Position of the mouse in the viewport
      const absx = e.clientX;
      const absy = e.clientY;

      // If these two positions intersect:
      if (absx > bbox.left &&
          absy > bbox.top &&
          absx < bbox.right &&
          absy < bbox.bottom
      ) {
        // Calculate mouse position relative to canvas
        const relx = absx - bbox.left;
        const rely = absy - bbox.top;
        // Calculate cell position
        const cellx = Math.floor(relx / window.gol.cellSize[0]);
        const celly = Math.floor(rely / window.gol.cellSize[1]);

        window.gol.game.turnOn(cellx, celly);
      }
    },

    // CONTROL FUNCTIONS

    // Begin the loop

    start() {
      window.gol.game.step();
      window.gol.redraw();
      setTimeout(() => {
        requestAnimationFrame(window.gol.start);
      }, 1000 / window.gol.fps);
    },

    // Initialize and begin

    init() {
      this.sizeChanged();
      this.game.randomize();
      this.start();
    },
  };

  window.addEventListener('resize', window.gol.sizeChanged);
  document.addEventListener('mousemove', window.gol.interacted);
  window.gol.init();
});
<|endoftext|>


<commit_before>/**
 * npm.link
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

var path = require('path');

module.exports = function (ns) {

};
<commit_msg>删除config/development.js<commit_after><|endoftext|>


<commit_before>/* eslint-env node */
// eslint-disable-next-line no-global-assign
require = require("esm")(module);

const webpack = require("webpack");
const path = require("path");
const fs = require("fs");
const AssetsPlugin = require("assets-webpack-plugin");
const { default: config } = require("@argos-ci/config");

const prod = process.env.NODE_ENV === "production";
module.exports = {
  mode: prod ? "production" : "development",
  entry: "./src/index.js",
  output: {
    filename: prod ? "[name]-bundle-[chunkhash:8].js" : "[name].js",
    publicPath: "/static/app/",
  },
  devtool: prod ? "source-map" : "eval-cheap-module-source-map",
  module: {
    rules: [
      {
        test: /\.m?js$/,
        type: "javascript/auto",
        resolve: {
          fullySpecified: false,
        },
      },
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: "swc-loader",
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        type: "asset/resource",
      },
    ],
  },
  plugins: [
    ...(prod
      ? [
          new AssetsPlugin({
            path: "dist",
          }),
        ]
      : []),
    new webpack.EnvironmentPlugin({
      PLATFORM: "browser",
      SENTRY_RELEASE: process.env.COMMIT_REF || "",
      API_BASE_URL: "https://api.argos-ci.dev:4001",
    }),
  ],
  ...(!prod
    ? {
        devServer: {
          historyApiFallback: true,
          allowedHosts: "all",
          https: {
            key: fs.readFileSync(
              path.join(__dirname, "../../_wildcard.argos-ci.dev-key.pem")
            ),
            cert: fs.readFileSync(
              path.join(__dirname, "../../_wildcard.argos-ci.dev.pem")
            ),
          },
          host: "app.argos-ci.dev",
          port: config.get("client.port"),
          proxy: {
            "**": {
              target: `https://app.argos-ci.dev:${config.get("server.port")}`,
              secure: false,
            },
          },
        },
      }
    : {}),
};
<commit_msg>chore(webpack): improve sourcemaps<commit_after>/* eslint-env node */
// eslint-disable-next-line no-global-assign
require = require("esm")(module);

const webpack = require("webpack");
const path = require("path");
const fs = require("fs");
const AssetsPlugin = require("assets-webpack-plugin");
const { default: config } = require("@argos-ci/config");

const prod = process.env.NODE_ENV === "production";
module.exports = {
  mode: prod ? "production" : "development",
  entry: "./src/index.js",
  output: {
    filename: prod ? "[name]-bundle-[chunkhash:8].js" : "[name].js",
    publicPath: "/static/app/",
  },
  devtool: prod ? "source-map" : "eval-source-map",
  module: {
    rules: [
      {
        test: /\.m?js$/,
        type: "javascript/auto",
        resolve: {
          fullySpecified: false,
        },
      },
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: "swc-loader",
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        type: "asset/resource",
      },
    ],
  },
  plugins: [
    ...(prod
      ? [
          new AssetsPlugin({
            path: "dist",
          }),
        ]
      : []),
    new webpack.EnvironmentPlugin({
      PLATFORM: "browser",
      SENTRY_RELEASE: process.env.COMMIT_REF || "",
      API_BASE_URL: "https://api.argos-ci.dev:4001",
    }),
  ],
  ...(!prod
    ? {
        devServer: {
          historyApiFallback: true,
          allowedHosts: "all",
          https: {
            key: fs.readFileSync(
              path.join(__dirname, "../../_wildcard.argos-ci.dev-key.pem")
            ),
            cert: fs.readFileSync(
              path.join(__dirname, "../../_wildcard.argos-ci.dev.pem")
            ),
          },
          host: "app.argos-ci.dev",
          port: config.get("client.port"),
          proxy: {
            "**": {
              target: `https://app.argos-ci.dev:${config.get("server.port")}`,
              secure: false,
            },
          },
        },
      }
    : {}),
};
<|endoftext|>


<commit_before>'use strict';

/* Services */

var barmanServices = angular.module('barmanServices', []);

barmanServices.factory('Order', [ '$http', function ($http) {
    /*
     * Check if an order already exists in the scope array
     * @param array: The scope array
     * @param order: The order
     *
     * @return true or false
     */
    var checkIfAlreadyExist = function(array, order) {
        for (var i = 0, l = array.length; i < l; i++) {
            if (array[i].id === order.id) {
                return true;
            }
        }

        return false;
    };

    return {
        /*
         * Get the orders from couchDB
         *
         * @param array: it's where we push the data
         */
        fetchOrders: function ($scope) {
            var promise = $http.get('https://lazywaiter.couchappy.com/orders/_design/orders/_view/all');

            promise.success(function(data, status, headers, config) {
                for (var i = 0, l = data.rows.length; i < l; i++) {
                    // Push only the new entries
                    if (!checkIfAlreadyExist($scope.orders, data.rows[i])) {
                        $scope.orders.push(data.rows[i]);
                    }
                }
            });
            promise.error(function(data, status, headers, config) {
                alert("error: Data not found");
            });
        },
        /*
         * Update status of an order
         *
         * @param $scope: The scope which we modify
         * @param order: The order which want to update the status
         */
        updateOrderStatusToReady: function($scope, order) {
            var index = $scope.orders.indexOf(order);
            var promise = $http.put('https://lazywaiter.couchappy.com/orders/' + order._id, order);
            promise.success(function(data, status, headers, config) {
                alert("state changed");
                if (index !== -1) {
                    delete $scope.orders[index];
                }
            });

            promise.error(function(data, status, headers, config) {
                order.status = "to_prepare";
                alert("error: Data not updated");
            });
        }
    }
}]);
<commit_msg>Retrieve only the orders with state 'to_prepare'<commit_after>'use strict';

/* Services */

var barmanServices = angular.module('barmanServices', []);

barmanServices.factory('Order', [ '$http', function ($http) {
    /*
     * Check if an order already exists in the scope array
     * @param array: The scope array
     * @param order: The order
     *
     * @return true or false
     */
    var checkIfAlreadyExist = function(array, order) {
        for (var i = 0, l = array.length; i < l; i++) {
            if (array[i].id === order.id) {
                return true;
            }
        }

        return false;
    };

    return {
        /*
         * Get the orders from couchDB
         *
         * @param array: it's where we push the data
         */
        fetchOrders: function ($scope) {
            var promise = $http.get('https://lazywaiter.couchappy.com/orders/_design/orders/_view/all');

            promise.success(function(data, status, headers, config) {
                for (var i = 0, l = data.rows.length; i < l; i++) {
                    // Push only the new entries
                    if (data.rows[i].value.status === "to_prepare") {
                        if (!checkIfAlreadyExist($scope.orders, data.rows[i])) {
                            $scope.orders.push(data.rows[i]);
                        }
                    }
                }
            });
            promise.error(function(data, status, headers, config) {
                alert("error: Data not found");
            });
        },
        /*
         * Update status of an order
         *
         * @param $scope: The scope which we modify
         * @param order: The order which want to update the status
         */
        updateOrderStatusToReady: function($scope, order) {
            var index = $scope.orders.indexOf(order);

            var promise = $http.put('https://lazywaiter.couchappy.com/orders/' + order._id, order);
            promise.success(function(data, status, headers, config) {
                alert("state changed");
                if (index !== -1) {
                    delete $scope.orders[index];
                }
            });

            promise.error(function(data, status, headers, config) {
                order.status = "to_prepare";
                alert("error: Data not updated");
            });
        }
    }
}])
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  app: {
    title: 'GalaJSy',
    description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
    keywords: 'mongodb, express, angularjs, node.js, mongoose, passport',
    googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID'
  },
  db: {
    promise: global.Promise
  },
  port: process.env.PORT || 3000,
  host: process.env.HOST || 'https://galajsy.herokuapp.com',
  // DOMAIN config should be set to the fully qualified application accessible ec2-35-163-71-140.us-west-2.compute.amazonaws.com
  // URL. For example: https://www.myapp.com (including port if required).
  domain: 'https://galajsy.herokuapp.com:3000',
  // Session Cookie settings
  sessionCookie: {
    // session expiration is set by default to 24 hours
    maxAge: 24 * (60 * 60 * 1000),
    // httpOnly flag makes sure the cookie is only accessed
    // through the HTTP protocol and not JS/browser
    httpOnly: true,
    // secure cookie should be turned to true to provide additional
    // layer of security so that the cookie is set only when working
    // in HTTPS mode.
    secure: false
  },
  // sessionSecret should be changed for security measures and concerns
  sessionSecret: process.env.SESSION_SECRET || 'GALAJSY',
  // sessionKey is the cookie session name
  sessionKey: 'sessionId',
  sessionCollection: 'sessions',
  // Lusca config
  csrf: {
    csrf: false,
    csp: false,
    xframe: 'SAMEORIGIN',
    p3p: 'ABCDEF',
    xssProtection: true
  },
  logo: 'modules/core/client/img/brand/logo.png',
  favicon: 'modules/core/client/img/brand/favicon.ico',
  illegalUsernames: ['meanjs', 'administrator', 'password', 'admin', 'user',
    'unknown', 'anonymous', 'null', 'undefined', 'api'
  ],
  uploads: {
    profile: {
      image: {
        dest: './modules/users/client/img/profile/uploads/',
        limits: {
          fileSize: 1 * 1024 * 1024 // Max file size in bytes (1 MB)
        }
      }
    }
  },
  shared: {
    owasp: {
      allowPassphrases: true,
      maxLength: 128,
      minLength: 10,
      minPhraseLength: 20,
      minOptionalTestsToPass: 4
    }
  }

};
<commit_msg>look for setting DOMAIN<commit_after>'use strict';

module.exports = {
  app: {
    title: 'GalaJSy',
    description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
    keywords: 'mongodb, express, angularjs, node.js, mongoose, passport',
    googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID'
  },
  db: {
    promise: global.Promise
  },
  port: process.env.PORT || 3000,
  host: process.env.HOST || 'https://galajsy.herokuapp.com',
  // DOMAIN config should be set to the fully qualified application accessible ec2-35-163-71-140.us-west-2.compute.amazonaws.com
  // URL. For example: https://www.myapp.com (including port if required).
  domain: 'https://galajsy.herokuapp.com',
  // Session Cookie settings
  sessionCookie: {
    // session expiration is set by default to 24 hours
    maxAge: 24 * (60 * 60 * 1000),
    // httpOnly flag makes sure the cookie is only accessed
    // through the HTTP protocol and not JS/browser
    httpOnly: true,
    // secure cookie should be turned to true to provide additional
    // layer of security so that the cookie is set only when working
    // in HTTPS mode.
    secure: false
  },
  // sessionSecret should be changed for security measures and concerns
  sessionSecret: process.env.SESSION_SECRET || 'GALAJSY',
  // sessionKey is the cookie session name
  sessionKey: 'sessionId',
  sessionCollection: 'sessions',
  // Lusca config
  csrf: {
    csrf: false,
    csp: false,
    xframe: 'SAMEORIGIN',
    p3p: 'ABCDEF',
    xssProtection: true
  },
  logo: 'modules/core/client/img/brand/logo.png',
  favicon: 'modules/core/client/img/brand/favicon.ico',
  illegalUsernames: ['meanjs', 'administrator', 'password', 'admin', 'user',
    'unknown', 'anonymous', 'null', 'undefined', 'api'
  ],
  uploads: {
    profile: {
      image: {
        dest: './modules/users/client/img/profile/uploads/',
        limits: {
          fileSize: 1 * 1024 * 1024 // Max file size in bytes (1 MB)
        }
      }
    }
  },
  shared: {
    owasp: {
      allowPassphrases: true,
      maxLength: 128,
      minLength: 10,
      minPhraseLength: 20,
      minOptionalTestsToPass: 4
    }
  }

};
<|endoftext|>


<commit_before>'use strict';

angular.

module('myApp.services', []).

/* Services */

value('version', '0.1').

factory('EventsDataService', function ($http) {
    return $http({method: 'GET', url: 'data/events.json'});
}).

factory('MedsDataService', function ($http) {
    return $http({method: 'GET', url: 'data/values.json'});
});
<commit_msg>bump version to 0.2<commit_after>'use strict';

angular.

module('myApp.services', []).

/* Services */

value('version', '0.2').

factory('EventsDataService', function ($http) {
    return $http({method: 'GET', url: 'data/events.json'});
}).

factory('MedsDataService', function ($http) {
    return $http({method: 'GET', url: 'data/values.json'});
});
<|endoftext|>


<commit_before>/* eslint-env node */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ilios',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    redirectAfterShibLogin: true,
    contentSecurityPolicy: {
      'default-src': ["'none'"],
      'script-src':  ["'self'", "'unsafe-eval'"],
      'font-src':    ["'self'"],
      'connect-src': ["'self'"],
      'img-src':     ["'self'", 'data:'],
      'style-src':   ["'self'", "'unsafe-inline'"],
      'media-src':   ["'self'"]
    },
    flashMessageDefaults: {
      timeout: 2000,
      extendedTimeout: 3000,
      types: [ 'success', 'warning', 'info', 'alert' ]
    },
    'ember-simple-auth': {
      authorizer: 'authorizer:token'
    },
    'ember-simple-auth-token': {
      serverTokenEndpoint: '/auth/login',
      serverTokenRefreshEndpoint: '/auth/token',
      tokenPropertyName: 'jwt',
      authorizationHeaderName: 'X-JWT-Authorization',
      authorizationPrefix: 'Token ',
      timeFactor: 1000
    },
    i18n: {
      defaultLocale: 'en'
    },
    froalaEditorDefaults: {
      toolbarInline: false,
      placeholderText: '',
      allowHTML: true,
      saveInterval: false,
      pastePlain: true,
      spellcheck: true,
      toolbarButtons: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsMD: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsSM: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsXS: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
    },
    serverVariables: {
      tagPrefix: 'iliosconfig',
      vars: ['api-host', 'api-name-space'],
      defaults: {
        'api-name-space': 'api/v1'
      }
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        String: true,
        Array: true,
        Function: false,
        Date: false,
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    //Hide a feature while it is in development
    IliosFeatures: {
      allowAddNewUser: true,
      curriculumInventory: true,
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.redirectAfterShibLogin = false;
    ENV.serverVariables.defaults['api-name-space'] = 'api';
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.flashMessageDefaults.timeout = 100;
    ENV.flashMessageDefaults.extendedTimeout = 100;
    ENV.serverVariables.defaults['api-name-space'] = 'api';
  }

  if (environment === 'heroku') {
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
  }

  //Just like dev except we can use proxy to get data from the API
  // Example for vagrant ember serve --env=proxy --proxy='http://10.10.10.10'
  if (environment === 'proxy') {
    ENV['ember-cli-mirage'] = {
      enabled: false
    };
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
  }

/*
  if (environment === 'production') {
  }

  if (environment === 'staging') {
  }
*/

  return ENV;
};
<commit_msg>set ci feature flag back to false.<commit_after>/* eslint-env node */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ilios',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    redirectAfterShibLogin: true,
    contentSecurityPolicy: {
      'default-src': ["'none'"],
      'script-src':  ["'self'", "'unsafe-eval'"],
      'font-src':    ["'self'"],
      'connect-src': ["'self'"],
      'img-src':     ["'self'", 'data:'],
      'style-src':   ["'self'", "'unsafe-inline'"],
      'media-src':   ["'self'"]
    },
    flashMessageDefaults: {
      timeout: 2000,
      extendedTimeout: 3000,
      types: [ 'success', 'warning', 'info', 'alert' ]
    },
    'ember-simple-auth': {
      authorizer: 'authorizer:token'
    },
    'ember-simple-auth-token': {
      serverTokenEndpoint: '/auth/login',
      serverTokenRefreshEndpoint: '/auth/token',
      tokenPropertyName: 'jwt',
      authorizationHeaderName: 'X-JWT-Authorization',
      authorizationPrefix: 'Token ',
      timeFactor: 1000
    },
    i18n: {
      defaultLocale: 'en'
    },
    froalaEditorDefaults: {
      toolbarInline: false,
      placeholderText: '',
      allowHTML: true,
      saveInterval: false,
      pastePlain: true,
      spellcheck: true,
      toolbarButtons: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsMD: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsSM: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
      toolbarButtonsXS: [
        'bold',
        'italic',
        'subscript',
        'superscript',
        'formatOL',
        'formatUL',
        'insertLink',
        'html'
      ],
    },
    serverVariables: {
      tagPrefix: 'iliosconfig',
      vars: ['api-host', 'api-name-space'],
      defaults: {
        'api-name-space': 'api/v1'
      }
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        String: true,
        Array: true,
        Function: false,
        Date: false,
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    //Hide a feature while it is in development
    IliosFeatures: {
      allowAddNewUser: true,
      curriculumInventory: false,
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.redirectAfterShibLogin = false;
    ENV.serverVariables.defaults['api-name-space'] = 'api';
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.flashMessageDefaults.timeout = 100;
    ENV.flashMessageDefaults.extendedTimeout = 100;
    ENV.serverVariables.defaults['api-name-space'] = 'api';
  }

  if (environment === 'heroku') {
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
  }

  //Just like dev except we can use proxy to get data from the API
  // Example for vagrant ember serve --env=proxy --proxy='http://10.10.10.10'
  if (environment === 'proxy') {
    ENV['ember-cli-mirage'] = {
      enabled: false
    };
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
  }

/*
  if (environment === 'production') {
  }

  if (environment === 'staging') {
  }
*/

  return ENV;
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'freemusicninja',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      API_NAMESPACE: '',
      API_CLIENT_ID: process.env.API_CLIENT_ID || 'web',
      API_HOST: '',
    },

    'simple-auth': {
      authorizer: 'simple-auth-authorizer:oauth2-bearer',
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.APP.API_HOST = process.env.API_URL;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.API_HOST = 'http://api';
    ENV.APP.API_CLIENT_ID = 'client_id';
    ENV['simple-auth'].store = 'simple-auth-session-store:ephemeral';
  }

  if (environment === 'production') {
    ENV.APP.API_HOST = 'http://api.freemusic.ninja';
  }

  ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: ENV.APP.API_HOST + '/oauth2/token/?client_id=' + encodeURIComponent(ENV.APP.API_CLIENT_ID),
  };

  ENV['simple-auth'].crossOriginWhitelist = [ENV.APP.API_HOST];

  ENV.contentSecurityPolicy = {
    'connect-src': "'self' data: " + ENV.APP.API_HOST.replace(/^https?:\/\//i, ''),
  };

  return ENV;
};
<commit_msg>Use HTTPS API endpoint<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'freemusicninja',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      API_NAMESPACE: '',
      API_CLIENT_ID: process.env.API_CLIENT_ID || 'web',
      API_HOST: '',
    },

    'simple-auth': {
      authorizer: 'simple-auth-authorizer:oauth2-bearer',
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.APP.API_HOST = process.env.API_URL;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.API_HOST = 'http://api';
    ENV.APP.API_CLIENT_ID = 'client_id';
    ENV['simple-auth'].store = 'simple-auth-session-store:ephemeral';
  }

  if (environment === 'production') {
    ENV.APP.API_HOST = 'https://api.freemusic.ninja';
  }

  ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: ENV.APP.API_HOST + '/oauth2/token/?client_id=' + encodeURIComponent(ENV.APP.API_CLIENT_ID),
  };

  ENV['simple-auth'].crossOriginWhitelist = [ENV.APP.API_HOST];

  ENV.contentSecurityPolicy = {
    'connect-src': "'self' data: " + ENV.APP.API_HOST.replace(/^https?:\/\//i, ''),
  };

  return ENV;
};
<|endoftext|>


<commit_before>'use strict';

/* Services */

var rapidScoreServices = angular.module('rapidScoreServices', ['ngResource']);
//var hostname = 'http://localhost:5000';
var hostname = 'http://lazyscore.herokuapp.com';

rapidScoreServices.factory('InstrumentAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/instruments/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ComposerAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/composers/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('GenreAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/genres/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username',
            {},
            {
                login: {method:'GET'},
                register: {method:'POST'},
                getOne: {method:'GET'}
            }
        );
    }]);

rapidScoreServices.factory('UserCartAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username/shopping-cart',
            {},
            {
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserOrderAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username/purchased',
            {},
            {
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/users/:username',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ScoreAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/sheetmusic/:scoreId',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ScoreAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/sheetmusic/:scoreId',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('CategoryAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/categories',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);
<commit_msg>Update services.js<commit_after>'use strict';

/* Services */

var rapidScoreServices = angular.module('rapidScoreServices', ['ngResource']);
//var hostname = 'http://localhost:5000';
var hostname = 'http://lazyscore.herokuapp.com';

rapidScoreServices.factory('InstrumentAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/instruments/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ComposerAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/composers/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('GenreAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/genres/:cname',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username',
            {},
            {
                login: {method:'GET'},
                register: {method:'POST'},
                getOne: {method:'GET'}
            }
        );
    }]);

rapidScoreServices.factory('UserCartAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username/shopping-cart',
            {},
            {
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserOrderAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/users/:username/purchased',
            {},
            {
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('UserAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/users/:username',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ScoreAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/sheetmusic/:scoreId',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('ScoreAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/sheetmusic/:scoreId',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);

rapidScoreServices.factory('CategoryAdminAPI', ['$resource',
    function($resource){
        return $resource(
                hostname + '/admin/categorytypes',
            {},
            {
                getOne: {method:'GET'},
                getAll: {method:'GET', isArray:true}
            }
        );
    }]);
<|endoftext|>


<commit_before>/* eslint-env node */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ember-customers',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>chore(config): Disable prototype extensions<commit_after>/* eslint-env node */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ember-customers',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: false
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'katana',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>Fix baseURL for github pages.<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'katana',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.baseURL = '/katana';
  }

  return ENV;
};
<|endoftext|>


<commit_before>
var namer = require("./namer"),
	typer = require("./typer");

/**
 * @hide
 *
 * This is used to parse out content like `{TYPE} name() description`.
 *
 * @param {String} line
 * @param {Bolean} ignoreName If true, only looks for a TYPE in curlies followed by a description.
 */
module.exports = function(line, ignoreName){

	var children = typer.tree(line),
		param = {};

	console.log(children);
	var textIs = function(i,text){
		return children[i] && children[i].token == text;
	};
	var processNameAndDescription = function(index){
		if(!children[index]){
			return;
		}
		if(!ignoreName){
			var nameChildren = [children[index]];
			index++;
			if( textIs(index,"function") ) {
				nameChildren[0].token = nameChildren[0].token + "function";
				index++;
			}
			if( textIs(index,"(") ){
				nameChildren.push( children[index] );
				index++;
			}
			namer.process( nameChildren, param);
		}

		param.description = (children[index] ?
			line.substr( children[index].start ) : "").replace(/\\/g,"");
	};

	// @function will be broken up by tree, lets put that back together
	if(textIs(0,"@") && textIs(1,"function")){
		children.splice(0,2,"@function")
	}

	if(children.length <= 1){
		return {};
	}
	var param = {},
		description,
		nameChildren;

	// starts with an object
	if(textIs(1,"{")){

		typer.process(children[1].children, param);
		processNameAndDescription(2)

	} else {
		// starts with a name
		processNameAndDescription(1)
	}

	// include for function naming
	namer.process( nameChildren, param);

	// clean up the description
	param.description = (param.description||"").replace(/^\s+/,"");
	return param;
};

<commit_msg>removing console.log<commit_after>
var namer = require("./namer"),
	typer = require("./typer");

/**
 * @hide
 *
 * This is used to parse out content like `{TYPE} name() description`.
 *
 * @param {String} line
 * @param {Bolean} ignoreName If true, only looks for a TYPE in curlies followed by a description.
 */
module.exports = function(line, ignoreName){

	var children = typer.tree(line),
		param = {};

	var textIs = function(i,text){
		return children[i] && children[i].token == text;
	};
	var processNameAndDescription = function(index){
		if(!children[index]){
			return;
		}
		if(!ignoreName){
			var nameChildren = [children[index]];
			index++;
			if( textIs(index,"function") ) {
				nameChildren[0].token = nameChildren[0].token + "function";
				index++;
			}
			if( textIs(index,"(") ){
				nameChildren.push( children[index] );
				index++;
			}
			namer.process( nameChildren, param);
		}

		param.description = (children[index] ?
			line.substr( children[index].start ) : "").replace(/\\/g,"");
	};

	// @function will be broken up by tree, lets put that back together
	if(textIs(0,"@") && textIs(1,"function")){
		children.splice(0,2,"@function")
	}

	if(children.length <= 1){
		return {};
	}
	var param = {},
		description,
		nameChildren;

	// starts with an object
	if(textIs(1,"{")){

		typer.process(children[1].children, param);
		processNameAndDescription(2)

	} else {
		// starts with a name
		processNameAndDescription(1)
	}

	// include for function naming
	namer.process( nameChildren, param);

	// clean up the description
	param.description = (param.description||"").replace(/^\s+/,"");
	return param;
};

<|endoftext|>


<commit_before>'use strict';

module.exports = function () {
  return {
    moment: {
      // Options:
      // 'all' - all years, all timezones
      // '2010-2020' - 2010-2020, all timezones
      // 'none' - no data, just timezone API
      includeTimezone: 'all'
    }
  }
};

module.exports = function (environment) {
  let ENV = {
    taleIconHeight: "360",
    taleIconWidth: "360",

    modulePrefix: 'wholetale',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    torii: {
      providers: {

      }
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      },
      'ember-oauth2': {
        model: {}
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV['ember-cli-mirage'] = {
    enabled: false
  };

  if (environment === 'test') {
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.apiHost = '';
    ENV.apiPath = '/api';
    ENV.apiUrl = '';
    ENV.dev = true;
    // ENV.APP.autoboot = false;
  }

  if (environment === 'test-dev') {
    ENV.apiHost = 'https://girdertest.wholetale.org';
    ENV.apiPath = 'api/v1';
    ENV.apiUrl = 'https://girdertest.wholetale.org/api/v1';
    ENV.dev = true;
  }

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.apiHost = 'https://girder.dev.wholetale.org';
    ENV.apiPath = 'api/v1';
    ENV.apiUrl = 'https://girder.dev.wholetale.org/api/v1';
    ENV.dev = true;
    ENV.orcidLogin = 'https://cn-stage-2.test.dataone.org/portal/oauth?action=start&target='+ENV.authRedirect;
    ENV.wholeTaleHost = 'http://dashboard.dev.wholetale.org';
    ENV.dataOneHost = 'https://dev.nceas.ucsb.edu/knb/d1/mn/v2';
  }

  if (environment === 'production') {
    ENV.apiHost = 'apiHOST';
    ENV.apiPath = 'api/v1';
    ENV.apiUrl = ENV.apiHost + '/' + ENV.apiPath;
    ENV.dev = false;
    ENV.authRedirect = 'https://dashboardHOST/login-success';
    ENV.orcidLogin = 'https://cn-stage-2.test.dataone.org/portal/oauth?action=start&target='+ENV.authRedirect
    ENV.wholeTaleHost = 'https://dashboardHOST';
    ENV.dataOneHost = 'dataOneHOST';
  }

  return ENV;
};

/*

https://auth.globus.org/v2/oauth2/authorize?access_type=online
    &state=iu9WwUYRo0QmGHTfiSO4PzgVIU5zFdXqbTHT5yciHvd1quMgUWdHMjv6anpWiw6c.http://localhost:4200?token={girderToken}
    &redirect_uri=https://girder.dev.wholetale.org:8080/api/v1/oauth/globus/callback
    &response_type=cod
    &client_id=724710b6-bb43-4803-a68e-b4133c34c599&scope=urn:globus:auth:scope:auth.globus.org:view_identities openid profile email
*/
<commit_msg>Simplify config<commit_after>'use strict';

module.exports = function () {
  return {
    moment: {
      // Options:
      // 'all' - all years, all timezones
      // '2010-2020' - 2010-2020, all timezones
      // 'none' - no data, just timezone API
      includeTimezone: 'all'
    }
  }
};

module.exports = function (environment) {
  let ENV = {
    taleIconHeight: "360",
    taleIconWidth: "360",

    modulePrefix: 'wholetale',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    torii: {
      providers: {

      }
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      },
      'ember-oauth2': {
        model: {}
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV['ember-cli-mirage'] = {
    enabled: false
  };

  if (environment === 'test') {
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.apiHost = '';
    ENV.apiPath = '/api';
    ENV.apiUrl = '';
    ENV.dev = true;
    // ENV.APP.autoboot = false;
  }

  ENV.apiHost = 'apiHOST';
  ENV.apiPath = 'api/v1';
  ENV.apiUrl = ENV.apiHost + '/' + ENV.apiPath;
  ENV.authRedirect = 'https://dashboardHOST/login-success';
  ENV.orcidLogin = 'https://cn-stage-2.test.dataone.org/portal/oauth?action=start&target='+ENV.authRedirect
  ENV.wholeTaleHost = 'https://dashboardHOST';
  ENV.dataOneHost = 'dataOneHOST';
  ENV.dev = environment === 'development';

  return ENV;
};

/*

https://auth.globus.org/v2/oauth2/authorize?access_type=online
    &state=iu9WwUYRo0QmGHTfiSO4PzgVIU5zFdXqbTHT5yciHvd1quMgUWdHMjv6anpWiw6c.http://localhost:4200?token={girderToken}
    &redirect_uri=https://girder.dev.wholetale.org:8080/api/v1/oauth/globus/callback
    &response_type=cod
    &client_id=724710b6-bb43-4803-a68e-b4133c34c599&scope=urn:globus:auth:scope:auth.globus.org:view_identities openid profile email
*/
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'jolliTest',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    contentSecurityPolicy: {
      'default-src': "* 'unsafe-inline' 'unsafe-eval'",
      'script-src': "* 'unsafe-inline' 'unsafe-eval'",
      'font-src': "* 'unsafe-inline' 'unsafe-eval'",
      'connect-src': "* 'unsafe-inline' 'unsafe-eval'",
      'img-src': "* 'unsafe-inline' 'unsafe-eval'",
      'style-src': "* 'unsafe-inline' 'unsafe-eval'",
      'media-src': "* 'unsafe-inline' 'unsafe-eval'"
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'auto';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>4/14 push to olli dev site version 1.15<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'jolli',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    contentSecurityPolicy: {
      'default-src': "* 'unsafe-inline' 'unsafe-eval'",
      'script-src': "* 'unsafe-inline' 'unsafe-eval'",
      'font-src': "* 'unsafe-inline' 'unsafe-eval'",
      'connect-src': "* 'unsafe-inline' 'unsafe-eval'",
      'img-src': "* 'unsafe-inline' 'unsafe-eval'",
      'style-src': "* 'unsafe-inline' 'unsafe-eval'",
      'media-src': "* 'unsafe-inline' 'unsafe-eval'"
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'auto';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    environment: environment,
    baseURL: '/',
    locationType: 'hash',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV.APP.version = require('../package.json').version;

  if (environment === 'development') {
    //ENV.APP.LOG_RESOLVER = true;
    //ENV.APP.LOG_ACTIVE_GENERATION = true;
    //ENV.APP.LOG_MODULE_RESOLVER = true;
    //ENV.APP.LOG_TRANSITIONS = true;
    //ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    //ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>Set .net build configuration in ember-cli environment.<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    environment: environment,
    configuration: 'Debug',
    baseURL: '/',
    locationType: 'hash',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV.APP.version = require('../package.json').version;

  if (environment === 'development') {
    //ENV.APP.LOG_RESOLVER = true;
    //ENV.APP.LOG_ACTIVE_GENERATION = true;
    //ENV.APP.LOG_MODULE_RESOLVER = true;
    //ENV.APP.LOG_TRANSITIONS = true;
    //ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    //ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'production') {
    ENV.configuration = 'Release';
  }

  return ENV;
};
<|endoftext|>


<commit_before>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');

var schema = new mongoose.Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  status: String,
  url: String,
  _source: {type: String, ref: 'Source'},
  _sourceType: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'}
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;
    this.storedAt = new Date();
  } else {
    // Capture updates before saving report
    if (this.isModified('status')) this._statusWasModified = true;
    if (this.isModified('_incident')) this._incidentWasModified = true;
  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:save', {_id: this._id.toString()});
  if (this._statusWasModified) schema.emit('report:status', {_id: this._id.toString(), status: this.status});
  if (this._incidentWasModified) schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident.toString()});
});

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine status filter
  if (query.status) {
    query.filter.status = {};
    if (query.status === 'assigned') query.filter.status.$exists = true;
    else if (query.status === 'unassigned') query.filter.status.$exists = false;
    else query.filter.status = query.status;
  }

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._sourceType = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

module.exports = Report;
<commit_msg>Bug #1745 Filtering on status = assigned not producing correct results<commit_after>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');

var schema = new mongoose.Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  status: String,
  url: String,
  _source: {type: String, ref: 'Source'},
  _sourceType: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'}
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;
    this.storedAt = new Date();
  } else {
    // Capture updates before saving report
    if (this.isModified('status')) this._statusWasModified = true;
    if (this.isModified('_incident')) this._incidentWasModified = true;
  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:save', {_id: this._id.toString()});
  if (this._statusWasModified) schema.emit('report:status', {_id: this._id.toString(), status: this.status});
  if (this._incidentWasModified) schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident.toString()});
});

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine status filter
  if (query.status) {
    query.filter.status = {};
    if (query.status === 'assigned') {
      query.filter.status.$exists = true;
      query.filter.status.$ne = '';
    }
    else if (query.status === 'unassigned') query.filter.status.$exists = false;
    else query.filter.status = query.status;
  }

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._sourceType = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

module.exports = Report;
<|endoftext|>


<commit_before>// https://github.com/gruntjs/grunt-contrib-watch
module.exports = {
	options: {
		livereload: true
	},
	js: {
		files: [
			'<%= files.js %>'
		],
		tasks: [
			'build:js'
		]
	},
	icons: {
		files: [
			'<%= files.icons %>'
		],
		tasks: [
			'newer:imagemin:icons',
			'webfont'
		]
	},
	php: {
		files: [
			'<%= files.php %>'
		],
		tasks: []
	},
	scss: {
		files: [
			'<%= files.scss %>'
		],
		tasks: [
			'sass:style',
			'postcss:style',
			'rtlcss:style',
			'cssmin:theme',
			'copy:css'
		]
	}
};
<commit_msg>Removed reference to grunt webfont<commit_after>// https://github.com/gruntjs/grunt-contrib-watch
module.exports = {
	options: {
		livereload: true
	},
	js: {
		files: [
			'<%= files.js %>'
		],
		tasks: [
			'build:js'
		]
	},
	icons: {
		files: [
			'<%= files.icons %>'
		],
		tasks: [
			'newer:imagemin:icons'
		]
	},
	php: {
		files: [
			'<%= files.php %>'
		],
		tasks: []
	},
	scss: {
		files: [
			'<%= files.scss %>'
		],
		tasks: [
			'sass:style',
			'postcss:style',
			'rtlcss:style',
			'cssmin:theme',
			'copy:css'
		]
	}
};
<|endoftext|>


<commit_before>define([
    "hr/utils",
    "hr/promise",
    "hr/hr",
    "views/dialogs/container",
    "views/dialogs/input",
    "views/dialogs/list",
    "text!resources/templates/dialogs/alert.html",
    "text!resources/templates/dialogs/confirm.html",
    "text!resources/templates/dialogs/prompt.html",
    "text!resources/templates/dialogs/schema.html"
], function(_, Q, hr, Dialog, DialogInputView, DialogListView,
alertTemplate, confirmTemplate, promptTemplate, schemaTemplate) {

    // Open a dialog
    var open = function(View, options) {
        var d = Q.defer();

        // Create the dialog
        var diag = new Dialog(_.extend(options || {}, {
            View: View
        }));

        // Bind close
        diag.on("close", function(force) {
            if (force) return d.reject(new Error("Dialog was been closed"));
            d.resolve(diag.view);
        });

        // Open it (add it to dom)
        diag.render();

        return d.promise;
    };

    // Input dialog
    var openInput = function(viewOptions, options, View) {
        return open(View || DialogInputView, _.extend(options || {}, {
            view: viewOptions || {}
        }))
        .then(function(view) {
            var value = view.getValue();

            if (value == null) return Q.reject(new Error("Dialog return empty value"));
            return value;
        });
    };

    // Alert
    var openAlert = function(text, options) {
        return openInput({
            template: alertTemplate,
            text: text
        });
    };
    var openErrorAlert = function(err) {
        return openAlert("Error: "+(err.message || err))
        .fin(function() {
            return Q.reject(err);
        });
    };

    // Confirm
    var openConfirm = function(text, options) {
        return openInput({
            template: confirmTemplate,
            text: text
        });
    };

    // Prompt
    var openPrompt = function(text, value, options) {
        return openInput({
            template: promptTemplate,
            text: text,
            defaultValue: value,
            value: function(d) { return d.$("input").val(); }
        });
    };

    // List
    var openList = function(source, options) {
        if (_.isArray(source)) {
            source = new hr.Collection({
                models: _.map(source, function(item) {
                    if (!_.isObject(item)) return { value: item };
                    return item;
                })
            });
        }

        return openInput(
            _.extend({
                template: "<%- item.get('value') %>",
                placeholder: "",
                filter: function() { return true; }
            }, options, {
                source: source
            }), {}, DialogListView);
    };

    // Schema
    var openSchema = function(schema, values) {
        values = values || {};

        return openInput({
            template: schemaTemplate,
            schema: schema,
            defaultValues: values,
            value: function(d) {
                var nvalues = _.clone(values);

                _.each(schema.properties, function(property, key) {
                    var v = d.$("*[name='"+key+"']").val();
                    nvalues[key] = v;
                });

                return nvalues;
            }
        });
    };

    return {
        open: open,
        alert: openAlert,
        error: openErrorAlert,
        confirm: openConfirm,
        prompt: openPrompt,
        list: openList,
        schema: openSchema
    };
});<commit_msg>Improve default template for list items<commit_after>define([
    "hr/utils",
    "hr/promise",
    "hr/hr",
    "views/dialogs/container",
    "views/dialogs/input",
    "views/dialogs/list",
    "text!resources/templates/dialogs/alert.html",
    "text!resources/templates/dialogs/confirm.html",
    "text!resources/templates/dialogs/prompt.html",
    "text!resources/templates/dialogs/schema.html"
], function(_, Q, hr, Dialog, DialogInputView, DialogListView,
alertTemplate, confirmTemplate, promptTemplate, schemaTemplate) {

    // Open a dialog
    var open = function(View, options) {
        var d = Q.defer();

        // Create the dialog
        var diag = new Dialog(_.extend(options || {}, {
            View: View
        }));

        // Bind close
        diag.on("close", function(force) {
            if (force) return d.reject(new Error("Dialog was been closed"));
            d.resolve(diag.view);
        });

        // Open it (add it to dom)
        diag.render();

        return d.promise;
    };

    // Input dialog
    var openInput = function(viewOptions, options, View) {
        return open(View || DialogInputView, _.extend(options || {}, {
            view: viewOptions || {}
        }))
        .then(function(view) {
            var value = view.getValue();

            if (value == null) return Q.reject(new Error("Dialog return empty value"));
            return value;
        });
    };

    // Alert
    var openAlert = function(text, options) {
        return openInput({
            template: alertTemplate,
            text: text
        });
    };
    var openErrorAlert = function(err) {
        return openAlert("Error: "+(err.message || err))
        .fin(function() {
            return Q.reject(err);
        });
    };

    // Confirm
    var openConfirm = function(text, options) {
        return openInput({
            template: confirmTemplate,
            text: text
        });
    };

    // Prompt
    var openPrompt = function(text, value, options) {
        return openInput({
            template: promptTemplate,
            text: text,
            defaultValue: value,
            value: function(d) { return d.$("input").val(); }
        });
    };

    // List
    var openList = function(source, options) {
        if (_.isArray(source)) {
            source = new hr.Collection({
                models: _.map(source, function(item) {
                    if (!_.isObject(item)) return { value: item };
                    return item;
                })
            });
        }

        return openInput(
            _.extend({
                template: "
<%- item.get('value') %>
",
                placeholder: "",
                filter: function() { return true; }
            }, options, {
                source: source
            }), {}, DialogListView);
    };

    // Schema
    var openSchema = function(schema, values) {
        values = values || {};

        return openInput({
            template: schemaTemplate,
            schema: schema,
            defaultValues: values,
            value: function(d) {
                var nvalues = _.clone(values);

                _.each(schema.properties, function(property, key) {
                    var v = d.$("*[name='"+key+"']").val();
                    nvalues[key] = v;
                });

                return nvalues;
            }
        });
    };

    return {
        open: open,
        alert: openAlert,
        error: openErrorAlert,
        confirm: openConfirm,
        prompt: openPrompt,
        list: openList,
        schema: openSchema
    };
});<|endoftext|>


<commit_before>var fs        = require('fs-extra');
var path      = require('path');
var _         = require('lodash');
var pluralize = require('pluralize');

// Shorter functions
var res = path.resolve;

module.exports = {
  description: 'Generate a controller, model, ressource or all of them.',
  logs: {
    before: 'Generating.',
    after: 'Generated.'
  },

  init: function(root, userRoot, args) {
    // check if userRoot is really an upapi app
    // Basically if templates and ressources.json exist
    var err = false;

    // TODO: try catch everything
    // careful: fs.exists will be deprecated soon...
    var stats = fs.lstatSync(path.join(userRoot, 'api/controllers'));
    if (!stats.isDirectory()) err = true;
    stats = fs.lstatSync(path.join(userRoot, 'api/models'));
    if (!stats.isDirectory()) err = true;
    stats = fs.lstatSync(res(userRoot, 'lib/config/ressources.json'));
    if (!stats.isFile()) err = true;

    if (err) {
      console.log('Are you sure you are in the good directory?');
      return false;
    }

    var types = ['controller', 'model', 'ressource'];
    this.name       = '';
    this.namePlural = '';

    // Minimum 2 arguments: generate <name>
    // args[1] can't be in types
    if (args.length === 2 && types.indexOf(args[1]) === -1) {
      this.name       = args[1];
      this.namePlural = pluralize(this.name);
      this.generate(root, userRoot);
    }

    // Maximum 3 arguments: generate <type> <name>
    // args[1] has to be in types
    else if (args.length === 3 && types.indexOf(args[1]) > -1) {
      this.name       = args[2];
      this.namePlural = pluralize(this.name);
      // generate the right file
      this['generate'+_.capitalize(args[1])](root, userRoot);
    }

    else {
      console.log('Bad usage');
      return false;
    }
  },

  generate: function(root, userRoot) {
    this.generateController(root, userRoot);
    this.generateModel(root, userRoot);
    this.generateRessource(root, userRoot);
  },

  generateController: function(root, userRoot) {
    console.log('Generating Controller ' + this.name);

    var content = fs.readFileSync(res(root, 'templates/controller.template'));
    content = _.template(content)({'ressource': this.namePlural});
    var fileName = res(userRoot, 'api/controllers/' + this.name + 'Controller.js' );

    fs.writeFileSync(fileName, content);
  },

  generateModel: function(root, userRoot) {
    console.log('Generating Model ' + this.name);

    var content = fs.readFileSync(res(root, 'templates/model.template'));
    content = _.template(content)({'ressource': this.name});
    var fileName = res(userRoot, 'api/models/' + this.namePlural+ '.js' );

    fs.writeFileSync(fileName, content);
  },

  generateRessource: function(root, userRoot) {
    console.log('Generating ressource ' + this.name);

    var ressources = require('../lib/config/ressources.json');
    var content = fs.readFileSync(res(root, 'templates/ressource.template'));
    content = _.template(content)({'ressource': this.namePlural});

    ressources.push(JSON.parse(content));

    var fileName = res(userRoot, 'lib/config/ressources.json');
    fs.writeJSONSync(fileName, ressources);
  }
};

<commit_msg>Fixes path to ressources.json<commit_after>var fs        = require('fs-extra');
var path      = require('path');
var _         = require('lodash');
var pluralize = require('pluralize');

// Shorter functions
var res = path.resolve;

module.exports = {
  description: 'Generate a controller, model, ressource or all of them.',
  logs: {
    before: 'Generating.',
    after: 'Generated.'
  },

  init: function(root, userRoot, args) {
    // check if userRoot is really an upapi app
    // Basically if templates and ressources.json exist
    var err = false;

    // TODO: try catch everything
    // careful: fs.exists will be deprecated soon...
    var stats = fs.lstatSync(path.join(userRoot, 'api/controllers'));
    if (!stats.isDirectory()) err = true;
    stats = fs.lstatSync(path.join(userRoot, 'api/models'));
    if (!stats.isDirectory()) err = true;
    stats = fs.lstatSync(res(userRoot, 'lib/config/ressources.json'));
    if (!stats.isFile()) err = true;

    if (err) {
      console.log('Are you sure you are in the good directory?');
      return false;
    }

    var types = ['controller', 'model', 'ressource'];
    this.name       = '';
    this.namePlural = '';

    // Minimum 2 arguments: generate <name>
    // args[1] can't be in types
    if (args.length === 2 && types.indexOf(args[1]) === -1) {
      this.name       = args[1];
      this.namePlural = pluralize(this.name);
      this.generate(root, userRoot);
    }

    // Maximum 3 arguments: generate <type> <name>
    // args[1] has to be in types
    else if (args.length === 3 && types.indexOf(args[1]) > -1) {
      this.name       = args[2];
      this.namePlural = pluralize(this.name);
      // generate the right file
      this['generate'+_.capitalize(args[1])](root, userRoot);
    }

    else {
      console.log('Bad usage');
      return false;
    }
  },

  generate: function(root, userRoot) {
    this.generateController(root, userRoot);
    this.generateModel(root, userRoot);
    this.generateRessource(root, userRoot);
  },

  generateController: function(root, userRoot) {
    console.log('Generating Controller ' + this.name);

    var content = fs.readFileSync(res(root, 'templates/controller.template'));
    content = _.template(content)({'ressource': this.namePlural});
    var fileName = res(userRoot, 'api/controllers/' + this.name + 'Controller.js' );

    fs.writeFileSync(fileName, content);
  },

  generateModel: function(root, userRoot) {
    console.log('Generating Model ' + this.name);

    var content = fs.readFileSync(res(root, 'templates/model.template'));
    content = _.template(content)({'ressource': this.name});
    var fileName = res(userRoot, 'api/models/' + this.namePlural+ '.js' );

    fs.writeFileSync(fileName, content);
  },

  generateRessource: function(root, userRoot) {
    console.log('Generating ressource ' + this.name);

    var ressources = require(userRoot +'/lib/config/ressources.json');
    var content = fs.readFileSync(res(root, 'templates/ressource.template'));
    content = _.template(content)({'ressource': this.namePlural});

    ressources.push(JSON.parse(content));

    var fileName = res(userRoot, 'lib/config/ressources.json');
    fs.writeJSONSync(fileName, ressources);
  }
};
<|endoftext|>