<commit_before>import * as utils from 'base/utils';
import Reader from 'base/reader';

const cached = {};

const CSVReader = Reader.extend({

  QUERY_FROM_CONCEPTS: 'concepts',
  QUERY_FROM_DATAPOINTS: 'datapoints',
  QUERY_FROM_ENTITIES: 'entities',

  CONDITION_CALLBACKS: {
    $gt: (configValue, rowValue) => rowValue > configValue,
    $gte: (configValue, rowValue) => rowValue >= configValue,
    $lt: (configValue, rowValue) => rowValue < configValue,
    $lte: (configValue, rowValue) => rowValue <= configValue,
    $in: (configValue, rowValue) => configValue.includes(rowValue)
  },

  ERRORS: {
    WRONG_TIME_COLUMN_OR_UNITS: 'reader/error/wrongTimeUnitsOrColumn',
    NOT_ENOUGH_ROWS_IN_FILE: 'reader/error/notEnoughRows',
    UNDEFINED_DELIMITER: 'reader/error/undefinedDelimiter',
    EMPTY_HEADERS: 'reader/error/emptyHeaders',
    GENERIC_ERROR: 'reader/error/generic',
  },

  _name: 'csv',

  /**
   * Initializes the reader.
   * @param {Object} readerInfo Information about the reader
   */
  init(readerInfo) {
    this._data = [];
    this._basepath = readerInfo.path;
    this.delimiter = readerInfo.delimiter;
    this.keySize = readerInfo.keySize || 1;

    if (!this._basepath) {
      utils.error('Missing base path for csv reader');
    }
  },

  /**
   * Reads from source
   * @param {Object} query to be performed
   * @param parsers
   * @returns {Promise} a promise that will be resolved when data is read
   */
  read(query, parsers = {}) {
    query = this._normalizeQuery(query, parsers);

    const {
      select,
      from,
      order_by = []
    } = query;

    const [orderBy] = order_by;

    return this.load()
      .then((result) => {
        const { data, columns } = result;
        this.ensureDataIsCorrect(result, parsers);

        switch (true) {
          case from === this.QUERY_FROM_CONCEPTS:
            return this._getConcepts(columns, data.map(this._getRowMapper(query, parsers)));

          case this._isDataQuery(from) && select.key.length > 0:
            return data
              .reduce(this._applyQuery(query, parsers), [])
              .sort((prev, next) => prev[orderBy] - next[orderBy]);

          default:
            return [];
        }
      })
      .catch((error) => {
        throw ({}).toString.call(error) === '[object Error]' ?
          this.error(this.ERRORS.GENERIC_ERROR, error) :
          error;
      });
  },

  ensureDataIsCorrect({ columns, data }, parsers) {
    const time = columns[this.keySize];
    const [firstRow] = data;
    const parser = parsers[time];

    if (parser && !parser(firstRow[time])) {
      throw this.error(this.ERRORS.WRONG_TIME_COLUMN_OR_UNITS);
    }

    if (!columns.length) {
      throw this.error(this.ERRORS.EMPTY_HEADERS);
    }
  },

  /**
   * This function returns info about the dataset
   * in case of CSV reader it's just the name of the file
   * @returns {object} object of info about the dataset
   */
  getDatasetInfo() {
    return { name: this._basepath.split('/').pop() };
  },

  load() {
    const { _basepath: path } = this;

    return new Promise((resolve, reject) => {
      const cachedData = cached[path];

      if (cachedData) {
        resolve(cachedData);
      } else {
        d3.text(path).get((error, text) => {
          if (!text) {
            return reject(`No permissions or empty file: ${path}. ${error}`);
          }

          if (error) {
            return reject(`Error happened while loading csv file: ${path}. ${error}`);
          }

          const { delimiter = this._guessDelimiter(text) } = this;
          const parser = d3.dsv(delimiter);
          const [header] = this._getRows(text, 1);
          const [columns] = parser.parseRows(header);
          const data = parser.parse(text);

          const result = { columns, data };
          cached[path] = result;
          resolve(result);
        });
      }
    });
  },

  _guessDelimiter(text) {
    const stringsToCheck = 2;
    const rows = this._getRows(text, stringsToCheck);

    if (rows.length !== stringsToCheck) {
      throw this.error(this.ERRORS.NOT_ENOUGH_ROWS_IN_FILE);
    }

    const [header, firstRow] = rows;
    const [comma, semicolon] = [',', ';'];
    const commasCountInHeader = this._countCharsInLine(header, comma);
    const semicolonsCountInHeader = this._countCharsInLine(header, semicolon);
    const commasCountInFirstRow = this._countCharsInLine(firstRow, comma);
    const semicolonsCountInFirstRow = this._countCharsInLine(firstRow, semicolon);

    if (
      commasCountInHeader === commasCountInFirstRow
      && commasCountInHeader > 1
      && (
        (semicolonsCountInHeader !== semicolonsCountInFirstRow)
        || (!semicolonsCountInHeader && !semicolonsCountInFirstRow)
      )
    ) {
      return comma;
    } else if (
      semicolonsCountInHeader === semicolonsCountInFirstRow
      && semicolonsCountInHeader > 1
      && (
        (commasCountInHeader !== commasCountInFirstRow)
        || (!commasCountInHeader && !commasCountInFirstRow)
      )
    ) {
      return semicolon;
    }

    throw this.error(this.ERRORS.UNDEFINED_DELIMITER);
  },

  _getRows(text, count = 0) {
    const re = /([^\r\n]+)/g;
    const rows = [];
    let rowsCount = 0;

    let matches = true;
    while (matches && rowsCount !== count) {
      matches = re.exec(text);
      if (matches && matches.length > 1) {
        ++rowsCount;
        rows.push(matches[1]);
      }
    }

    return rows;
  },

  _countCharsInLine(text, char) {
    const re = new RegExp(char, 'g');
    const matches = text.match(re);
    return matches ? matches.length : 0;
  },

  _normalizeQuery(_query, parsers) {
    const query = Object.assign({}, _query);
    const { where, join } = query;

    if (where.$and) {
      where.$and = where.$and.reduce((whereResult, condition) => {
        Object.keys(condition).forEach(rowKey => {
          const conditionValue = condition[rowKey];

          if (typeof conditionValue === 'string' && conditionValue.startsWith('$')) {
            const joinWhere = join[conditionValue].where;

            Object.keys(joinWhere)
              .forEach(joinRowKey => {
                const value = joinWhere[joinRowKey];
                const parser = parsers[joinRowKey];

                whereResult[joinRowKey] = parser ?
                  typeof value === 'object' ?
                    Object.keys(value).reduce((callbackConditions, callbackKey) => {
                      callbackConditions[callbackKey] = parser(value[callbackKey]);
                      return callbackConditions;
                    }, {}) :
                    parser(value)
                  : value;
              });
          } else {
            const parser = parsers[rowKey];
            whereResult[rowKey] = parser ? parser(conditionValue) : conditionValue;
          }
        });

        return whereResult;
      }, {});
    }

    return query;
  },

  _isDataQuery(from) {
    return [
      this.QUERY_FROM_DATAPOINTS,
      this.QUERY_FROM_ENTITIES
    ].includes(from);
  },

  _getRowMapper(query, parsers) {
    const { select } = query;

    return (row) => {
      let correct = true;

      const result = Object.keys(row).reduce((result, key) => {
        if (correct) {
          const value = row[key];
          const parser = parsers[key];
          let resultValue;

          if (parser) {
            resultValue = parser(value);
          } else {
            const numeric = parseFloat(value);
            resultValue = !isNaN(numeric) && isFinite(numeric) ? parseFloat(value.replace(',', '.')) : value;
          }

          if (!resultValue && resultValue !== 0) {
            if (select.key.includes(key)) {
              correct = false;
            }
          } else {
            result[key] = resultValue;
          }
        }

        return result;
      }, {});

      return correct && result;
    };
  },

  _getConcepts(columns, data) {
    return columns.map((concept, index) => {
      const result = { concept };

      if (index < this.keySize) {
        result.concept_type = 'entity_domain';
      } else if (index === this.keySize) {
        //the column after is expected to have time
        result.concept_type = 'time';
      } else {
        result.concept_type = 'measure';

        for (let i = data.length - 1; i >= 0; i--) {
          if (utils.isString(data[i][concept]) && data[i][concept] !== '') {
            result.concept_type = 'entity_set';
            [result.domain] = columns;
            break;
          }
        }
      }

      return result;
    })
  },

  _applyQuery(query, parsers) {
    const {
      select,
      from
    } = query;

    const [uniqueKey] = select.key;
    const uniqueValues = [];
    const mapRow = this._getRowMapper(query, parsers);

    return (result, row) => {
      row = mapRow(row);

      if (row) {
        const unique = row[uniqueKey];
        const isUnique = from !== this.QUERY_FROM_ENTITIES || !uniqueValues.includes(unique);
        const isSuitable = this._isSuitableRow(query, row);

        if (isSuitable && isUnique) {
          if (from === this.QUERY_FROM_ENTITIES) {
            uniqueValues.push(unique);
          }

          const rowFilteredByKeys = Object.keys(row)
            .reduce((resultRow, rowKey) => {
              if (select.key.includes(rowKey) || select.value.includes(rowKey)) {
                resultRow[rowKey] = row[rowKey];
              }

              return resultRow;
            }, {});

          result.push(rowFilteredByKeys);
        }
      }

      return result;
    };
  },

  _isSuitableRow(query, row) {
    const { where } = query;

    return !where.$and ||
      Object.keys(where.$and).every(conditionKey => {
        const condition = where.$and[conditionKey];
        const rowValue = row[conditionKey];

        // if the column is missing, then don't apply filter
        return rowValue === undefined
          || (typeof condition !== 'object' ?
            (rowValue === condition
              //resolve booleans via strings
              || condition === true && utils.isString(rowValue) && rowValue.toLowerCase().trim() === 'true'
              || condition === false && utils.isString(rowValue) && rowValue.toLowerCase().trim() === 'false'
            ) :
            Object.keys(condition).every(callbackKey =>
              this.CONDITION_CALLBACKS[callbackKey](condition[callbackKey], rowValue)
            ));
      });
  },

  error(code, message) {
    return { code, message };
  }

});

export default CSVReader;
<commit_msg>Handle throw in csv reader<commit_after>import * as utils from 'base/utils';
import Reader from 'base/reader';

const cached = {};

const CSVReader = Reader.extend({

  QUERY_FROM_CONCEPTS: 'concepts',
  QUERY_FROM_DATAPOINTS: 'datapoints',
  QUERY_FROM_ENTITIES: 'entities',

  CONDITION_CALLBACKS: {
    $gt: (configValue, rowValue) => rowValue > configValue,
    $gte: (configValue, rowValue) => rowValue >= configValue,
    $lt: (configValue, rowValue) => rowValue < configValue,
    $lte: (configValue, rowValue) => rowValue <= configValue,
    $in: (configValue, rowValue) => configValue.includes(rowValue)
  },

  ERRORS: {
    WRONG_TIME_COLUMN_OR_UNITS: 'reader/error/wrongTimeUnitsOrColumn',
    NOT_ENOUGH_ROWS_IN_FILE: 'reader/error/notEnoughRows',
    UNDEFINED_DELIMITER: 'reader/error/undefinedDelimiter',
    EMPTY_HEADERS: 'reader/error/emptyHeaders',
    GENERIC_ERROR: 'reader/error/generic',
  },

  _name: 'csv',

  /**
   * Initializes the reader.
   * @param {Object} readerInfo Information about the reader
   */
  init(readerInfo) {
    this._data = [];
    this._basepath = readerInfo.path;
    this.delimiter = readerInfo.delimiter;
    this.keySize = readerInfo.keySize || 1;

    if (!this._basepath) {
      utils.error('Missing base path for csv reader');
    }
  },

  /**
   * Reads from source
   * @param {Object} query to be performed
   * @param parsers
   * @returns {Promise} a promise that will be resolved when data is read
   */
  read(query, parsers = {}) {
    query = this._normalizeQuery(query, parsers);

    const {
      select,
      from,
      order_by = []
    } = query;

    const [orderBy] = order_by;

    return this.load()
      .then((result) => {
        const { data, columns } = result;
        this.ensureDataIsCorrect(result, parsers);

        switch (true) {
          case from === this.QUERY_FROM_CONCEPTS:
            return this._getConcepts(columns, data.map(this._getRowMapper(query, parsers)));

          case this._isDataQuery(from) && select.key.length > 0:
            return data
              .reduce(this._applyQuery(query, parsers), [])
              .sort((prev, next) => prev[orderBy] - next[orderBy]);

          default:
            return [];
        }
      })
      .catch((error) => {
        throw ({}).toString.call(error) === '[object Error]' ?
          this.error(this.ERRORS.GENERIC_ERROR, error) :
          error;
      });
  },

  ensureDataIsCorrect({ columns, data }, parsers) {
    const time = columns[this.keySize];
    const [firstRow] = data;
    const parser = parsers[time];

    if (parser && !parser(firstRow[time])) {
      throw this.error(this.ERRORS.WRONG_TIME_COLUMN_OR_UNITS);
    }

    if (!columns.length) {
      throw this.error(this.ERRORS.EMPTY_HEADERS);
    }
  },

  /**
   * This function returns info about the dataset
   * in case of CSV reader it's just the name of the file
   * @returns {object} object of info about the dataset
   */
  getDatasetInfo() {
    return { name: this._basepath.split('/').pop() };
  },

  load() {
    const { _basepath: path } = this;

    return new Promise((resolve, reject) => {
      const cachedData = cached[path];

      if (cachedData) {
        resolve(cachedData);
      } else {
        d3.text(path).get((error, text) => {
          if (!text) {
            return reject(`No permissions or empty file: ${path}. ${error}`);
          }

          if (error) {
            return reject(`Error happened while loading csv file: ${path}. ${error}`);
          }

          try {
            const { delimiter = this._guessDelimiter(text) } = this;
            const parser = d3.dsv(delimiter);
            const [header] = this._getRows(text, 1);
            const [columns] = parser.parseRows(header);
            const data = parser.parse(text);

            const result = { columns, data };
            cached[path] = result;
            resolve(result);
          } catch (e) {
            return reject(e);
          }
        });
      }
    });
  },

  _guessDelimiter(text) {
    const stringsToCheck = 2;
    const rows = this._getRows(text, stringsToCheck);

    if (rows.length !== stringsToCheck) {
      throw this.error(this.ERRORS.NOT_ENOUGH_ROWS_IN_FILE);
    }

    const [header, firstRow] = rows;
    const [comma, semicolon] = [',', ';'];
    const commasCountInHeader = this._countCharsInLine(header, comma);
    const semicolonsCountInHeader = this._countCharsInLine(header, semicolon);
    const commasCountInFirstRow = this._countCharsInLine(firstRow, comma);
    const semicolonsCountInFirstRow = this._countCharsInLine(firstRow, semicolon);

    if (
      commasCountInHeader === commasCountInFirstRow
      && commasCountInHeader > 1
      && (
        (semicolonsCountInHeader !== semicolonsCountInFirstRow)
        || (!semicolonsCountInHeader && !semicolonsCountInFirstRow)
        || (commasCountInHeader > semicolonsCountInHeader && commasCountInFirstRow > semicolonsCountInFirstRow)
      )
    ) {
      return comma;
    } else if (
      semicolonsCountInHeader === semicolonsCountInFirstRow
      && semicolonsCountInHeader > 1
      && (
        (commasCountInHeader !== commasCountInFirstRow)
        || (!commasCountInHeader && !commasCountInFirstRow)
        || (semicolonsCountInHeader > commasCountInHeader && semicolonsCountInFirstRow > commasCountInFirstRow)
      )
    ) {
      return semicolon;
    }

    throw this.error(this.ERRORS.UNDEFINED_DELIMITER);
  },

  _getRows(text, count = 0) {
    const re = /([^\r\n]+)/g;
    const rows = [];
    let rowsCount = 0;

    let matches = true;
    while (matches && rowsCount !== count) {
      matches = re.exec(text);
      if (matches && matches.length > 1) {
        ++rowsCount;
        rows.push(matches[1]);
      }
    }

    return rows;
  },

  _countCharsInLine(text, char) {
    const re = new RegExp(char, 'g');
    const matches = text.match(re);
    return matches ? matches.length : 0;
  },

  _normalizeQuery(_query, parsers) {
    const query = Object.assign({}, _query);
    const { where, join } = query;

    if (where.$and) {
      where.$and = where.$and.reduce((whereResult, condition) => {
        Object.keys(condition).forEach(rowKey => {
          const conditionValue = condition[rowKey];

          if (typeof conditionValue === 'string' && conditionValue.startsWith('$')) {
            const joinWhere = join[conditionValue].where;

            Object.keys(joinWhere)
              .forEach(joinRowKey => {
                const value = joinWhere[joinRowKey];
                const parser = parsers[joinRowKey];

                whereResult[joinRowKey] = parser ?
                  typeof value === 'object' ?
                    Object.keys(value).reduce((callbackConditions, callbackKey) => {
                      callbackConditions[callbackKey] = parser(value[callbackKey]);
                      return callbackConditions;
                    }, {}) :
                    parser(value)
                  : value;
              });
          } else {
            const parser = parsers[rowKey];
            whereResult[rowKey] = parser ? parser(conditionValue) : conditionValue;
          }
        });

        return whereResult;
      }, {});
    }

    return query;
  },

  _isDataQuery(from) {
    return [
      this.QUERY_FROM_DATAPOINTS,
      this.QUERY_FROM_ENTITIES
    ].includes(from);
  },

  _getRowMapper(query, parsers) {
    const { select } = query;

    return (row) => {
      let correct = true;

      const result = Object.keys(row).reduce((result, key) => {
        if (correct) {
          const value = row[key];
          const parser = parsers[key];
          let resultValue;

          if (parser) {
            resultValue = parser(value);
          } else {
            const numeric = parseFloat(value);
            resultValue = !isNaN(numeric) && isFinite(numeric) ? parseFloat(value.replace(',', '.')) : value;
          }

          if (!resultValue && resultValue !== 0) {
            if (select.key.includes(key)) {
              correct = false;
            }
          } else {
            result[key] = resultValue;
          }
        }

        return result;
      }, {});

      return correct && result;
    };
  },

  _getConcepts(columns, data) {
    return columns.map((concept, index) => {
      const result = { concept };

      if (index < this.keySize) {
        result.concept_type = 'entity_domain';
      } else if (index === this.keySize) {
        //the column after is expected to have time
        result.concept_type = 'time';
      } else {
        result.concept_type = 'measure';

        for (let i = data.length - 1; i >= 0; i--) {
          if (utils.isString(data[i][concept]) && data[i][concept] !== '') {
            result.concept_type = 'entity_set';
            [result.domain] = columns;
            break;
          }
        }
      }

      return result;
    })
  },

  _applyQuery(query, parsers) {
    const {
      select,
      from
    } = query;

    const [uniqueKey] = select.key;
    const uniqueValues = [];
    const mapRow = this._getRowMapper(query, parsers);

    return (result, row) => {
      row = mapRow(row);

      if (row) {
        const unique = row[uniqueKey];
        const isUnique = from !== this.QUERY_FROM_ENTITIES || !uniqueValues.includes(unique);
        const isSuitable = this._isSuitableRow(query, row);

        if (isSuitable && isUnique) {
          if (from === this.QUERY_FROM_ENTITIES) {
            uniqueValues.push(unique);
          }

          const rowFilteredByKeys = Object.keys(row)
            .reduce((resultRow, rowKey) => {
              if (select.key.includes(rowKey) || select.value.includes(rowKey)) {
                resultRow[rowKey] = row[rowKey];
              }

              return resultRow;
            }, {});

          result.push(rowFilteredByKeys);
        }
      }

      return result;
    };
  },

  _isSuitableRow(query, row) {
    const { where } = query;

    return !where.$and ||
      Object.keys(where.$and).every(conditionKey => {
        const condition = where.$and[conditionKey];
        const rowValue = row[conditionKey];

        // if the column is missing, then don't apply filter
        return rowValue === undefined
          || (typeof condition !== 'object' ?
            (rowValue === condition
              //resolve booleans via strings
              || condition === true && utils.isString(rowValue) && rowValue.toLowerCase().trim() === 'true'
              || condition === false && utils.isString(rowValue) && rowValue.toLowerCase().trim() === 'false'
            ) :
            Object.keys(condition).every(callbackKey =>
              this.CONDITION_CALLBACKS[callbackKey](condition[callbackKey], rowValue)
            ));
      });
  },

  error(code, message) {
    return { code, message };
  }

});

export default CSVReader;
<|endoftext|>


<commit_before>// Load in modules and set up routes
var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    _ = require('underscore'),
    smith = require('../src/smith.js'),
    spriteDir = path.join(__dirname, 'test_sprites'),
    expectedDir = __dirname + '/expected_files';

module.exports = {
  // Setup
  'An array of sprites': function () {
    this.sprites = [
      path.join(spriteDir, 'sprite1.png'),
      path.join(spriteDir, 'sprite2.jpg'),
      path.join(spriteDir, 'sprite3.png')
    ];

    // By default, write to the topDown namespace
    this.namespace = 'topDown.';
  },
  'An empty array': function () {
    this.namespace = 'empty.';
    this.sprites = [];
  },

  // Processing
  'when processed via spritesmith': '_when processed via spritesmith',
  '_when processed via spritesmith': function (done) {
    var that = this;

    // Load in params and add on to src
    var options = this.options || {},
        params = _.extend({'src': this.sprites}, options);

    // Attempt to smith out the sprites
    smith(params, function (err, result) {
      // If there is an error, throw it
      if (err) {
        throw err;
      } else {
      // Otherwise, save the result
        that.result = result;
      }

      // Callback
      done(err);
    });
  },
  'when converted from left to right': [function () {
    this.namespace = 'leftRight.';
    this.options = {'algorithm': 'left-right'};
  }, 'when processed via spritesmith'],
  'when provided with a padding parameter': [function () {
    this.namespace = 'padding.';
    this.options = {'algorithm': 'binary-tree', 'padding': 2};
  }, 'when processed via spritesmith'],
  'when told not to sort': [function () {
    this.namespace = 'unsort.';
    this.options = {'algorithm': 'top-down', 'algorithmOpts': {'sort': false}};
  }, 'when processed via spritesmith'],

  // Engine-specific setups
  'phantomjssmith': ['An array of sprites', function () {
    this.namespace = 'phantomjs.';
    this.options = {'engine': 'phantomjs'};
  }],
  'gmsmith': ['An array of sprites', function () {
    this.namespace = 'gm.';
    this.options = {'engine': 'gm'};
  }],
  'canvassmith': ['An array of sprites', function () {
    this.namespace = 'canvas.';
    this.options = {'engine': 'canvas'};
  }],

  // Assertions
  'renders a top-down spritesheet': 'assertSpritesheet',
  'renders a left-right spritesheet': 'assertSpritesheet',
  'renders a padded spritesheet': 'assertSpritesheet',
  'renders an unsorted spritesheet': 'assertSpritesheet',
  'has the proper coordinates': 'assertCoordinates',
  'has the proper properties': 'assertProps',
  'returns an image': function () {
    // DEV: Write out to actual_files
    if (process.env.TEST_DEBUG) {
      try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + this.namespace + 'sprite.png', this.result.image, 'binary');
    }

    assert.notEqual(this.result.image, '');
  },
  'renders an empty spritesheet': function () {
    assert.strictEqual(this.result.image, '');
  },
  'returns an empty coordinate mapping': function () {
    assert.deepEqual(this.result.coordinates, {});
  },

  // Bulky assertions
  assertSpritesheet: function () {
    var result = this.result,
        namespace = this.namespace;

    // DEV: Write out to actual_files
    if (process.env.TEST_DEBUG) {
      try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.png', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.jpg', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.tiff', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'coordinates.json', JSON.stringify(result.coordinates, null, 4));
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'properties.json', JSON.stringify(result.properties, null, 4));
    }

    // Assert the actual image is the same expected
    var actualImage = result.image,
        expectedFilenames = ['canvas.png', 'gm.png', 'gm2.png', 'phantomjs.png', 'phantomjs2.png'],
        matchesAnImage = false;

    // ANTI-PATTERN: Looping over set without identifiable lines for stack traces
    expectedFilenames.forEach(function testAgainstExpected (filename) {
      if (!matchesAnImage) {
        var filepath = path.join(expectedDir, namespace + filename);
        if (fs.existsSync(filepath)) {
          var expectedImage = fs.readFileSync(filepath, 'binary');
          matchesAnImage = actualImage === expectedImage;
        }
      }
    });

    assert(matchesAnImage, "Actual image does not match expected image");
  },
  assertCoordinates: function () {
    // Load in the coordinates
    var result = this.result,
        expectedCoords = require(expectedDir + '/' + this.namespace + 'coordinates.json');

    // Normalize the actual coordinates
    // TODO: Normalize dir should be an option
    var actualCoords = result.coordinates,
        normCoords = {};
    assert(actualCoords, "Result does not have a coordinates property");

    Object.getOwnPropertyNames(actualCoords).forEach(function (filepath) {
      var file = path.relative(spriteDir, filepath);
      normCoords[file] = actualCoords[filepath];
    });

    // Assert that the returned coordinates deep equal those in the coordinates.json
    assert.deepEqual(expectedCoords, normCoords, "Actual coordinates do not match expected coordinates");
  },
  assertProps: function () {
    // Load in the properties
    var actualProps = this.result.properties,
        expectedProps = require(expectedDir + '/' + this.namespace + 'properties.json');

    // Assert that the returned properties equals the expected properties
    assert.deepEqual(expectedProps, actualProps, "Actual properties do not match expected properties");
  }
};
<commit_msg>Adjusted order of sprites for test<commit_after>// Load in modules and set up routes
var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    _ = require('underscore'),
    smith = require('../src/smith.js'),
    spriteDir = path.join(__dirname, 'test_sprites'),
    expectedDir = __dirname + '/expected_files';

module.exports = {
  // Setup
  'An array of sprites': function () {
    this.sprites = [
      path.join(spriteDir, 'sprite1.png'),
      path.join(spriteDir, 'sprite3.png'),
      path.join(spriteDir, 'sprite2.jpg')
    ];

    // By default, write to the topDown namespace
    this.namespace = 'topDown.';
  },
  'An empty array': function () {
    this.namespace = 'empty.';
    this.sprites = [];
  },

  // Processing
  'when processed via spritesmith': '_when processed via spritesmith',
  '_when processed via spritesmith': function (done) {
    var that = this;

    // Load in params and add on to src
    var options = this.options || {},
        params = _.extend({'src': this.sprites}, options);

    // Attempt to smith out the sprites
    smith(params, function (err, result) {
      // If there is an error, throw it
      if (err) {
        throw err;
      } else {
      // Otherwise, save the result
        that.result = result;
      }

      // Callback
      done(err);
    });
  },
  'when converted from left to right': [function () {
    this.namespace = 'leftRight.';
    this.options = {'algorithm': 'left-right'};
  }, 'when processed via spritesmith'],
  'when provided with a padding parameter': [function () {
    this.namespace = 'padding.';
    this.options = {'algorithm': 'binary-tree', 'padding': 2};
  }, 'when processed via spritesmith'],
  'when told not to sort': [function () {
    this.namespace = 'unsorted.';
    this.options = {'algorithm': 'top-down', 'algorithmOpts': {'sort': false}};
  }, 'when processed via spritesmith'],

  // Engine-specific setups
  'phantomjssmith': ['An array of sprites', function () {
    this.namespace = 'phantomjs.';
    this.options = {'engine': 'phantomjs'};
  }],
  'gmsmith': ['An array of sprites', function () {
    this.namespace = 'gm.';
    this.options = {'engine': 'gm'};
  }],
  'canvassmith': ['An array of sprites', function () {
    this.namespace = 'canvas.';
    this.options = {'engine': 'canvas'};
  }],

  // Assertions
  'renders a top-down spritesheet': 'assertSpritesheet',
  'renders a left-right spritesheet': 'assertSpritesheet',
  'renders a padded spritesheet': 'assertSpritesheet',
  'renders an unsorted spritesheet': 'assertSpritesheet',
  'has the proper coordinates': 'assertCoordinates',
  'has the proper properties': 'assertProps',
  'returns an image': function () {
    // DEV: Write out to actual_files
    if (process.env.TEST_DEBUG) {
      try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + this.namespace + 'sprite.png', this.result.image, 'binary');
    }

    assert.notEqual(this.result.image, '');
  },
  'renders an empty spritesheet': function () {
    assert.strictEqual(this.result.image, '');
  },
  'returns an empty coordinate mapping': function () {
    assert.deepEqual(this.result.coordinates, {});
  },

  // Bulky assertions
  assertSpritesheet: function () {
    var result = this.result,
        namespace = this.namespace;

    // DEV: Write out to actual_files
    if (process.env.TEST_DEBUG) {
      try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.png', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.jpg', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'sprite.tiff', result.image, 'binary');
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'coordinates.json', JSON.stringify(result.coordinates, null, 4));
      fs.writeFileSync(__dirname + '/actual_files/' + namespace + 'properties.json', JSON.stringify(result.properties, null, 4));
    }

    // Assert the actual image is the same expected
    var actualImage = result.image,
        expectedFilenames = ['canvas.png', 'gm.png', 'gm2.png', 'phantomjs.png', 'phantomjs2.png'],
        matchesAnImage = false;

    // ANTI-PATTERN: Looping over set without identifiable lines for stack traces
    expectedFilenames.forEach(function testAgainstExpected (filename) {
      if (!matchesAnImage) {
        var filepath = path.join(expectedDir, namespace + filename);
        if (fs.existsSync(filepath)) {
          var expectedImage = fs.readFileSync(filepath, 'binary');
          matchesAnImage = actualImage === expectedImage;
        }
      }
    });

    assert(matchesAnImage, "Actual image does not match expected image");
  },
  assertCoordinates: function () {
    // Load in the coordinates
    var result = this.result,
        expectedCoords = require(expectedDir + '/' + this.namespace + 'coordinates.json');

    // Normalize the actual coordinates
    // TODO: Normalize dir should be an option
    var actualCoords = result.coordinates,
        normCoords = {};
    assert(actualCoords, "Result does not have a coordinates property");

    Object.getOwnPropertyNames(actualCoords).forEach(function (filepath) {
      var file = path.relative(spriteDir, filepath);
      normCoords[file] = actualCoords[filepath];
    });

    // Assert that the returned coordinates deep equal those in the coordinates.json
    assert.deepEqual(expectedCoords, normCoords, "Actual coordinates do not match expected coordinates");
  },
  assertProps: function () {
    // Load in the properties
    var actualProps = this.result.properties,
        expectedProps = require(expectedDir + '/' + this.namespace + 'properties.json');

    // Assert that the returned properties equals the expected properties
    assert.deepEqual(expectedProps, actualProps, "Actual properties do not match expected properties");
  }
};
<|endoftext|>


<commit_before>'use strict';

function MethodGenerationContext(holderGenc, outerGenc, blockMethod) {
    var signature = null,
        primitive = false,
        needsToCatchNonLocalReturn      = false,
        throwsNonLocalReturn            = false,
        accessesVariablesOfOuterContext = false,
        args       = [],
        argNames   = [],
        locals     = [],
        localNames = [],
        _this      = this;

    this.makeCatchNonLocalReturn = function () {
        throwsNonLocalReturn = true;

        var ctx = _this.getOuterContext();
        ctx.needsToCatchNonLocalReturn = true;
    };

    this.requiresContext = function () {
        return throwsNonLocalReturn || accessesVariablesOfOuterContext;
    };

    this.getOuterContext = function () {
        if (outerGenc == null) {
            return _this;
        } else {
            return outerGenc.getOuterContext();
        }
    };

    this.needsToCatchNonLocalReturn = function () {
        // only the most outer method needs to catch
        return needsToCatchNonLocalReturn && outerGenc == null;
    };

    this.assemble = function (body, sourceSection) {
        if (primitive) {
            return constructEmptyPrimitive(signature);
        }

        if (needsToCatchNonLocalReturn) {
            body = createCatchNonLocalReturn(body);
        }

        // return the method - the holder field is to be set later on!
        return  universe.newMethod(signature,
            getSourceSectionForMethod(sourceSection), body, locals.length);
    };

    function getSourceSectionForMethod(ssBody) {
        return new SourceSection(
                holderGenc.getName().getString() + ">>" + signature.toString(),
                ssBody.startLine(), ssBody.startColumn(),
                ssBody.charIndex(), ssBody.length());
    }

    this.markAsPrimitive = function () {
        primitive = true;
    };

    this.setSignature = function (sig) {
        signature = sig;
    };

    function addArgument(arg) {
        if (("self" == arg || "$blockSelf" == arg) && args.length > 0) {
            throw new IllegalStateException("The self argument always has to be the first argument of a method");
        }

        var argument = new Argument(arg, args.length);
        args.push(argument);
        argNames.push(arg);
    }

    this.addArgumentIfAbsent = function (arg) {
        if (argNames.indexOf(arg) != -1) {
            return;
        }
        addArgument(arg);
    };

    this.addLocalIfAbsent = function (local) {
        if (localNames.indexOf(local) != -1) {
            return;
        }
        addLocal(local);
    };

    function addLocal(local) {
        var l = new Local(local, locals.length);
        locals.push(l);
        localNames.push(local);
    }

    this.isBlockMethod = function () {
        return blockMethod;
    };

    this.getHolder = function () {
        return holderGenc;
    };

    this.getOuterSelfContextLevel = function () {
        if (outerGenc == null) {
            return 0;
        } else {
            return outerGenc.getOuterSelfContextLevel() + 1;
        }
    };

    this.getContextLevel = function (varName) {
        if (localNames.indexOf(varName) != -1
            || argNames.indexOf(varName) != -1) {
            return 0;
        }

        if (outerGenc != null) {
            return 1 + outerGenc.getContextLevel(varName);
        }
        return 0;
    };

    this.getVariable = function (varName) {
        var i = localNames.indexOf(varName);
        if (i != -1) {
            return locals[i];
        }

        i = argNames.indexOf(varName);
        if (i != -1) {
            return args[i];
        }

        if (outerGenc != null) {
            var outerVar = outerGenc.getVariable(varName);
            if (outerVar != null) {
                accessesVariablesOfOuterContext = true;
            }
            return outerVar;
        }
        return null;
    };

    this.getSuperReadNode = function (source) {
        var self = _this.getVariable("self");
        return self.getSuperReadNode(_this.getOuterSelfContextLevel(),
            holderGenc.getName(), holderGenc.isClassSide(), source);
    };

    this.getLocalReadNode = function (variableName, source) {
        var variable = _this.getVariable(variableName);
        return variable.getReadNode(_this.getContextLevel(variableName), source);
    };

    this.getLocalWriteNode = function (variableName, valExpr, source) {
        var variable = _this.getLocal(variableName);
        return variable.getWriteNode(_this.getContextLevel(variableName),
            valExpr, source);
    };

    this.getLocal = function (varName) {
        var i = localNames.indexOf(varName);
        if (i != -1) {
            return locals[i];
        }

        if (outerGenc != null) {
            var outerLocal = outerGenc.getLocal(varName);
            if (outerLocal != null) {
                accessesVariablesOfOuterContext = true;
            }
            return outerLocal;
        }
        return null;
    };

    this.getNonLocalReturn = function (expr, source) {
        _this.makeCatchNonLocalReturn();
        return createNonLocalReturn(expr, _this.getOuterSelfContextLevel(),
            source);
    };

    function getSelfRead(source) {
        return _this.getVariable("self").getReadNode(
            _this.getContextLevel("self"), source);
    }

    this.getObjectFieldRead = function (fieldName, source) {
        if (!holderGenc.hasField(fieldName)) {
            return null;
        }
        return createFieldRead(getSelfRead(source),
            holderGenc.getFieldIndex(fieldName), source);
    };

    this.getGlobalRead = function (varName, source) {
        return createGlobalRead(varName, universe, source);
    };

    this.getObjectFieldWrite = function (fieldName, exp, source) {
        if (!holderGenc.hasField(fieldName)) {
            return null;
        }

        return createFieldWrite(getSelfRead(source), exp,
            holderGenc.getFieldIndex(fieldName), source);
    };

    /**
     * @returns {Number} of explicit arguments,
     *         i.e., excluding the implicit 'self' argument
     */
    this.getNumberOfArguments = function () {
        return args.length;
    };

    this.getSignature = function () {
        return signature;
    };

    this.toString = function () {
        return "MethodGenC(" + holderGenc.getName().getString() + ">>" + signature.toString() + ")";
    };
}
<commit_msg>We don't track whether a block access context or not<commit_after>'use strict';

function MethodGenerationContext(holderGenc, outerGenc, blockMethod) {
    var signature = null,
        primitive = false,
        needsToCatchNonLocalReturn      = false,
        throwsNonLocalReturn            = false,
        args       = [],
        argNames   = [],
        locals     = [],
        localNames = [],
        _this      = this;

    this.makeCatchNonLocalReturn = function () {
        throwsNonLocalReturn = true;

        var ctx = _this.getOuterContext();
        ctx.needsToCatchNonLocalReturn = true;
    };

    this.requiresContext = function () {
        return throwsNonLocalReturn || accessesVariablesOfOuterContext;
    };

    this.getOuterContext = function () {
        if (outerGenc == null) {
            return _this;
        } else {
            return outerGenc.getOuterContext();
        }
    };

    this.needsToCatchNonLocalReturn = function () {
        // only the most outer method needs to catch
        return needsToCatchNonLocalReturn && outerGenc == null;
    };

    this.assemble = function (body, sourceSection) {
        if (primitive) {
            return constructEmptyPrimitive(signature);
        }

        if (needsToCatchNonLocalReturn) {
            body = createCatchNonLocalReturn(body);
        }

        // return the method - the holder field is to be set later on!
        return  universe.newMethod(signature,
            getSourceSectionForMethod(sourceSection), body, locals.length);
    };

    function getSourceSectionForMethod(ssBody) {
        return new SourceSection(
                holderGenc.getName().getString() + ">>" + signature.toString(),
                ssBody.startLine(), ssBody.startColumn(),
                ssBody.charIndex(), ssBody.length());
    }

    this.markAsPrimitive = function () {
        primitive = true;
    };

    this.setSignature = function (sig) {
        signature = sig;
    };

    function addArgument(arg) {
        if (("self" == arg || "$blockSelf" == arg) && args.length > 0) {
            throw new IllegalStateException("The self argument always has to be the first argument of a method");
        }

        var argument = new Argument(arg, args.length);
        args.push(argument);
        argNames.push(arg);
    }

    this.addArgumentIfAbsent = function (arg) {
        if (argNames.indexOf(arg) != -1) {
            return;
        }
        addArgument(arg);
    };

    this.addLocalIfAbsent = function (local) {
        if (localNames.indexOf(local) != -1) {
            return;
        }
        addLocal(local);
    };

    function addLocal(local) {
        var l = new Local(local, locals.length);
        locals.push(l);
        localNames.push(local);
    }

    this.isBlockMethod = function () {
        return blockMethod;
    };

    this.getHolder = function () {
        return holderGenc;
    };

    this.getOuterSelfContextLevel = function () {
        if (outerGenc == null) {
            return 0;
        } else {
            return outerGenc.getOuterSelfContextLevel() + 1;
        }
    };

    this.getContextLevel = function (varName) {
        if (localNames.indexOf(varName) != -1
            || argNames.indexOf(varName) != -1) {
            return 0;
        }

        if (outerGenc != null) {
            return 1 + outerGenc.getContextLevel(varName);
        }
        return 0;
    };

    this.getVariable = function (varName) {
        var i = localNames.indexOf(varName);
        if (i != -1) {
            return locals[i];
        }

        i = argNames.indexOf(varName);
        if (i != -1) {
            return args[i];
        }

        if (outerGenc != null) {
            return outerGenc.getVariable(varName);
        }
        return null;
    };

    this.getSuperReadNode = function (source) {
        var self = _this.getVariable("self");
        return self.getSuperReadNode(_this.getOuterSelfContextLevel(),
            holderGenc.getName(), holderGenc.isClassSide(), source);
    };

    this.getLocalReadNode = function (variableName, source) {
        var variable = _this.getVariable(variableName);
        return variable.getReadNode(_this.getContextLevel(variableName), source);
    };

    this.getLocalWriteNode = function (variableName, valExpr, source) {
        var variable = _this.getLocal(variableName);
        return variable.getWriteNode(_this.getContextLevel(variableName),
            valExpr, source);
    };

    this.getLocal = function (varName) {
        var i = localNames.indexOf(varName);
        if (i != -1) {
            return locals[i];
        }

        if (outerGenc != null) {
            return outerGenc.getLocal(varName);
        }
        return null;
    };

    this.getNonLocalReturn = function (expr, source) {
        _this.makeCatchNonLocalReturn();
        return createNonLocalReturn(expr, _this.getOuterSelfContextLevel(),
            source);
    };

    function getSelfRead(source) {
        return _this.getVariable("self").getReadNode(
            _this.getContextLevel("self"), source);
    }

    this.getObjectFieldRead = function (fieldName, source) {
        if (!holderGenc.hasField(fieldName)) {
            return null;
        }
        return createFieldRead(getSelfRead(source),
            holderGenc.getFieldIndex(fieldName), source);
    };

    this.getGlobalRead = function (varName, source) {
        return createGlobalRead(varName, universe, source);
    };

    this.getObjectFieldWrite = function (fieldName, exp, source) {
        if (!holderGenc.hasField(fieldName)) {
            return null;
        }

        return createFieldWrite(getSelfRead(source), exp,
            holderGenc.getFieldIndex(fieldName), source);
    };

    /**
     * @returns {Number} of explicit arguments,
     *         i.e., excluding the implicit 'self' argument
     */
    this.getNumberOfArguments = function () {
        return args.length;
    };

    this.getSignature = function () {
        return signature;
    };

    this.toString = function () {
        return "MethodGenC(" + holderGenc.getName().getString() + ">>" + signature.toString() + ")";
    };
}
<|endoftext|>


<commit_before>'use strict';
const mongoClient = require ('mongodb').MongoClient;
const ObjectId = require ('mongodb').ObjectId;
const hash = require ('./hash');

let db = null;
let users = null;
let polls = null;

// connect to database and set up collections
function init (uri) {
  console.log ('db.init');
  return new Promise ((resolve, reject) => {
    if (db === null) {
      mongoClient.connect (uri, (err, instance) => {
        if (err) {
          console.log ('  err', err);
          return reject (err);
        }
        db = instance;
        users = db.collection ('users');
        users.ensureIndex ({username: 1}, {unique: true})
        .then (() => {
          polls = db.collection ('polls');
          console.log ('  completed');
          return resolve ();
        }).catch (err => {
          console.log ('  err', err);
          reject (err);
        });
      });
    } else {
      console.log ('  already completed');
      resolve ();
    }
  });
}

// Close database and null out references
function close () {
  return new Promise ((resolve, reject) => {
    if (db) {
      users = null;
      polls = null;
      db.close ()
      .then (() => { db = null; resolve (); })
      .catch (() => { db = null; resolve (); });
    } else {
      resolve ();
    }
  });
}

// Find single user by user name
function findUserByUsername (username) {
  return users.findOne ({username: username });
}

// Insert single user with username, password only populated. Suitable for
// register user type functions.
function insertUser (username, password) {
  return new Promise ((resolve, reject) => {
    findUserByUsername (username)
    .then (result => {
      if (result !== null) {
        reject (new Error ('User already exists'));
      } else {
        let userHash = hash.create (password);
        let user = {
          username: username,
          hash: userHash.hash,
          salt: userHash.salt,
          name: '',
          email: ''
        };
        users.insert (user, {w:1})
        .then (result => { resolve (result); });
      }
    })
    .catch (err => {
      reject (err);
    });
  });
}

// Update user information (not username or password).
function updateUser (username, name, email) {
  return users.update (
    { 'username': username },
    { $set: {'name': name, 'email': email} }
  );
}

// remove user by username
function removeUser (username) {
  return users.remove ({ username: username });
}

// get all polls
function getPolls () {
  return polls.find ().toArray ();
}

// get a single poll
function getPoll (_id) {
  return polls.findOne ({ _id: new ObjectId (_id) });
}

// add a new poll
function insertPoll (poll) {
  return polls.insert (poll, {w:1});
}

// update a poll by _id
function updatePoll (_id, poll) {
  return polls.update ({ _id: new ObjectId (_id) }, poll);
}

// remove a poll by _id
function removePoll (_id) {
  return polls.remove ({ _id: new ObjectId (_id) });
}

// remove all polls
function removePolls () {
  return polls.remove ({});
}

// vote in a poll, for a specific choice.
function vote (_id, choice) {
  return new Promise ((resolve, reject) => {
    polls.update (
      {_id: new ObjectId (_id), 'choices.text': choice},
      {$inc: { 'choices.$.votes': 1 }},
      (err, result) => {
        if (err) {
          reject (err);
        } else {
          resolve (result);
        }
      }
    );
  });
}

exports.init = init;
exports.close = close;
exports.findUserByUsername = findUserByUsername;
exports.insertUser = insertUser;
exports.updateUser = updateUser;
exports.removeUser = removeUser;
exports.getPolls = getPolls;
exports.getPoll = getPoll;
exports.insertPoll = insertPoll;
exports.updatePoll = updatePoll;
exports.removePoll = removePoll;
exports.removePolls = removePolls;
exports.vote = vote;
<commit_msg>Improve error handling<commit_after>'use strict';
const mongoClient = require ('mongodb').MongoClient;
const ObjectId = require ('mongodb').ObjectId;
const hash = require ('./hash');

let db = null;
let users = null;
let polls = null;

// connect to database and set up collections
function init (uri) {
  console.log ('db.init');
  return new Promise ((resolve, reject) => {
    if (db === null) {
      mongoClient.connect (uri, (err, instance) => {
        if (err) {
          console.log ('  err', err);
          return reject (err);
        }
        db = instance;
        Promise.resolve ().then (() => {
          users = db.collection ('users');
          return users.ensureIndex ({username: 1}, {unique: true});
        }).then (() => {
          polls = db.collection ('polls');
          return resolve ();
        }).catch (err => {
          console.log ('  err', err);
          reject (err);
        });
      });
    } else {
      resolve ();
    }
  });
}

// Close database and null out references
function close () {
  return new Promise ((resolve, reject) => {
    if (db) {
      users = null;
      polls = null;
      Promise.resolve ().then (() => {
        return db.close ();
      }).then (() => {
        db = null;
        resolve ();
      }).catch (() => {
        db = null;
        resolve ();
      });
    } else {
      resolve ();
    }
  });
}

// Find single user by user name
function findUserByUsername (username) {
  return users.findOne ({username: username });
}

// Insert single user with username, password only populated. Suitable for
// register user type functions.
function insertUser (username, password) {
  return new Promise ((resolve, reject) => {
    Promise.resolve ().then (() => {
      return findUserByUsername (username);
    }).then (result => {
      if (result !== null) {
        return reject (new Error ('User already exists'));
      }
      let userHash = hash.create (password);
      let user = {
        username: username,
        hash: userHash.hash,
        salt: userHash.salt,
        name: '',
        email: ''
      };
      return users.insert (user, {w:1});
    }).then (result => {
      resolve (result);
    }).catch (err => {
      reject (err);
    });
  });
}

// Update user information (not username or password).
function updateUser (username, name, email) {
  return users.update (
    { 'username': username },
    { $set: {'name': name, 'email': email} }
  );
}

// remove user by username
function removeUser (username) {
  return users.remove ({ username: username });
}

// get all polls
function getPolls () {
  return polls.find ().toArray ();
}

// get a single poll
function getPoll (_id) {
  return polls.findOne ({ _id: new ObjectId (_id) });
}

// add a new poll
function insertPoll (poll) {
  return polls.insert (poll, {w:1});
}

// update a poll by _id
function updatePoll (_id, poll) {
  return polls.update ({ _id: new ObjectId (_id) }, poll);
}

// remove a poll by _id
function removePoll (_id) {
  return polls.remove ({ _id: new ObjectId (_id) });
}

// remove all polls
function removePolls () {
  return polls.remove ({});
}

// vote in a poll, for a specific choice.
function vote (_id, choice) {
  return polls.update (
      {_id: new ObjectId (_id), 'choices.text': choice},
      {$inc: { 'choices.$.votes': 1 }});
}

exports.init = init;
exports.close = close;
exports.findUserByUsername = findUserByUsername;
exports.insertUser = insertUser;
exports.updateUser = updateUser;
exports.removeUser = removeUser;
exports.getPolls = getPolls;
exports.getPoll = getPoll;
exports.insertPoll = insertPoll;
exports.updatePoll = updatePoll;
exports.removePoll = removePoll;
exports.removePolls = removePolls;
exports.vote = vote;
<|endoftext|>


<commit_before>import _ from 'intl'
import BaseComponent from 'base-component'
import Icon from 'icon'
import Link from 'link'
import { NavLink, NavTabs } from 'nav'
import Page from '../page'
import React, { cloneElement } from 'react'
import VmActionBar from './action-bar'
import { Select, Text } from 'editable'
import {
  assign,
  forEach,
  isEmpty,
  map,
  pick
} from 'lodash'
import {
  editVm,
  fetchVmStats,
  isVmRunning,
  migrateVm
} from 'xo'
import { Container, Row, Col } from 'grid'
import {
  connectStore,
  mapPlus,
  routes
} from 'utils'
import {
  createGetObject,
  createGetObjectsOfType,
  createGetVmDisks,
  createSelector,
  createSumBy,
  getCheckPermissions,
  isAdmin
} from 'selectors'

import TabGeneral from './tab-general'
import TabStats from './tab-stats'
import TabConsole from './tab-console'
import TabContainers from './tab-containers'
import TabDisks from './tab-disks'
import TabNetwork from './tab-network'
import TabSnapshots from './tab-snapshots'
import TabLogs from './tab-logs'
import TabAdvanced from './tab-advanced'

// ===================================================================

@routes('general', {
  advanced: TabAdvanced,
  console: TabConsole,
  containers: TabContainers,
  disks: TabDisks,
  general: TabGeneral,
  logs: TabLogs,
  network: TabNetwork,
  snapshots: TabSnapshots,
  stats: TabStats
})
@connectStore(() => {
  const getVm = createGetObject()

  const getContainer = createGetObject(
    (state, props) => getVm(state, props).$container
  )

  const getPool = createGetObject(
    (state, props) => getVm(state, props).$pool
  )

  const getVbds = createGetObjectsOfType('VBD').pick(
    (state, props) => getVm(state, props).$VBDs
  ).sort()
  const getVdis = createGetVmDisks(getVm)
  const getSrs = createGetObjectsOfType('SR').pick(
    createSelector(
      getVdis,
      vdis => map(vdis, vdi => vdi.$SR)
    )
  )

  const getVmTotalDiskSpace = createSumBy(
    createGetVmDisks(getVm),
    'size'
  )

  const getHosts = createGetObjectsOfType('host')

  return (state, props) => {
    const vm = getVm(state, props)
    if (!vm) {
      return {}
    }

    return {
      checkPermissions: getCheckPermissions(state, props),
      container: getContainer(state, props),
      hosts: getHosts(state, props),
      isAdmin: isAdmin(state, props),
      pool: getPool(state, props),
      srs: getSrs(state, props),
      vbds: getVbds(state, props),
      vdis: getVdis(state, props),
      vm,
      vmTotalDiskSpace: getVmTotalDiskSpace(state, props)
    }
  }
})
export default class Vm extends BaseComponent {
  static contextTypes = {
    router: React.PropTypes.object
  }

  loop (vm = this.props.vm) {
    if (this.cancel) {
      this.cancel()
    }

    if (!isVmRunning(vm)) {
      return
    }

    let cancelled = false
    this.cancel = () => { cancelled = true }

    fetchVmStats(vm).then(stats => {
      if (cancelled) {
        return
      }
      this.cancel = null

      clearTimeout(this.timeout)
      this.setState({
        statsOverview: stats
      }, () => {
        this.timeout = setTimeout(this.loop, stats.interval * 1000)
      })
    })
  }
  loop = ::this.loop

  componentWillMount () {
    this.loop()
  }

  componentWillUnmount () {
    clearTimeout(this.timeout)
  }

  componentWillReceiveProps (props) {
    const vmCur = this.props.vm
    const vmNext = props.vm

    if (vmCur && !vmNext) {
      this.context.router.push('/')
    }

    if (!isVmRunning(vmCur) && isVmRunning(vmNext)) {
      this.loop(vmNext)
    } else if (isVmRunning(vmCur) && !isVmRunning(vmNext)) {
      this.setState({
        statsOverview: undefined
      })
    }
  }

  _getCanSnapshot = createSelector(
    () => this.props.checkPermissions,
    () => this.props.vm,
    () => this.props.srs,
    (checkPermissions, vm, srs) => checkPermissions([
      [ vm.id, 'administrate' ],
      ...map(srs, sr => [ sr.id, 'operate' ])
    ])
  )

  _setNameDescription = nameDescription => editVm(this.props.vm, { name_description: nameDescription })
  _setNameLabel = nameLabel => editVm(this.props.vm, { name_label: nameLabel })
  _migrateVm = host => migrateVm(this.props.vm, host)

  _selectOptionRenderer = option => option.name_label

  header () {
    const { vm, container, pool, hosts } = this.props
    if (!vm) {
      return <Icon icon='loading' />
    }
    return <Container>
      <Row>
        <Col mediumSize={6} className='header-title'>

            {isEmpty(vm.current_operations)
              ? <Icon icon={`vm-${vm.power_state.toLowerCase()}`} />
              : <Icon icon='vm-busy' />
            }
            {' '}
            <Text
              value={vm.name_label}
              onChange={this._setNameLabel}
            />

            <Text
              value={vm.name_description}
              onChange={this._setNameDescription}
            />

              {vm.power_state === 'Running' && container &&

                   -
                  <Select
                    onChange={this._migrateVm}
                    options={hosts}
                    renderer={this._selectOptionRenderer}
                    useLongClick
                    value={container}
                  >
                    <Link to={`/${container.type}s/${container.id}`}>{container.name_label}</Link>
                  </Select>

              }
              {' '}
              {pool && (<Link to={`/pools/${pool.id}`}>{pool.name_label}</Link>)}

        </Col>
        <Col mediumSize={6} className='text-xs-center'>

            <VmActionBar vm={vm} />

        </Col>
      </Row>

      <Row>
        <Col>
          <NavTabs>
            <NavLink to={`/vms/${vm.id}/general`}>{_('generalTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/stats`}>{_('statsTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/console`}>{_('consoleTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/network`}>{_('networkTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/disks`}>{_('disksTabName', { disks: vm.$VBDs.length })}</NavLink>
            {this._getCanSnapshot() && <NavLink to={`/vms/${vm.id}/snapshots`}>{_('snapshotsTabName')} {vm.snapshots.length !== 0 && {vm.snapshots.length}}</NavLink>}
            <NavLink to={`/vms/${vm.id}/logs`}>{_('logsTabName')}</NavLink>
            {vm.docker && <NavLink to={`/vms/${vm.id}/containers`}>{_('containersTabName')}</NavLink>}
            <NavLink to={`/vms/${vm.id}/advanced`}>{_('advancedTabName')}</NavLink>
          </NavTabs>
        </Col>
      </Row>
    </Container>
  }

  _toggleHeader = () => this.setState({ collapsedHeader: !this.state.collapsedHeader })

  render () {
    const { container, vm } = this.props

    if (!vm) {
      return
{_('statusLoading')}

    }

    const childProps = assign(pick(this.props, [
      'container',
      'pool',
      'removeTag',
      'srs',
      'vbds',
      'vdis',
      'vm',
      'vmTotalDiskSpace'
    ]), pick(this.state, [
      'statsOverview'
    ]))
    return <Page header={this.header()} collapsedHeader={this.state.collapsedHeader} title={`${vm.name_label}${container ? ` (${container.name_label})` : ''}`}>
      {cloneElement(this.props.children, { ...childProps, toggleHeader: this._toggleHeader })}
    </Page>
  }
}
<commit_msg>fix(vm): remove unused imports<commit_after>import _ from 'intl'
import BaseComponent from 'base-component'
import Icon from 'icon'
import Link from 'link'
import { NavLink, NavTabs } from 'nav'
import Page from '../page'
import React, { cloneElement } from 'react'
import VmActionBar from './action-bar'
import { Select, Text } from 'editable'
import {
  assign,
  isEmpty,
  map,
  pick
} from 'lodash'
import {
  editVm,
  fetchVmStats,
  isVmRunning,
  migrateVm
} from 'xo'
import { Container, Row, Col } from 'grid'
import {
  connectStore,
  routes
} from 'utils'
import {
  createGetObject,
  createGetObjectsOfType,
  createGetVmDisks,
  createSelector,
  createSumBy,
  getCheckPermissions,
  isAdmin
} from 'selectors'

import TabGeneral from './tab-general'
import TabStats from './tab-stats'
import TabConsole from './tab-console'
import TabContainers from './tab-containers'
import TabDisks from './tab-disks'
import TabNetwork from './tab-network'
import TabSnapshots from './tab-snapshots'
import TabLogs from './tab-logs'
import TabAdvanced from './tab-advanced'

// ===================================================================

@routes('general', {
  advanced: TabAdvanced,
  console: TabConsole,
  containers: TabContainers,
  disks: TabDisks,
  general: TabGeneral,
  logs: TabLogs,
  network: TabNetwork,
  snapshots: TabSnapshots,
  stats: TabStats
})
@connectStore(() => {
  const getVm = createGetObject()

  const getContainer = createGetObject(
    (state, props) => getVm(state, props).$container
  )

  const getPool = createGetObject(
    (state, props) => getVm(state, props).$pool
  )

  const getVbds = createGetObjectsOfType('VBD').pick(
    (state, props) => getVm(state, props).$VBDs
  ).sort()
  const getVdis = createGetVmDisks(getVm)
  const getSrs = createGetObjectsOfType('SR').pick(
    createSelector(
      getVdis,
      vdis => map(vdis, vdi => vdi.$SR)
    )
  )

  const getVmTotalDiskSpace = createSumBy(
    createGetVmDisks(getVm),
    'size'
  )

  const getHosts = createGetObjectsOfType('host')

  return (state, props) => {
    const vm = getVm(state, props)
    if (!vm) {
      return {}
    }

    return {
      checkPermissions: getCheckPermissions(state, props),
      container: getContainer(state, props),
      hosts: getHosts(state, props),
      isAdmin: isAdmin(state, props),
      pool: getPool(state, props),
      srs: getSrs(state, props),
      vbds: getVbds(state, props),
      vdis: getVdis(state, props),
      vm,
      vmTotalDiskSpace: getVmTotalDiskSpace(state, props)
    }
  }
})
export default class Vm extends BaseComponent {
  static contextTypes = {
    router: React.PropTypes.object
  }

  loop (vm = this.props.vm) {
    if (this.cancel) {
      this.cancel()
    }

    if (!isVmRunning(vm)) {
      return
    }

    let cancelled = false
    this.cancel = () => { cancelled = true }

    fetchVmStats(vm).then(stats => {
      if (cancelled) {
        return
      }
      this.cancel = null

      clearTimeout(this.timeout)
      this.setState({
        statsOverview: stats
      }, () => {
        this.timeout = setTimeout(this.loop, stats.interval * 1000)
      })
    })
  }
  loop = ::this.loop

  componentWillMount () {
    this.loop()
  }

  componentWillUnmount () {
    clearTimeout(this.timeout)
  }

  componentWillReceiveProps (props) {
    const vmCur = this.props.vm
    const vmNext = props.vm

    if (vmCur && !vmNext) {
      this.context.router.push('/')
    }

    if (!isVmRunning(vmCur) && isVmRunning(vmNext)) {
      this.loop(vmNext)
    } else if (isVmRunning(vmCur) && !isVmRunning(vmNext)) {
      this.setState({
        statsOverview: undefined
      })
    }
  }

  _getCanSnapshot = createSelector(
    () => this.props.checkPermissions,
    () => this.props.vm,
    () => this.props.srs,
    (checkPermissions, vm, srs) => checkPermissions([
      [ vm.id, 'administrate' ],
      ...map(srs, sr => [ sr.id, 'operate' ])
    ])
  )

  _setNameDescription = nameDescription => editVm(this.props.vm, { name_description: nameDescription })
  _setNameLabel = nameLabel => editVm(this.props.vm, { name_label: nameLabel })
  _migrateVm = host => migrateVm(this.props.vm, host)

  _selectOptionRenderer = option => option.name_label

  header () {
    const { vm, container, pool, hosts } = this.props
    if (!vm) {
      return <Icon icon='loading' />
    }
    return <Container>
      <Row>
        <Col mediumSize={6} className='header-title'>

            {isEmpty(vm.current_operations)
              ? <Icon icon={`vm-${vm.power_state.toLowerCase()}`} />
              : <Icon icon='vm-busy' />
            }
            {' '}
            <Text
              value={vm.name_label}
              onChange={this._setNameLabel}
            />

            <Text
              value={vm.name_description}
              onChange={this._setNameDescription}
            />

              {vm.power_state === 'Running' && container &&

                   -
                  <Select
                    onChange={this._migrateVm}
                    options={hosts}
                    renderer={this._selectOptionRenderer}
                    useLongClick
                    value={container}
                  >
                    <Link to={`/${container.type}s/${container.id}`}>{container.name_label}</Link>
                  </Select>

              }
              {' '}
              {pool && (<Link to={`/pools/${pool.id}`}>{pool.name_label}</Link>)}

        </Col>
        <Col mediumSize={6} className='text-xs-center'>

            <VmActionBar vm={vm} />

        </Col>
      </Row>

      <Row>
        <Col>
          <NavTabs>
            <NavLink to={`/vms/${vm.id}/general`}>{_('generalTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/stats`}>{_('statsTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/console`}>{_('consoleTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/network`}>{_('networkTabName')}</NavLink>
            <NavLink to={`/vms/${vm.id}/disks`}>{_('disksTabName', { disks: vm.$VBDs.length })}</NavLink>
            {this._getCanSnapshot() && <NavLink to={`/vms/${vm.id}/snapshots`}>{_('snapshotsTabName')} {vm.snapshots.length !== 0 && {vm.snapshots.length}}</NavLink>}
            <NavLink to={`/vms/${vm.id}/logs`}>{_('logsTabName')}</NavLink>
            {vm.docker && <NavLink to={`/vms/${vm.id}/containers`}>{_('containersTabName')}</NavLink>}
            <NavLink to={`/vms/${vm.id}/advanced`}>{_('advancedTabName')}</NavLink>
          </NavTabs>
        </Col>
      </Row>
    </Container>
  }

  _toggleHeader = () => this.setState({ collapsedHeader: !this.state.collapsedHeader })

  render () {
    const { container, vm } = this.props

    if (!vm) {
      return
{_('statusLoading')}

    }

    const childProps = assign(pick(this.props, [
      'container',
      'pool',
      'removeTag',
      'srs',
      'vbds',
      'vdis',
      'vm',
      'vmTotalDiskSpace'
    ]), pick(this.state, [
      'statsOverview'
    ]))
    return <Page header={this.header()} collapsedHeader={this.state.collapsedHeader} title={`${vm.name_label}${container ? ` (${container.name_label})` : ''}`}>
      {cloneElement(this.props.children, { ...childProps, toggleHeader: this._toggleHeader })}
    </Page>
  }
}
<|endoftext|>


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

    define(['config'], function(config) {

        var storage = {
            container: null
        };

        // set the storage container
        if (config.persist == "local") {
            storage.container = localStorage;
        } else if (config.persist == "session") {
            storage.container = sessionStorage;
        } else {
            storage.container = null;
        }

        console.log(storage.container);

        // Pass in accounts from an account manager
        storage.storeAccounts = function (appId, accounts, services) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length == 0) {
                appData = {}
            } else {
                appData = JSON.parse(appData);
            }

            // add accounts from the manager
            var i, account, array = [];
            for (i = 0; i < accounts.length; i++) {
                account = accounts[i];
                array.push(JSON.stringify(account));
            }
            // add accounts not in services
            for (i = 0; i < appData.accounts.length; i++) {
                account = JSON.parse(appData.accounts[i]);
                if (services.indexOf(account.service) == -1) {
                    array.push(appData.accounts[i]);
                }
            }
            // store the final array
            appData.accounts = array;
            storage.container[key] = JSON.stringify(appData);
        };

        // Return an array of accounts, initialize if necessary
        // the appData is stringified
        storage.loadAccounts = function (appId, services) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length === 0) {
                appData = {};
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
                return appData.accounts;
            }

            appData = JSON.parse(appData);
            // accounts also needs to be parsed
            var i, array = [], accounts = appData.accounts;
            for (i = 0; i < accounts.length; i++) {
                var acc = JSON.parse(accounts[i]);
                if (services.indexOf(acc.service) != -1) {
                    array.push(acc);
                }
            }
            return array;
        };

        storage.removeAllAccounts = function (appId) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length == 0) {
                appData = {};
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
            } else {
                appData = JSON.parse(appData);
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
            }
        };

        storage.storeId = function(explorerId) {
            if (!storage.container) return;
            var key = 'k-explorerId';
            storage.container[key] = explorerId;
        }

        storage.loadId = function() {
            if (!storage.container) return;
            var key = 'k-explorerId';
            return storage.container[key];
        }

        return storage;
    });
})();<commit_msg>storage.js: remove extraneous log statement<commit_after>(function () {
    'use strict';

    define(['config'], function(config) {

        var storage = {
            container: null
        };

        // set the storage container
        if (config.persist == "local") {
            storage.container = localStorage;
        } else if (config.persist == "session") {
            storage.container = sessionStorage;
        } else {
            storage.container = null;
        }

        // Pass in accounts from an account manager
        storage.storeAccounts = function (appId, accounts, services) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length == 0) {
                appData = {}
            } else {
                appData = JSON.parse(appData);
            }

            // add accounts from the manager
            var i, account, array = [];
            for (i = 0; i < accounts.length; i++) {
                account = accounts[i];
                array.push(JSON.stringify(account));
            }
            // add accounts not in services
            for (i = 0; i < appData.accounts.length; i++) {
                account = JSON.parse(appData.accounts[i]);
                if (services.indexOf(account.service) == -1) {
                    array.push(appData.accounts[i]);
                }
            }
            // store the final array
            appData.accounts = array;
            storage.container[key] = JSON.stringify(appData);
        };

        // Return an array of accounts, initialize if necessary
        // the appData is stringified
        storage.loadAccounts = function (appId, services) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length === 0) {
                appData = {};
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
                return appData.accounts;
            }

            appData = JSON.parse(appData);
            // accounts also needs to be parsed
            var i, array = [], accounts = appData.accounts;
            for (i = 0; i < accounts.length; i++) {
                var acc = JSON.parse(accounts[i]);
                if (services.indexOf(acc.service) != -1) {
                    array.push(acc);
                }
            }
            return array;
        };

        storage.removeAllAccounts = function (appId) {
            if (!storage.container) return;

            var key = 'k-' + appId, appData = storage.container[key];
            if (!appData || appData.length == 0) {
                appData = {};
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
            } else {
                appData = JSON.parse(appData);
                appData.accounts = [];
                storage.container[key] = JSON.stringify(appData);
            }
        };

        storage.storeId = function(explorerId) {
            if (!storage.container) return;
            var key = 'k-explorerId';
            storage.container[key] = explorerId;
        }

        storage.loadId = function() {
            if (!storage.container) return;
            var key = 'k-explorerId';
            return storage.container[key];
        }

        return storage;
    });
})();
<|endoftext|>


<commit_before>'use strict'
var express = require('express'),
    app = express(),
    config = require('./libs/config'),
    router = require('./routes'),
    SerialPort = require('serialport').SerialPort,
    serialPort = new SerialPort(config.serial.path, {
      baudrate: config.serial.buadRate
    }, false),
    cards = require('./routes/cards'),
    door = require('./libs/door'),
    bodyParser = require('body-parser');

app.use(bodyParser.json())

app.get('/', function(req, res){
  res.send({
    active: true,
    timestamp: new Date().getTime()
  })
})

app.use('/api/v1', router)

// Server Listener
app.listen(config.app.port, config.app.host, function(e) {
  console.log('Listening on http://%s:%s', config.app.host, config.app.port)
  door.setup(function() {
    serialPort.open(function (error) {
      if ( error ) {
        console.log('failed to open: '+ error);
      } else {
        serialPort.on('data', function(data) {
          cards.isUIDAllowed(data, function(err, test) {
            if (err) throw err;
            door.open();
          });
        });
      }
    });
  });
})
<commit_msg>Allow to work in DEV or PROD<commit_after>'use strict'
var express = require('express'),
    app = express(),
    config = require('./libs/config'),
    router = require('./routes'),
    SerialPort = require('serialport').SerialPort,
    serialPort = new SerialPort(config.serial.path, {
      baudrate: config.serial.buadRate
    }, false),
    cards = require('./routes/cards'),
    door = require('./libs/door'),
    bodyParser = require('body-parser');

app.use(bodyParser.json())

app.get('/', function(req, res){
  res.send({
    active: true,
    timestamp: new Date().getTime()
  })
})

app.use('/api/v1', router)

// Server Listener
app.listen(config.app.port, config.app.host, function(e) {
  console.log('Listening on http://%s:%s', config.app.host, config.app.port)
  if(process.env.PROD) {
    door.setup(function() {
      serialPort.open(function (error) {
        if ( error ) {
          console.log('failed to open: '+ error);
        } else {
          serialPort.on('data', function(data) {
            cards.isUIDAllowed(data, function(err, test) {
              if (err) throw err;
              door.open();
            });
          });
        }
      });
    });
  }
})
<|endoftext|>


<commit_before>import {enableSave, createWindowTabWithFormattedData} from './utils'
let path = require('path')
const _ = require('lodash')
function makeCustomFormat(separator, delimiter) {
  // assemble a format object describing a custom format
  return {
    label: 'Custom',
    filters: [],
    options: {
      separator: separator,
      delimiter: delimiter
    },
    mime_type: 'text/plain',
    default_extension: 'txt'
  }
}

function openFile(format) {
  Dialog.showOpenDialog({
    filters: format.filters
  }, function(filenames) {
    readFile(filenames, format)
  })
}

function openCustom() {
  // var window = BrowserWindow.getFocusedWindow()
  var dialog = new BrowserWindow({width: 200, height: 400})
  dialog.once('closed', function() {
    ipc.removeAllListeners('formatSelected')
    dialog = null
  })
  ipc.once('formatSelected', function(event, data) {
    dialog.close()
    var format = makeCustomFormat(data.separator, data.delimiter)
    openFile(format)
  })
  dialog.loadURL(`http://localhost:9080/#/customformat`)
}

function filenameExists(filename) {
  let threshold = global.tab.activeFilename ? 1 : 0
  console.log(`threshold is: ${threshold}`)
  let length = global.tab.filenames.length
  let filtered = _.without(global.tab.filenames, filename)
  return length - filtered.length > threshold
}

function saveFileAs(format, window) {
  if (!window) {
    window = BrowserWindow.getFocusedWindow()
  }
  Dialog.showSaveDialog({
    filters: format.filters,
    defaultPath: global.tab.activeTitle
  }, function(filename) {
    if (filename === undefined) {
      console.log('returning as no filename was entered...')
      return
    }
    if (filenameExists(filename)) {
      console.log('returning as filename exists...')
      return
    }

    // enableSave()
    window.webContents.send('saveData', format, filename)
    window.format = format
    window.webContents.send('saveDataSuccess')
  })
}

function saveAsCustom() {
  var window = BrowserWindow.getFocusedWindow()
  var dialog = new BrowserWindow({width: 200, height: 400})
  dialog.once('closed', function() {
    ipc.removeAllListeners('formatSelected')
    dialog = null
  })
  ipc.once('formatSelected', function(event, data) {
    dialog.close()
    var format = makeCustomFormat(data.separator, data.delimiter)
    saveFileAs(format, window)
  })
  dialog.loadURL(`http://localhost:9080/#/customformat`)
}

function saveFile() {
  var window = BrowserWindow.getFocusedWindow()
  window.webContents.send('saveData', window.format)
}

function readFile(filenames, format) {
  if (filenames === undefined) {

  } else {
    var filename = filenames[0]
    Fs.readFile(filename, 'utf-8', function(err, data) {
      if (err) {
        console.log(err.stack)
      }
      createWindowTabWithFormattedData(data, format)
      // enableSave()
    })
  }
}

export {
  openFile,
  openCustom,
  readFile,
  saveFileAs,
  saveAsCustom,
  saveFile
}
<commit_msg>OCC-247: added feedback on file duplicate.<commit_after>import {enableSave, createWindowTabWithFormattedData} from './utils'
let path = require('path')
const _ = require('lodash')
function makeCustomFormat(separator, delimiter) {
  // assemble a format object describing a custom format
  return {
    label: 'Custom',
    filters: [],
    options: {
      separator: separator,
      delimiter: delimiter
    },
    mime_type: 'text/plain',
    default_extension: 'txt'
  }
}

function openFile(format) {
  Dialog.showOpenDialog({
    filters: format.filters
  }, function(filenames) {
    readFile(filenames, format)
  })
}

function openCustom() {
  // var window = BrowserWindow.getFocusedWindow()
  var dialog = new BrowserWindow({width: 200, height: 400})
  dialog.once('closed', function() {
    ipc.removeAllListeners('formatSelected')
    dialog = null
  })
  ipc.once('formatSelected', function(event, data) {
    dialog.close()
    var format = makeCustomFormat(data.separator, data.delimiter)
    openFile(format)
  })
  dialog.loadURL(`http://localhost:9080/#/customformat`)
}

function filenameExists(filename) {
  let threshold = global.tab.activeFilename ? 1 : 0
  console.log(`threshold is: ${threshold}`)
  let length = global.tab.filenames.length
  let filtered = _.without(global.tab.filenames, filename)
  return length - filtered.length > threshold
}

function saveFileAs(format, window) {
  if (!window) {
    window = BrowserWindow.getFocusedWindow()
  }
  Dialog.showSaveDialog({
    filters: format.filters,
    defaultPath: global.tab.activeTitle
  }, function(filename) {
    if (filename === undefined) {
      console.log('returning as no filename was entered...')
      return
    }
    if (filenameExists(filename)) {
      console.log('returning as filename exists...')
      Dialog.showMessageBox(window, {
        type: 'warning',
        title: 'Save failed',
        message: 'Filename already exists. Please try again.'
      })
      return
    }

    // enableSave()
    window.webContents.send('saveData', format, filename)
    window.format = format
    window.webContents.send('saveDataSuccess')
  })
}

function saveAsCustom() {
  var window = BrowserWindow.getFocusedWindow()
  var dialog = new BrowserWindow({width: 200, height: 400})
  dialog.once('closed', function() {
    ipc.removeAllListeners('formatSelected')
    dialog = null
  })
  ipc.once('formatSelected', function(event, data) {
    dialog.close()
    var format = makeCustomFormat(data.separator, data.delimiter)
    saveFileAs(format, window)
  })
  dialog.loadURL(`http://localhost:9080/#/customformat`)
}

function saveFile() {
  var window = BrowserWindow.getFocusedWindow()
  window.webContents.send('saveData', window.format)
}

function readFile(filenames, format) {
  if (filenames === undefined) {

  } else {
    var filename = filenames[0]
    Fs.readFile(filename, 'utf-8', function(err, data) {
      if (err) {
        console.log(err.stack)
      }
      createWindowTabWithFormattedData(data, format)
      // enableSave()
    })
  }
}

export {
  openFile,
  openCustom,
  readFile,
  saveFileAs,
  saveAsCustom,
  saveFile
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 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, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {

    "use strict";

    // Registry for languages that have specific per-language URLs or file paths that we use
    // elsewhere in Brackets.
    //
    // TODO: dynamically populate the local prefix list below?
    module.exports = {
        root: true,
        "cs": true,
        "de": true,
        "es": true,
		"fa-ir": true,
        "fi": true,
        "fr": true,
        "id": true,
        "it": true,
        "ja": true,
        "ko": true,
        "nb": true,
        "pl": true,
        "pt-br": true,
        "pt-pt": true,
        "ru": true,
        "sv": true,
        "zh-cn": true,
        "tr": true
    };
});
<commit_msg>enable urls<commit_after>/*
 * Copyright (c) 2013 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, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {

    "use strict";

    // Registry for languages that have specific per-language URLs or file paths that we use
    // elsewhere in Brackets.
    //
    // TODO: dynamically populate the local prefix list below?
    module.exports = {
        root: true,
        "cs": true,
        "de": true,
        "es": true,
		"fa-ir": true,
        "fi": true,
        "fr": true,
        "hr": true,
        "id": true,
        "it": true,
        "ja": true,
        "ko": true,
        "nb": true,
        "pl": true,
        "pt-br": true,
        "pt-pt": true,
        "ru": true,
        "sv": true,
        "zh-cn": true,
        "tr": true
    };
});
<|endoftext|>


<commit_before>var conjectures = [];

function guessIncidences(el) {
    if (guessIncidences.hasOwnProperty(el.kind))
        guessIncidences[el.kind](el);
}

guessIncidences.P = function(p) {
    csgeo.lines.forEach(function(l) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
    csgeo.conics.forEach(function(c) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.L = function(l) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.S = guessIncidences.L;

guessIncidences.C = function(c) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

function applyIncidence(a, b) {
    return function() {
        a.incidences.push(b.name);
        b.incidences.push(a.name);
    };
}

function incidentPL(p, l) {
    return {
        toString: function() {
            return "point " + p.name + " incident line " + l.name;
        },
        apply: applyIncidence(p, l),
        holds: function() {
            var pn = List.scaldiv(List.abs(p.homog), p.homog);
            var ln = List.scaldiv(List.abs(l.homog), l.homog);
            var prod = CSNumber.abs(List.scalproduct(pn, ln));
            return (prod.value.real < 0.0000000000001);
        }
    };
}

function incidentPC(p, c) {
    return {
        toString: function() {
            return "point " + p.name + " incident conic " + c.name;
        },
        apply: applyIncidence(p, c),
        holds: function() {
            var erg = General.mult(c.matrix, p.homog);
            erg = General.mult(p.homog, erg);
            erg = CSNumber.abs(erg);
            return (erg.value.real < 0.0000000000001);
        }
    };
}

function checkConjectures() {
    var debug = true;
    if(debug) console.log("conjectures", conjectures.length);
    if(!debug) if (conjectures.length === 0) return;
    //    debugger;
    backupGeo();
    // TODO: we need some randomized proving here:
    // move free elements and check conjectures a number of times.
    // For now assume that all conjectures could be verified.

    var ii, jj, kk;
    var free = csgeo.free;
    var moves, el;
    var nummoves = 3;

    // debug code remove later
    var nconject = conjectures.length;
    csgeo.free.forEach(function(el) {
        jj = nummoves;
        while (jj--) {
            //if (el.kind === "C") debugger; // no conic movement currently
            if (el.pinned) {
                if (debug) console.log("element ", el.name, "is pinned");
                break;
            }
            if (debug) console.log("prover: moving element", el.name);
            moves = geoOps[el.type].getRandomMove(el);
            // moves are arrays which can have different type: homog, radius etc ...
            moves.forEach(function(newpos) {
                //if(el.type === "PointOnCircle") debugger;
                movepointscr(el, newpos.value, newpos.type);
            });
            // check if conjecture still holds
            conjectures = conjectures.filter(function(con) {
                return con.holds();
            });
        }
    });

    if (debug) {
        console.log("dropped ", nconject - conjectures.length, " conjectures");
    }

    if (!debug) restoreGeo();

    for (var i = 0; i < conjectures.length; ++i) {
        conjectures[i].apply();
    }
    conjectures = [];
    if (debug) {
        csgeo.gslp.forEach(function(el) {
            console.log(el.name, el.incidences);
        });
    }
}
<commit_msg>point on line<commit_after>var conjectures = [];

function guessIncidences(el) {
    if (guessIncidences.hasOwnProperty(el.kind))
        guessIncidences[el.kind](el);
}

guessIncidences.P = function(p) {
    csgeo.lines.forEach(function(l) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
    csgeo.conics.forEach(function(c) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.L = function(l) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.S = guessIncidences.L;

guessIncidences.C = function(c) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

function applyIncidence(a, b) {
    return function() {
        a.incidences.push(b.name);
        b.incidences.push(a.name);
    };
}

function incidentPL(p, l) {
    return {
        toString: function() {
            return "point " + p.name + " incident line " + l.name;
        },
        apply: applyIncidence(p, l),
        holds: function() {
            var pn = List.scaldiv(List.abs(p.homog), p.homog);
            var ln = List.scaldiv(List.abs(l.homog), l.homog);
            var prod = CSNumber.abs(List.scalproduct(pn, ln));
            return (prod.value.real < 0.0000000000001);
        }
    };
}

function incidentPC(p, c) {
    return {
        toString: function() {
            return "point " + p.name + " incident conic " + c.name;
        },
        apply: applyIncidence(p, c),
        holds: function() {
            var erg = General.mult(c.matrix, p.homog);
            erg = General.mult(p.homog, erg);
            erg = CSNumber.abs(erg);
            return (erg.value.real < 0.0000000000001);
        }
    };
}

function checkConjectures() {
    var debug = true;
    if(debug) console.log("conjectures", conjectures.length);
    if(!debug) if (conjectures.length === 0) return;
    //    debugger;
    backupGeo();
    // TODO: we need some randomized proving here:
    // move free elements and check conjectures a number of times.
    // For now assume that all conjectures could be verified.

    var ii, jj, kk;
    var free = csgeo.free;
    var moves, el;
    var nummoves = 3;

    // debug code remove later
    var nconject = conjectures.length;
    csgeo.free.forEach(function(el) {
        jj = nummoves;
        while (jj--) {
            //if (el.kind === "C") debugger; // no conic movement currently
            if (el.pinned) {
                if (debug) console.log("element ", el.name, "is pinned");
                break;
            }
            if (debug) console.log("prover: moving element", el.name);
            moves = geoOps[el.type].getRandomMove(el);
            // moves are arrays which can have different type: homog, radius etc ...
            moves.forEach(function(newpos) {
                //if(el.type === "PointOnLine")
                movepointscr(el, newpos.value, newpos.type);
            });
            // check if conjecture still holds
            conjectures = conjectures.filter(function(con) {
                return con.holds();
            });
        }
    });

    if (debug) {
        console.log("dropped ", nconject - conjectures.length, " conjectures");
    }

    if (!debug) restoreGeo();

    for (var i = 0; i < conjectures.length; ++i) {
        conjectures[i].apply();
    }
    conjectures = [];
    if (debug) {
        csgeo.gslp.forEach(function(el) {
            console.log(el.name, el.incidences);
        });
    }
}
<|endoftext|>