<commit_before>/*
               ______                           ______  ____
              / ____/________  __  ______  ____/ / __ \/ __ )
             / / __/ ___/ __ \/ / / / __ \/ __  / / / / __  |
            / /_/ / /  / /_/ / /_/ / / / / /_/ / /_/ / /_/ /
            \____/_/   \____/\__,_/_/ /_/\__,_/_____/_____/

GroundDB is a thin layer providing Meteor offline database and methods

Concept, localstorage is simple wide spread but slow

GroundDB saves outstanding methods and minimongo into localstorage at window
unload, but can be configured to save at any changes and at certain interval(ms)

When the app loads GroundDB resumes methods and database changes

Regz. RaiX

*/

/* global Ground: true */
/* global EventEmitter: false */  // raix:eventemitter */
/* global Kernel: false */        // dispatch:kernel */
/* global LocalForage: false */   // raix:localforeage

//////////////////////////////// GROUND DATABASE ///////////////////////////////
Ground = {};

// Global helper for applying grounddb on a collection
Ground.Collection = class GroundCollection extends Mongo.Collection {

  constructor(name, {
    // Ground db options
    version=1.0,
    conflictHandler=UpdateLogic,
    // Default Mongo.Collection options
    connection=undefined,
    idGeneration='STRING',
    transform=undefined,
    _driver=undefined,
    _preventAutopublish=true // Mongo.Collection default is false
  } = {}) {

    if (name !== ''+name || name === '') {
      throw new Meteor.Error('missing-name', 'Ground.Collection requires a collection name');
    }

    super(name, { connection, idGeneration, transform, _driver, _preventAutopublish });

    // Rig an event handler on Meteor.Collection
    this.eventemitter = new EventState();

    // Count for pending write operations
    this.pendingWrites = new ProgressCount();

    // Count for pending read operations
    this.pendingReads = new ProgressCount();

    // Carry last updated at if supported by schema
    this.lastUpdatedAt = null;

    // Is this an offline client only database?
    this.offlineDatabase = (connection === null);

    this.isLoaded = false;

    // Create scoped storage
    this.storage = new LocalForage({
      name: name,
      version: 1.0 // options.version
    });

    // Overwrite default logic on connection
    if (this._connection) {
      // Instanciate update logic
      let updateLogic = new conflictHandler(this);

      this._connection._stores[ this._name ].update = (ddp) => {
        var mongoId = ddp.id && MongoID.idParse(ddp.id);
        var doc = ddp.id && this._collection.findOne(mongoId);

        // remove _id from document
        if (doc) delete doc._id;

        if (ddp.msg === 'replace') {
          if (ddp.replace) {
            if (doc) {
              let fields = DiffSequence.makeChangedFields(ddp.replace, doc);
              delete fields._id;
              updateLogic.changed(mongoId, fields, doc);
            } else {
              updateLogic.added(mongoId, ddp.replace);
            }
          } else {
            updateLogic.removed(mongoId, doc);
          }
        } else if (ddp.msg === 'added') {
          if (doc) {
            let fields = DiffSequence.makeChangedFields(ddp.fields, doc);
            delete fields._id;
            updateLogic.changed(mongoId, fields, doc);
          } else {
            updateLogic.added(mongoId, ddp.fields);
          }
        } else if (ddp.msg === 'changed') {
          if (doc) {
            // let fields = DiffSequence.makeChangedFields(ddp.fields, doc);
            updateLogic.changed(mongoId, ddp.fields, doc);
          } else {
            updateLogic.added(mongoId, ddp.fields);
          }
        } else if (ddp.msg === 'removed') {
          updateLogic.removed(mongoId, doc);
        }
      };

    } // EO Connection update overwrite

    // Auto store updates locally
    this.monitorChanges();

    // Load database from local storage
    this.loadDatabase();
  }

  loadDatabase() {
    // Then load the docs into minimongo
    this.pendingReads.inc();
    this.storage
      .ready(() => {

        this.storage
          .length()
          .then(len => {
            if (len === 0) {
              this.pendingReads.dec();
              Kernel.defer(() => {
                console.log('LOADED');
                this.isLoaded = true;
                this.emitState('loaded', { count: len });
              });
            } else {
              // Update progress
              this.pendingReads.inc(len);
              // Count handled documents
              let handled = 0;
              this.storage
                .iterate((doc, id) => {

                  Kernel.defer(() => {

                    // Add the document to minimongo
                    this._collection._docs._map[id] = doc;

                    // Update progress
                    this.pendingReads.dec();

                    // Check if all documetns have been handled
                    if (++handled === len) {
                      this.invalidate();
                      Kernel.defer(() => {
                        console.log('LOADED');
                        this.isLoaded = true;
                        this.emitState('loaded', { count: len });
                      });
                    }
                  });

                })
                .then(() => {
                  this.pendingReads.dec();
                });
            }

          });
      });
  }

  saveDocument(doc, remove) {
    if (this.isLoaded) {
      this.pendingWrites.inc();

      this.storage
        .ready(() => {

          if (remove) {
            this.storage
              .removeItem(doc._id)
              .then(() => {
                this.pendingWrites.dec();
              });
          } else {
            this.storage
              .setItem(doc._id, doc)
              .then(() => {
                this.pendingWrites.dec();
              });
          }

        });

    }
    // xxx: should we buffer changes?
  }

  getLastUpdated(doc) {
    var result = null;

    if (doc.updatedAt || doc.createdAt || doc.removedAt) {
      result = new Date(Math.max(doc.updatedAt || null, doc.createdAt || null, doc.removedAt || null));
    }

    return result;
  }

  setLastUpdated(lastUpdatedAt) {
    if (lastUpdatedAt) {
      if (this.lastUpdatedAt < lastUpdatedAt || !this.lastUpdatedAt) {
        this.lastUpdatedAt = lastUpdatedAt || null;
      }
    }
  }

  monitorChanges() {
    // Store documents to localforage
    this.find().observe({
      'added': doc => {
        this.setLastUpdated(this.getLastUpdated(doc));
        this.saveDocument(doc);
      },
      // If removedAt is set this means the document should be removed
      'changed': (doc, oldDoc) => {
        this.setLastUpdated(this.getLastUpdated(doc));

        if (this.lastUpdatedAt) {
          if (doc.removedAt && !oldDoc.removedAt) {
            // Remove the document completely
            this._collection.remove(doc._id);
            this.saveDocument(doc, true);
          } else {
            this.saveDocument(doc);
          }
        } else {
          this.saveDocument(doc);
        }
      },
      // If lastUpdated is supported by schema we should not use removed
      // any more - rather catch this in the changed event...
      'removed': doc => {
        if (!this.lastUpdatedAt) {
          this.saveDocument(doc, true); }
        }
    });
  }

  shutdown(callback) {
    // xxx: have a better lock / fence
    this.writeFence = true;

    return new Promise(resolve => {
      Tracker.autorun(c => {
        // Wait until all writes have been done
        if (this.pendingWrites.isDone()) {
          c.stop();

          if (typeof callback === 'function') callback();
          resolve();
        }
      });
    });
  }

  invalidate() {
    Object.keys(this._collection.queries)
      .forEach(key => {
        // this._collection.queries[key].changed();
      });
  }

  clear() {
    this.storage.clear();
    //this._collection.remove({}, { multi: true });
    this._collection._docs._map = {};
    this.invalidate();
  }
  //////////////////////////////////////////////////////////////////////////////
  // WRAP EVENTEMITTER API on prototype
  //////////////////////////////////////////////////////////////////////////////

  // Wrap the Event Emitter Api "on"
  on(/* arguments */) {
    return this.eventemitter.on(...arguments);
  }

  // Wrap the Event Emitter Api "once"
  once(/* arguments */) {
    return this.eventemitter.once(...arguments);
  }

  // Wrap the Event Emitter Api "off"
  off(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  // Wrap the Event Emitter Api "emit"
  emit(/* arguments */) {
    return this.eventemitter.emit(...arguments);
  }

  // Wrap the Event Emitter Api "emit"
  emitState(/* arguments */) {
    return this.eventemitter.emitState(...arguments);
  }

  // // Add api helpers
  addListener(/* arguments */) {
    return this.eventemitter.on(...arguments);
  }

  removeListener(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  removeAllListeners(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  // // Add jquery like helpers
  one(/* arguments */) {
    return this.eventemitter.once(...arguments);
  }

  trigger(/* arguments */) {
    return this.eventemitter.emit(...arguments);
  }

};

/**
 * Default update logic - for conflict handling "server-win"
 *
 * This class can be used as a base for building custom conflict
 * handlers.
 */
UpdateLogic = class UpdateLogic {

  constructor(collection) {
    this.collection = collection;
  }

  added(id, doc) {
    this.collection._collection.insert(_.extend({ _id: id }, doc));
  }

  changed(id, fields, oldDoc) {
    this.collection._collection.update({ _id: id }, this.modifier(fields));
  }

  removed(id, oldDoc) {
    this.collection._collection.remove({ _id: id });
  }

  modifier(fields) {
    var mod = {};
    _.each(fields, (value, key) => {
      if (value === undefined) {
        if (!mod.$unset)
          mod.$unset = {};
        mod.$unset[key] = 1;
      } else {
        if (!mod.$set)
          mod.$set = {};
        mod.$set[key] = value;
      }
    });

    return mod;
  }
};
<commit_msg>don't update doc with an empty object (no $set)<commit_after>/*
               ______                           ______  ____
              / ____/________  __  ______  ____/ / __ \/ __ )
             / / __/ ___/ __ \/ / / / __ \/ __  / / / / __  |
            / /_/ / /  / /_/ / /_/ / / / / /_/ / /_/ / /_/ /
            \____/_/   \____/\__,_/_/ /_/\__,_/_____/_____/

GroundDB is a thin layer providing Meteor offline database and methods

Concept, localstorage is simple wide spread but slow

GroundDB saves outstanding methods and minimongo into localstorage at window
unload, but can be configured to save at any changes and at certain interval(ms)

When the app loads GroundDB resumes methods and database changes

Regz. RaiX

*/

/* global Ground: true */
/* global EventEmitter: false */  // raix:eventemitter */
/* global Kernel: false */        // dispatch:kernel */
/* global LocalForage: false */   // raix:localforeage

//////////////////////////////// GROUND DATABASE ///////////////////////////////
Ground = {};

// Global helper for applying grounddb on a collection
Ground.Collection = class GroundCollection extends Mongo.Collection {

  constructor(name, {
    // Ground db options
    version=1.0,
    conflictHandler=UpdateLogic,
    // Default Mongo.Collection options
    connection=undefined,
    idGeneration='STRING',
    transform=undefined,
    _driver=undefined,
    _preventAutopublish=true // Mongo.Collection default is false
  } = {}) {

    if (name !== ''+name || name === '') {
      throw new Meteor.Error('missing-name', 'Ground.Collection requires a collection name');
    }

    super(name, { connection, idGeneration, transform, _driver, _preventAutopublish });

    // Rig an event handler on Meteor.Collection
    this.eventemitter = new EventState();

    // Count for pending write operations
    this.pendingWrites = new ProgressCount();

    // Count for pending read operations
    this.pendingReads = new ProgressCount();

    // Carry last updated at if supported by schema
    this.lastUpdatedAt = null;

    // Is this an offline client only database?
    this.offlineDatabase = (connection === null);

    this.isLoaded = false;

    // Create scoped storage
    this.storage = new LocalForage({
      name: name,
      version: 1.0 // options.version
    });

    // Overwrite default logic on connection
    if (this._connection) {
      // Instanciate update logic
      let updateLogic = new conflictHandler(this);

      this._connection._stores[ this._name ].update = (ddp) => {
        var mongoId = ddp.id && MongoID.idParse(ddp.id);
        var doc = ddp.id && this._collection.findOne(mongoId);

        // remove _id from document
        if (doc) delete doc._id;

        if (ddp.msg === 'replace') {
          if (ddp.replace) {
            if (doc) {
              let fields = DiffSequence.makeChangedFields(ddp.replace, doc);
              delete fields._id;
              updateLogic.changed(mongoId, fields, doc);
            } else {
              updateLogic.added(mongoId, ddp.replace);
            }
          } else {
            updateLogic.removed(mongoId, doc);
          }
        } else if (ddp.msg === 'added') {
          if (doc) {
            let fields = DiffSequence.makeChangedFields(ddp.fields, doc);
            delete fields._id;
            updateLogic.changed(mongoId, fields, doc);
          } else {
            updateLogic.added(mongoId, ddp.fields);
          }
        } else if (ddp.msg === 'changed') {
          if (doc) {
            // let fields = DiffSequence.makeChangedFields(ddp.fields, doc);
            updateLogic.changed(mongoId, ddp.fields, doc);
          } else {
            updateLogic.added(mongoId, ddp.fields);
          }
        } else if (ddp.msg === 'removed') {
          updateLogic.removed(mongoId, doc);
        }
      };

    } // EO Connection update overwrite

    // Auto store updates locally
    this.monitorChanges();

    // Load database from local storage
    this.loadDatabase();
  }

  loadDatabase() {
    // Then load the docs into minimongo
    this.pendingReads.inc();
    this.storage
      .ready(() => {

        this.storage
          .length()
          .then(len => {
            if (len === 0) {
              this.pendingReads.dec();
              Kernel.defer(() => {
                console.log('LOADED');
                this.isLoaded = true;
                this.emitState('loaded', { count: len });
              });
            } else {
              // Update progress
              this.pendingReads.inc(len);
              // Count handled documents
              let handled = 0;
              this.storage
                .iterate((doc, id) => {

                  Kernel.defer(() => {

                    // Add the document to minimongo
                    this._collection._docs._map[id] = doc;

                    // Update progress
                    this.pendingReads.dec();

                    // Check if all documetns have been handled
                    if (++handled === len) {
                      this.invalidate();
                      Kernel.defer(() => {
                        console.log('LOADED');
                        this.isLoaded = true;
                        this.emitState('loaded', { count: len });
                      });
                    }
                  });

                })
                .then(() => {
                  this.pendingReads.dec();
                });
            }

          });
      });
  }

  saveDocument(doc, remove) {
    if (this.isLoaded) {
      this.pendingWrites.inc();

      this.storage
        .ready(() => {

          if (remove) {
            this.storage
              .removeItem(doc._id)
              .then(() => {
                this.pendingWrites.dec();
              });
          } else {
            this.storage
              .setItem(doc._id, doc)
              .then(() => {
                this.pendingWrites.dec();
              });
          }

        });

    }
    // xxx: should we buffer changes?
  }

  getLastUpdated(doc) {
    var result = null;

    if (doc.updatedAt || doc.createdAt || doc.removedAt) {
      result = new Date(Math.max(doc.updatedAt || null, doc.createdAt || null, doc.removedAt || null));
    }

    return result;
  }

  setLastUpdated(lastUpdatedAt) {
    if (lastUpdatedAt) {
      if (this.lastUpdatedAt < lastUpdatedAt || !this.lastUpdatedAt) {
        this.lastUpdatedAt = lastUpdatedAt || null;
      }
    }
  }

  monitorChanges() {
    // Store documents to localforage
    this.find().observe({
      'added': doc => {
        this.setLastUpdated(this.getLastUpdated(doc));
        this.saveDocument(doc);
      },
      // If removedAt is set this means the document should be removed
      'changed': (doc, oldDoc) => {
        this.setLastUpdated(this.getLastUpdated(doc));

        if (this.lastUpdatedAt) {
          if (doc.removedAt && !oldDoc.removedAt) {
            // Remove the document completely
            this._collection.remove(doc._id);
            this.saveDocument(doc, true);
          } else {
            this.saveDocument(doc);
          }
        } else {
          this.saveDocument(doc);
        }
      },
      // If lastUpdated is supported by schema we should not use removed
      // any more - rather catch this in the changed event...
      'removed': doc => {
        if (!this.lastUpdatedAt) {
          this.saveDocument(doc, true); }
        }
    });
  }

  shutdown(callback) {
    // xxx: have a better lock / fence
    this.writeFence = true;

    return new Promise(resolve => {
      Tracker.autorun(c => {
        // Wait until all writes have been done
        if (this.pendingWrites.isDone()) {
          c.stop();

          if (typeof callback === 'function') callback();
          resolve();
        }
      });
    });
  }

  invalidate() {
    Object.keys(this._collection.queries)
      .forEach(key => {
        // this._collection.queries[key].changed();
      });
  }

  clear() {
    this.storage.clear();
    //this._collection.remove({}, { multi: true });
    this._collection._docs._map = {};
    this.invalidate();
  }
  //////////////////////////////////////////////////////////////////////////////
  // WRAP EVENTEMITTER API on prototype
  //////////////////////////////////////////////////////////////////////////////

  // Wrap the Event Emitter Api "on"
  on(/* arguments */) {
    return this.eventemitter.on(...arguments);
  }

  // Wrap the Event Emitter Api "once"
  once(/* arguments */) {
    return this.eventemitter.once(...arguments);
  }

  // Wrap the Event Emitter Api "off"
  off(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  // Wrap the Event Emitter Api "emit"
  emit(/* arguments */) {
    return this.eventemitter.emit(...arguments);
  }

  // Wrap the Event Emitter Api "emit"
  emitState(/* arguments */) {
    return this.eventemitter.emitState(...arguments);
  }

  // // Add api helpers
  addListener(/* arguments */) {
    return this.eventemitter.on(...arguments);
  }

  removeListener(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  removeAllListeners(/* arguments */) {
    return this.eventemitter.off(...arguments);
  }

  // // Add jquery like helpers
  one(/* arguments */) {
    return this.eventemitter.once(...arguments);
  }

  trigger(/* arguments */) {
    return this.eventemitter.emit(...arguments);
  }

};

/**
 * Default update logic - for conflict handling "server-win"
 *
 * This class can be used as a base for building custom conflict
 * handlers.
 */
UpdateLogic = class UpdateLogic {

  constructor(collection) {
    this.collection = collection;
  }

  added(id, doc) {
    this.collection._collection.insert(_.extend({ _id: id }, doc));
  }

  changed(id, fields, oldDoc) {
    if (!_.empty(fields)) {
      this.collection._collection.update({ _id: id }, this.modifier(fields));
    }
  }

  removed(id, oldDoc) {
    this.collection._collection.remove({ _id: id });
  }

  modifier(fields) {
    var mod = {};
    _.each(fields, (value, key) => {
      if (value === undefined) {
        if (!mod.$unset)
          mod.$unset = {};
        mod.$unset[key] = 1;
      } else {
        if (!mod.$set)
          mod.$set = {};
        mod.$set[key] = value;
      }
    });

    return mod;
  }
};
<|endoftext|>


<commit_before>module.exports = {
    'en': {
        id: 9,
        abilities: 'Abilities',
        evoLine: 'Evolutionary Line',
        bases: 'Base Stats',
        height: 'Height',
        weight: 'Weight',
        eggs: 'Egg Groups',
        dex: 'Dex Entry (Sun/Moon)',
        resources: 'External Resources'
    },
    'fr': {
        id: 5,
        abilities: 'Talents',
        evoLine: 'Famille d\'évolution',
        bases: 'Statistiques indicatives',
        height: 'Taille',
        weight: 'Poids',
        eggs: 'Groupe œuf',
        dex: 'Descriptions du Pokédex (Soleil/Lune)',
        resources: 'Ressources Extérieur'
    }
}<commit_msg>Added baseline japanese locale for testing<commit_after>module.exports = {
    'en': {
        id: 9,
        abilities: 'Abilities',
        evoLine: 'Evolutionary Line',
        bases: 'Base Stats',
        height: 'Height',
        weight: 'Weight',
        eggs: 'Egg Groups',
        dex: 'Dex Entry (Sun/Moon)',
        resources: 'External Resources'
    },
    'fr': {
        id: 5,
        abilities: 'Talents',
        evoLine: 'Famille d\'évolution',
        bases: 'Statistiques indicatives',
        height: 'Taille',
        weight: 'Poids',
        eggs: 'Groupe œuf',
        dex: 'Descriptions du Pokédex (Soleil/Lune)',
        resources: 'Ressources Extérieur'
    },
    'jp': {
        id: 1,
        abilities: '特性',
        evoLine: '進化',
        bases: '種族値',
        height: 'たかさ',
        weight: 'おもさ',
        eggs: 'タマゴグループ',
        dex: '説明文',
        resources: '対外 出所'
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2019, Sebastian Rath
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const BaseCompiler = require('../base-compiler'),
    argumentParsers = require("./argument-parsers"),
    path = require('path');

class PythonCompiler extends BaseCompiler {

    constructor(compilerInfo, env) {
        super(compilerInfo, env);
        this.compiler.demangler = null;
        this.demanglerClass = null;
    }

    // eslint-disable-next-line no-unused-vars
    processAsm(result, filters) {
        const lineRe = /^\s{0,4}([0-9]+)(.*)/;

        const bytecodeLines = result.asm.split("\n");

        const bytecodeResult = [];
        let lastLineNo = null;
        let sourceLoc = null;

        bytecodeLines.forEach(line => {
            const match = line.match(lineRe);

            if (match) {
                const lineno = parseInt(match[1]);
                sourceLoc = {line: lineno, file: null};
                lastLineNo = lineno;
            } else if (!line) {
                sourceLoc = {line: null, file: null};
                lastLineNo = null;
            } else {
                sourceLoc = {line: lastLineNo, file: null};
            }

            bytecodeResult.push({text: line, source: sourceLoc});
        });

        return bytecodeResult;
    }

    getDisasmScriptPath() {
        const script = this.compilerProps('disasmScript');

        return script || path.resolve(__dirname, '..', '..', 'etc', 'scripts', 'dis_all.py');
    }

    optionsForFilter(filters, outputFilename) {
        return ['-I',
            this.getDisasmScriptPath(),
            '--outputfile',
            outputFilename,
            '--inputfile'];
    }

    getArgumentParser() {
        return argumentParsers.Base;
    }
}

module.exports = PythonCompiler;
<commit_msg>Fix python compiler implementation<commit_after>// Copyright (c) 2019, Sebastian Rath
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const BaseCompiler = require('../base-compiler'),
    argumentParsers = require("./argument-parsers"),
    path = require('path');

class PythonCompiler extends BaseCompiler {

    constructor(compilerInfo, env) {
        super(compilerInfo, env);
        this.compiler.demangler = null;
        this.demanglerClass = null;
    }

    // eslint-disable-next-line no-unused-vars
    processAsm(result, filters) {
        const lineRe = /^\s{0,4}([0-9]+)(.*)/;

        const bytecodeLines = result.asm.split("\n");

        const bytecodeResult = [];
        let lastLineNo = null;
        let sourceLoc = null;

        bytecodeLines.forEach(line => {
            const match = line.match(lineRe);

            if (match) {
                const lineno = parseInt(match[1]);
                sourceLoc = {line: lineno, file: null};
                lastLineNo = lineno;
            } else if (!line) {
                sourceLoc = {line: null, file: null};
                lastLineNo = null;
            } else {
                sourceLoc = {line: lastLineNo, file: null};
            }

            bytecodeResult.push({text: line, source: sourceLoc});
        });

        return {asm: bytecodeResult};
    }

    getDisasmScriptPath() {
        const script = this.compilerProps('disasmScript');

        return script || path.resolve(__dirname, '..', '..', 'etc', 'scripts', 'dis_all.py');
    }

    optionsForFilter(filters, outputFilename) {
        return ['-I',
            this.getDisasmScriptPath(),
            '--outputfile',
            outputFilename,
            '--inputfile'];
    }

    getArgumentParser() {
        return argumentParsers.Base;
    }
}

module.exports = PythonCompiler;
<|endoftext|>


<commit_before>
/*!
 * Connect - DynamoDB
 * Copyright(c) 2012 Mike Carson <ca98am79@gmail.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var dynode = require('dynode');

/**
 * One day in seconds.
 */

var oneDay = 86400;

/**
 * Return the `DynamoDBStore` extending `connect`'s session Store.
 *
 * @param {object} connect
 * @return {Function}
 * @api public
 */

module.exports = function(connect){

    /**
   * Connect's Store.
   */

    var Store = connect.session.Store;

    /**
   * Initialize DynamoDBStore with the given `options`.
   *
   * @param {Object} options
   * @api public
   */

    function DynamoDBStore(options) {
        options = options || {};
        Store.call(this, options);
        this.prefix = null == options.prefix
        ? 'sess:'
        : options.prefix;

        this.client = options.client || new (dynode.Client)({
            https: true,
            accessKeyId: options.accessKeyId,
            secretAccessKey: options.secretAccessKey
        });
        this.table = options.table || 'sessions';
        this.reapInterval = options.reapInterval || (10 * 60 * 1000);
        if (this.reapInterval > 0) {
            this._reap = setInterval(this.reap.bind(this), this.reapInterval);
        }
    };

    /**
   * Inherit from `Store`.
   */

    DynamoDBStore.prototype.__proto__ = Store.prototype;

    /**
   * Attempt to fetch session by the given `sid`.
   *
   * @param {String} sid
   * @param {Function} fn
   * @api public
   */

    DynamoDBStore.prototype.get = function(sid, fn){
        sid = this.prefix + sid;
        var now = +new Date;
        this.client.getItem(this.table, sid, function(err, data){
            try {
                if (!data) return fn(null, null);
                else if (data.expires && now >= data.expires) {
                    fn(null, null);
                } else {
                    var sess = data.sess.toString();
                    sess = JSON.parse(sess);
                    fn(null, sess);
                }
            } catch (err) {
                fn(err);
            }
        }.bind(this));
    };

    /**
   * Commit the given `sess` object associated with the given `sid`.
   *
   * @param {String} sid
   * @param {Session} sess
   * @param {Function} fn
   * @api public
   */

    DynamoDBStore.prototype.set = function(sid, sess, fn){
        sid = this.prefix + sid;
        try {
            this.client.getItem(this.table, sid, function(err, data){
                var expires = typeof sess.cookie.maxAge === 'number'
                ? (+new Date()) + sess.cookie.maxAge
                : (+new Date()) + oneDay;
                sess = JSON.stringify(sess);
                if (err) {
                    data = {
                        _id: sid,
                        expires: expires,
                        type: 'connect-session',
                        sess: sess
                    };
                    this.client.putItem(this.table, data, fn);
                } else {
                    if (data) {
                        data.expires = expires;
                        data.sess = sess;
                        delete data._id;
                        this.client.updateItem(this.table, sid, data, fn);
                    } else {
                        data = {
                            _id: sid,
                            expires: expires,
                            type: 'connect-session',
                            sess: sess
                        };
                        this.client.putItem(this.table, data, fn);
                    }
                }
            }.bind(this));
        } catch (err) {
            fn && fn(err);
        }
    };

    /**
   * Cleans up expired sessions
   *
   * @api public
   */
    DynamoDBStore.prototype.reap = function (fn) {
        var now = +new Date;
        var options = {
            endkey: '[' + now + ',{}]'
        };
        var opts = {
            ScanFilter : {
                "expires":{
                    "AttributeValueList":[{
                        "N":now.toString()
                        }],
                    "ComparisonOperator":"LT"
                }
            },
        AttributesToGet : ["_id"]
    };
    this.client.scan(this.table, opts, function (err, data) {
        if (err) return fn && fn(err);
        destroy.call(this, data, fn);
    }.bind(this));
};

function destroy(data, fn) {
    var self = this;
    function destroyDataAt(index) {
        if (index === data.length) {
            return fn && fn();
        } else {
            var sid = data[index]._id;
            sid = sid.substring(self.prefix.length, sid.length);
            self.destroy(sid, function() {
                destroyDataAt(index+1);
            });
        }
    }
    destroyDataAt(0);
}

/**
   * Destroy the session associated with the given `sid`.
   *
   * @param {String} sid
   * @api public
   */
DynamoDBStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.deleteItem(this.table, sid, fn || function(){});
};

/**
   * Clear intervals
   *
   * @param {String} sid
   * @api public
   */
DynamoDBStore.prototype.clearInterval = function () {
    if (this._reap) clearInterval(this._reap);
};

return DynamoDBStore;
};<commit_msg>add check to see if sessions table exists, if not it creates it<commit_after>
/*!
 * Connect - DynamoDB
 * Copyright(c) 2012 Mike Carson <ca98am79@gmail.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var dynode = require('dynode');

/**
 * One day in seconds.
 */

var oneDay = 86400;

/**
 * Return the `DynamoDBStore` extending `connect`'s session Store.
 *
 * @param {object} connect
 * @return {Function}
 * @api public
 */

module.exports = function(connect){

    /**
   * Connect's Store.
   */

    var Store = connect.session.Store;

    /**
   * Initialize DynamoDBStore with the given `options`.
   *
   * @param {Object} options
   * @api public
   */

    function DynamoDBStore(options) {
        options = options || {};
        Store.call(this, options);
        this.prefix = null == options.prefix
        ? 'sess:'
        : options.prefix;

        this.client = options.client || new (dynode.Client)({
            https: true,
            accessKeyId: options.accessKeyId,
            secretAccessKey: options.secretAccessKey
        });

        this.table = options.table || 'sessions';
        this.reapInterval = options.reapInterval || (10 * 60 * 1000);
        if (this.reapInterval > 0) {
            this._reap = setInterval(this.reap.bind(this), this.reapInterval);
        }

        // check if table exists, otherwise create it
        dynode.describeTable(options.table, function (error, info) {
        	if (error) {
        		dynode.createTable(options.table, console.log);
        	}
        });
    };

    /**
   * Inherit from `Store`.
   */

    DynamoDBStore.prototype.__proto__ = Store.prototype;

    /**
   * Attempt to fetch session by the given `sid`.
   *
   * @param {String} sid
   * @param {Function} fn
   * @api public
   */

    DynamoDBStore.prototype.get = function(sid, fn){
        sid = this.prefix + sid;
        var now = +new Date;
        this.client.getItem(this.table, sid, function(err, data){
            try {
                if (!data) return fn(null, null);
                else if (data.expires && now >= data.expires) {
                    fn(null, null);
                } else {
                    var sess = data.sess.toString();
                    sess = JSON.parse(sess);
                    fn(null, sess);
                }
            } catch (err) {
                fn(err);
            }
        }.bind(this));
    };

    /**
   * Commit the given `sess` object associated with the given `sid`.
   *
   * @param {String} sid
   * @param {Session} sess
   * @param {Function} fn
   * @api public
   */

    DynamoDBStore.prototype.set = function(sid, sess, fn){
        sid = this.prefix + sid;
        try {
            this.client.getItem(this.table, sid, function(err, data){
                var expires = typeof sess.cookie.maxAge === 'number'
                ? (+new Date()) + sess.cookie.maxAge
                : (+new Date()) + oneDay;
                sess = JSON.stringify(sess);
                if (err) {
                    data = {
                        id: sid,
                        expires: expires,
                        type: 'connect-session',
                        sess: sess
                    };
                    this.client.putItem(this.table, data, fn);
                } else {
                    if (data) {
                        data.expires = expires;
                        data.sess = sess;
                        delete data.id;
                        this.client.updateItem(this.table, sid, data, fn);
                    } else {
                        data = {
                            id: sid,
                            expires: expires,
                            type: 'connect-session',
                            sess: sess
                        };
                        this.client.putItem(this.table, data, fn);
                    }
                }
            }.bind(this));
        } catch (err) {
            fn && fn(err);
        }
    };

    /**
   * Cleans up expired sessions
   *
   * @api public
   */
    DynamoDBStore.prototype.reap = function (fn) {
        var now = +new Date;
        var options = {
            endkey: '[' + now + ',{}]'
        };
        var opts = {
            ScanFilter : {
                "expires":{
                    "AttributeValueList":[{
                        "N":now.toString()
                        }],
                    "ComparisonOperator":"LT"
                }
            },
        AttributesToGet : ["id"]
    };
    this.client.scan(this.table, opts, function (err, data) {
        if (err) return fn && fn(err);
        destroy.call(this, data, fn);
    }.bind(this));
};

function destroy(data, fn) {
    var self = this;
    function destroyDataAt(index) {
        if (index === data.length) {
            return fn && fn();
        } else {
            var sid = data[index].id;
            sid = sid.substring(self.prefix.length, sid.length);
            self.destroy(sid, function() {
                destroyDataAt(index+1);
            });
        }
    }
    destroyDataAt(0);
}

/**
   * Destroy the session associated with the given `sid`.
   *
   * @param {String} sid
   * @api public
   */
DynamoDBStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.deleteItem(this.table, sid, fn || function(){});
};

/**
   * Clear intervals
   *
   * @param {String} sid
   * @api public
   */
DynamoDBStore.prototype.clearInterval = function () {
    if (this._reap) clearInterval(this._reap);
};

return DynamoDBStore;
};<|endoftext|>


<commit_before>module.exports = {
    handler: {
        serverError: (req, res, override, err) => {
            console.error('-------');
            console.error('[ERROR]');
            console.error('-------');
            console.error(err);
            console.error('-------');

            if (override) {
                override({
                    raw: {
                        req: req,
                        res: res
                    }
                })
            }
            else {
                res.status(500).send('An error has occurred.')
            }
        }
    },
    delegate: (config, req, res, session) => {
        var controller = {
            raw: {
                req: req,
                res: res
            },
            model: config.model,
            session: {
                set: (key, val, ttl) => {
                    return session.set(req, res, key, val, ttl);
                },
                get: (key, ttl) => {
                    return session.get(req, res, key, ttl);
                },
                del: (key) => {
                    return session.del(req, res, key);
                },
                ttl: (key) => {
                    return session.ttl(req, res, key);
                },
                expire: (key, ttl) => {
                    return session.expire(req, res, key, ttl);
                }
            },
            params: (key) => {
                if (req.method == 'GET') {
                    return req.query[key]
                }
                else {
                    return req.body[key]
                }
            },
            headers: (key) => {
                return req.get(key)
            },
            redirect: (url, statusCode) => {
                if (statusCode) {
                    res.redirect(url, statusCode)
                }
                else {
                    res.redirect(url)
                }
            },
            render: (view, params) => {
                var renderString = await(config.view.render(req, res, view, params));
                controller.finish(renderString);
            },
            finish: (body) => {
                controller.finishWithCode(200, body)
            },
            finisher: {
                notfound: function(body) {
                    controller.finishWithCode(404, body)
                },
                invalid: function(body) {
                    controller.finishWithCode(400, body)
                },
                error: function(body) {
                    controller.finishWithCode(500, body)
                }
            },
            finishWithCode: (code, body) => {
                if (!body) {
                    if (code == 404) {
                        body = 'Page not found.'
                    }
                    else if (code == 403) {
                        body = 'Forbidden.'
                    }
                    else if (code == 400) {
                        body = 'Invalid Request.'
                    }
                    else if (500 <= code < 600) {
                        body = 'An error has occurred.'
                    }
                }

                res.status(code).send(body)
            }
        }

        return controller;
    }
}
<commit_msg>url parameter getter.<commit_after>module.exports = {
    handler: {
        serverError: (req, res, override, err) => {
            console.error('-------');
            console.error('[ERROR]');
            console.error('-------');
            console.error(err);
            console.error('-------');

            if (override) {
                override({
                    raw: {
                        req: req,
                        res: res
                    }
                })
            }
            else {
                res.status(500).send('An error has occurred.')
            }
        }
    },
    delegate: (config, req, res, session) => {
        var controller = {
            raw: {
                req: req,
                res: res
            },
            model: config.model,
            session: {
                set: (key, val, ttl) => {
                    return session.set(req, res, key, val, ttl);
                },
                get: (key, ttl) => {
                    return session.get(req, res, key, ttl);
                },
                del: (key) => {
                    return session.del(req, res, key);
                },
                ttl: (key) => {
                    return session.ttl(req, res, key);
                },
                expire: (key, ttl) => {
                    return session.expire(req, res, key, ttl);
                }
            },
            params: (key, url) => {
                if (url) {
                    return req.params[key];
                }

                if (req.method == 'GET') {
                    return req.query[key]
                }
                else {
                    return req.body[key]
                }
            },
            headers: (key) => {
                return req.get(key)
            },
            redirect: (url, statusCode) => {
                if (statusCode) {
                    res.redirect(url, statusCode)
                }
                else {
                    res.redirect(url)
                }
            },
            render: (view, params) => {
                var renderString = await(config.view.render(req, res, view, params));
                controller.finish(renderString);
            },
            finish: (body) => {
                controller.finishWithCode(200, body)
            },
            finisher: {
                notfound: function(body) {
                    controller.finishWithCode(404, body)
                },
                invalid: function(body) {
                    controller.finishWithCode(400, body)
                },
                error: function(body) {
                    controller.finishWithCode(500, body)
                }
            },
            finishWithCode: (code, body) => {
                if (!body) {
                    if (code == 404) {
                        body = 'Page not found.'
                    }
                    else if (code == 403) {
                        body = 'Forbidden.'
                    }
                    else if (code == 400) {
                        body = 'Invalid Request.'
                    }
                    else if (500 <= code < 600) {
                        body = 'An error has occurred.'
                    }
                }

                res.status(code).send(body)
            }
        }

        return controller;
    }
}
<|endoftext|>


<commit_before>module.exports = function(models) {

  this.login = function(req, res, next) {
    models.User.findByUsernameAndPassword(req.body.user.username, req.body.user.password, function(err, user) {
      if (err) next(err);
      req.session.user = user;
      console.log(req.session.user);
// TODO notify
//        req.flash();
      //res.redirect('home');
    });
  };

  this.logout = function(req, res, next) {
    req.session.destroy(function() {
//      res.redirect('home');
      res.redirect(req.header('Referer'));
    });
  };

  return this;

}.bind({});

<commit_msg>remove console.log<commit_after>module.exports = function(models) {

  this.login = function(req, res, next) {
    models.User.findByUsernameAndPassword(req.body.user.username, req.body.user.password, function(err, user) {
      if (err) next(err);
      req.session.user = user;
// TODO notify
//        req.flash();
      //res.redirect('home');
      res.redirect(req.header('Referer'));
    });
  };

  this.logout = function(req, res, next) {
    req.session.destroy(function() {
//      res.redirect('home');
      res.redirect(req.header('Referer'));
    });
  };

  return this;

}.bind({});

<|endoftext|>


<commit_before>
'use strict';

var auth = require('basic-auth');

// Loads the controller
//
// @app   {Object}    The config
//
function main (config) {

  return {

    isAuth: function(req, res, next) {

      if(!config.auth) {
        return next();
      }

      var user = auth(req);

      if(
        config.auth &&
        user &&
        config.auth.username === user.name &&
        config.auth.password === user.pass
      ) {
        return next();
      }

      res.json(500, { message: 'Permission Denied' });
    }

  };

}

module.exports = main;<commit_msg>Use statusCode 403 for Permission Denied<commit_after>'use strict';

var auth = require('basic-auth');

// Loads the controller
//
// @app   {Object}    The config
//
function main (config) {

  return {

    isAuth: function(req, res, next) {

      if(!config.auth) {
        return next();
      }

      var user = auth(req);

      if(
        config.auth &&
        user &&
        config.auth.username === user.name &&
        config.auth.password === user.pass
      ) {
        return next();
      }

      res.json(403, { message: 'Permission Denied' });
    }

  };

}

module.exports = main;
<|endoftext|>


<commit_before>/*
 * MotionGuidePlugin
 * Visit http://createjs.com/ for documentation, updates and examples.
 *
 * Copyright (c) 2010 gskinner.com, inc.
 *
 * 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.
 */

/**
 * @module TweenJS
 */

// namespace:
this.createjs = this.createjs||{};

(function() {
	"use strict";

	/**
	 * A TweenJS plugin for working with motion guides.
	 *
	 * To use, install the plugin after TweenJS has loaded. Next tween the 'guide' property with an object as detailed below.
	 *
	 *       createjs.MotionGuidePlugin.install();
	 *
	 *
Example

	 *
	 *      // Using a Motion Guide
	 *	    createjs.Tween.get(target).to({guide:{ path:[0,0, 0,200,200,200, 200,0,0,0] }},7000);
	 *	    // Visualizing the line
	 *	    graphics.moveTo(0,0).curveTo(0,200,200,200).curveTo(200,0,0,0);
	 *
	 * Each path needs pre-computation to ensure there's fast performance. Because of the pre-computation there's no
	 * built in support for path changes mid tween. These are the Guide Object's properties:

	 *
 path: Required, Array : The x/y points used to draw the path with a moveTo and 1 to n curveTo calls.

	 *
 start: Optional, 0-1 : Initial position, default 0 except for when continuing along the same path.

	 *
 end: Optional, 0-1 : Final position, default 1 if not specified.

	 *
 orient: Optional, string : "fixed"/"auto"/"cw"/"ccw"

	 *
"fixed" forces the object to face down the path all movement (relative to start rotation),

	 *
"auto" rotates the object along the path relative to the line.

	 *
"cw"/"ccw" force clockwise or counter clockwise rotations including Adobe Flash/Animate-like
	 *      		behaviour

	 *

	 *

	 * Guide objects should not be shared between tweens even if all properties are identical, the library stores
	 * information on these objects in the background and sharing them can cause unexpected behaviour. Values
	 * outside 0-1 range of tweens will be a "best guess" from the appropriate part of the defined curve.
	 *
	 * @class MotionGuidePlugin
	 * @constructor
	 **/
	function MotionGuidePlugin() {
		throw("MotionGuidePlugin cannot be instantiated.")
	};

// static properties:
	/**
	 * @property priority
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.priority = 0; // high priority, should run sooner

	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotOffS;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotOffE;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotNormS;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotNormE;

// static methods
	/**
	 * Installs this plugin for use with TweenJS. Call this once after TweenJS is loaded to enable this plugin.
	 * @method install
	 * @static
	 **/
	MotionGuidePlugin.install = function() {
		createjs.Tween.installPlugin(MotionGuidePlugin, ["guide", "x", "y", "rotation"]);
		return createjs.Tween.IGNORE;
	};

	/**
	 * @method init
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.init = function(tween, prop, value) {
		var target = tween.target;
		if(!target.hasOwnProperty("x")){ target.x = 0; }
		if(!target.hasOwnProperty("y")){ target.y = 0; }
		if(!target.hasOwnProperty("rotation")){ target.rotation = 0; }

		if(prop=="rotation"){ tween.__needsRot = true; }
		return prop=="guide"?null:value;
	};

	/**
	 * @method step
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.step = function(tween, prop, startValue, endValue, injectProps) {
		// other props
		if(prop == "rotation"){
			tween.__rotGlobalS = startValue;
			tween.__rotGlobalE = endValue;
			MotionGuidePlugin.testRotData(tween, injectProps);
		}
		if(prop != "guide"){ return endValue; }

		// guide only information - Start -
		var temp, data = endValue;
		if(!data.hasOwnProperty("path")){ data.path = []; }
		var path = data.path;
		if(!data.hasOwnProperty("end")){ data.end = 1; }
		if(!data.hasOwnProperty("start")){
			data.start = (startValue&&startValue.hasOwnProperty("end")&&startValue.path===path)?startValue.end:0;
		}

		// Figure out subline information
		if(data.hasOwnProperty("_segments") && data._length){ return endValue; }
		var l = path.length;
		var accuracy = 10;		// Adjust to improve line following precision but sacrifice performance (# of seg)
		if(l >= 6 && (l-2) % 4 == 0){	// Enough points && contains correct number per entry ignoring start
			data._segments = [];
			data._length = 0;
			for(var i=2; i<l; i+=4){
				var sx = path[i-2], sy = path[i-1];
				var cx = path[i+0], cy = path[i+1];
				var ex = path[i+2], ey = path[i+3];
				var oldX = sx, oldY = sy;
				var tempX, tempY, total = 0;
				var sublines = [];
				for(var j=1; j<=accuracy; j++){
					var t = j/accuracy;
					var inv = 1 - t;
					tempX = inv*inv * sx + 2 * inv * t * cx + t*t * ex;
					tempY = inv*inv * sy + 2 * inv * t * cy + t*t * ey;
					total += sublines[sublines.push(Math.sqrt((temp=tempX-oldX)*temp + (temp=tempY-oldY)*temp))-1];
					oldX = tempX;
					oldY = tempY;
				}
				data._segments.push(total);
				data._segments.push(sublines);
				data._length += total;
			}
		} else {
			throw("invalid 'path' data, please see documentation for valid paths");
		}

		// Setup x/y tweens
		temp = data.orient;
		data.orient = true;
		var o = {};
		MotionGuidePlugin.calc(data, data.start, o);
		tween.__rotPathS = Number(o.rotation.toFixed(5));
		MotionGuidePlugin.calc(data, data.end, o);
		tween.__rotPathE = Number(o.rotation.toFixed(5));
		data.orient = false;	//here and now we don't know if we need to
		MotionGuidePlugin.calc(data, data.end, injectProps);
		data.orient = temp;

		// Setup rotation properties
		if(!data.orient){ return endValue; }
		tween.__guideData = data;
		MotionGuidePlugin.testRotData(tween, injectProps);
		return endValue;
	};

	/**
	 * @method testRotData
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.testRotData = function(tween, injectProps){

		// no rotation informat? if we need it come back, if we don't use 0 & ensure we have guide data
		if(tween.__rotGlobalS === undefined || tween.__rotGlobalE === undefined){
			if(tween.__needsRot){ return; }
			if(tween._curQueueProps.rotation !== undefined){
				tween.__rotGlobalS = tween.__rotGlobalE = tween._curQueueProps.rotation;
			} else {
				tween.__rotGlobalS = tween.__rotGlobalE = injectProps.rotation = tween.target.rotation || 0;
			}
		}
		if(tween.__guideData === undefined){ return; }

		// Process rotation properties
		var data = tween.__guideData;
		var rotGlobalD = tween.__rotGlobalE - tween.__rotGlobalS;
		var rotPathD = tween.__rotPathE - tween.__rotPathS;
		var rot = rotGlobalD - rotPathD;

		if(data.orient == "auto"){
			if(rot > 180){			rot -= 360; }
			else if(rot < -180){	rot += 360; }

		} else if(data.orient == "cw"){
			while(rot < 0){ rot += 360; }
			if(rot == 0 && rotGlobalD > 0 && rotGlobalD != 180){ rot += 360; }

		} else if(data.orient == "ccw"){
			rot = rotGlobalD - ((rotPathD > 180)?(360-rotPathD):(rotPathD));	// sign flipping on path
			while(rot > 0){ rot -= 360; }
			if(rot == 0 && rotGlobalD < 0 && rotGlobalD != -180){ rot -= 360; }
		}

		data.rotDelta = rot;
		data.rotOffS = tween.__rotGlobalS - tween.__rotPathS;

		// reset
		tween.__rotGlobalS = tween.__rotGlobalE = tween.__guideData = tween.__needsRot = undefined;
	};

	/**
	 * @method tween
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.tween = function(tween, prop, value, startValues, endValues, ratio, wait, end) {
		var data = endValues.guide;
		if(data == undefined || data === startValues.guide){ return value; }
		if(data.lastRatio != ratio){
			// first time through so calculate what I need to
			var t = ((data.end-data.start)*(wait?data.end:ratio)+data.start);
			MotionGuidePlugin.calc(data, t, tween.target);
			switch(data.orient){
				case "cw":		// mix in the original rotation
				case "ccw":
				case "auto": tween.target.rotation += data.rotOffS + data.rotDelta*ratio; break;
				case "fixed":	// follow fixed behaviour to solve potential issues
				default: tween.target.rotation += data.rotOffS; break;
			}
			data.lastRatio = ratio;
		}
		if(prop == "rotation" && ((!data.orient) || data.orient == "false")){ return value; }
		return tween.target[prop];
	};

	/**
	 * Determine the appropriate x/y/rotation information about a path for a given ratio along the path.
	 * Assumes a path object with all optional parameters specified.
	 * @param data Data object you would pass to the "guide:" property in a Tween
	 * @param ratio 0-1 Distance along path, values outside 0-1 are "best guess"
	 * @param target Object to copy the results onto, will use a new object if not supplied.
	 * @return {Object} The target object or a new object w/ the tweened properties
	 * @static
	 */
	MotionGuidePlugin.calc = function(data, ratio, target) {
		if(data._segments == undefined){ throw("Missing critical pre-calculated information, please file a bug"); }
		if(target == undefined){ target = {x:0, y:0, rotation:0}; }
		var seg = data._segments;
		var path = data.path;

		// find segment
		var pos = data._length * ratio;
		var cap = seg.length - 2;
		var n = 0;
		while(pos > seg[n] && n < cap){
			pos -= seg[n];
			n+=2;
		}

		// find subline
		var sublines = seg[n+1];
		var i = 0;
		cap = sublines.length-1;
		while(pos > sublines[i] && i < cap){
			pos -= sublines[i];
			i++;
		}
		var t = (i/++cap)+(pos/(cap*sublines[i]));

		// find x/y
		n = (n*2)+2;
		var inv = 1 - t;
		target.x = inv*inv * path[n-2] + 2 * inv * t * path[n+0] + t*t * path[n+2];
		target.y = inv*inv * path[n-1] + 2 * inv * t * path[n+1] + t*t * path[n+3];

		// orientation
		if(data.orient){
			target.rotation = 57.2957795 * Math.atan2(
				(path[n+1]-path[n-1])*inv + (path[n+3]-path[n+1])*t,
				(path[n+0]-path[n-2])*inv + (path[n+2]-path[n+0])*t);
		}

		return target;
	};

	createjs.MotionGuidePlugin = MotionGuidePlugin;

}());
<commit_msg>Added an error for MotionGuidePlugin until it can be updated.<commit_after>/*
 * MotionGuidePlugin
 * Visit http://createjs.com/ for documentation, updates and examples.
 *
 * Copyright (c) 2010 gskinner.com, inc.
 *
 * 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.
 */

/**
 * @module TweenJS
 */

// namespace:
this.createjs = this.createjs||{};

(function() {
	"use strict";

	/**
	 * A TweenJS plugin for working with motion guides.
	 *
	 * To use, install the plugin after TweenJS has loaded. Next tween the 'guide' property with an object as detailed below.
	 *
	 *       createjs.MotionGuidePlugin.install();
	 *
	 *
Example

	 *
	 *      // Using a Motion Guide
	 *	    createjs.Tween.get(target).to({guide:{ path:[0,0, 0,200,200,200, 200,0,0,0] }},7000);
	 *	    // Visualizing the line
	 *	    graphics.moveTo(0,0).curveTo(0,200,200,200).curveTo(200,0,0,0);
	 *
	 * Each path needs pre-computation to ensure there's fast performance. Because of the pre-computation there's no
	 * built in support for path changes mid tween. These are the Guide Object's properties:

	 *
 path: Required, Array : The x/y points used to draw the path with a moveTo and 1 to n curveTo calls.

	 *
 start: Optional, 0-1 : Initial position, default 0 except for when continuing along the same path.

	 *
 end: Optional, 0-1 : Final position, default 1 if not specified.

	 *
 orient: Optional, string : "fixed"/"auto"/"cw"/"ccw"

	 *
"fixed" forces the object to face down the path all movement (relative to start rotation),

	 *
"auto" rotates the object along the path relative to the line.

	 *
"cw"/"ccw" force clockwise or counter clockwise rotations including Adobe Flash/Animate-like
	 *      		behaviour

	 *

	 *

	 * Guide objects should not be shared between tweens even if all properties are identical, the library stores
	 * information on these objects in the background and sharing them can cause unexpected behaviour. Values
	 * outside 0-1 range of tweens will be a "best guess" from the appropriate part of the defined curve.
	 *
	 * @class MotionGuidePlugin
	 * @constructor
	 **/
	function MotionGuidePlugin() {
		throw("MotionGuidePlugin cannot be instantiated.")
	};

// static properties:
	/**
	 * @property priority
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.priority = 0; // high priority, should run sooner

	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotOffS;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotOffE;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotNormS;
	/**
	 * @property temporary variable storage
	 * @private
	 * @static
	 */
	MotionGuidePlugin._rotNormE;

// static methods
	/**
	 * Installs this plugin for use with TweenJS. Call this once after TweenJS is loaded to enable this plugin.
	 * @method install
	 * @static
	 **/
	MotionGuidePlugin.install = function() {
		throw("MotionGuidePlugin has not been updated to work with the latest TweenJS plugin model yet. Soon!")
		createjs.Tween.installPlugin(MotionGuidePlugin, ["guide", "x", "y", "rotation"]);
		return createjs.Tween.IGNORE;
	};

	/**
	 * @method init
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.init = function(tween, prop, value) {
		var target = tween.target;
		if(!target.hasOwnProperty("x")){ target.x = 0; }
		if(!target.hasOwnProperty("y")){ target.y = 0; }
		if(!target.hasOwnProperty("rotation")){ target.rotation = 0; }

		if(prop=="rotation"){ tween.__needsRot = true; }
		return prop=="guide"?null:value;
	};

	/**
	 * @method step
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.step = function(tween, prop, startValue, endValue, injectProps) {
		// other props
		if(prop == "rotation"){
			tween.__rotGlobalS = startValue;
			tween.__rotGlobalE = endValue;
			MotionGuidePlugin.testRotData(tween, injectProps);
		}
		if(prop != "guide"){ return endValue; }

		// guide only information - Start -
		var temp, data = endValue;
		if(!data.hasOwnProperty("path")){ data.path = []; }
		var path = data.path;
		if(!data.hasOwnProperty("end")){ data.end = 1; }
		if(!data.hasOwnProperty("start")){
			data.start = (startValue&&startValue.hasOwnProperty("end")&&startValue.path===path)?startValue.end:0;
		}

		// Figure out subline information
		if(data.hasOwnProperty("_segments") && data._length){ return endValue; }
		var l = path.length;
		var accuracy = 10;		// Adjust to improve line following precision but sacrifice performance (# of seg)
		if(l >= 6 && (l-2) % 4 == 0){	// Enough points && contains correct number per entry ignoring start
			data._segments = [];
			data._length = 0;
			for(var i=2; i<l; i+=4){
				var sx = path[i-2], sy = path[i-1];
				var cx = path[i+0], cy = path[i+1];
				var ex = path[i+2], ey = path[i+3];
				var oldX = sx, oldY = sy;
				var tempX, tempY, total = 0;
				var sublines = [];
				for(var j=1; j<=accuracy; j++){
					var t = j/accuracy;
					var inv = 1 - t;
					tempX = inv*inv * sx + 2 * inv * t * cx + t*t * ex;
					tempY = inv*inv * sy + 2 * inv * t * cy + t*t * ey;
					total += sublines[sublines.push(Math.sqrt((temp=tempX-oldX)*temp + (temp=tempY-oldY)*temp))-1];
					oldX = tempX;
					oldY = tempY;
				}
				data._segments.push(total);
				data._segments.push(sublines);
				data._length += total;
			}
		} else {
			throw("invalid 'path' data, please see documentation for valid paths");
		}

		// Setup x/y tweens
		temp = data.orient;
		data.orient = true;
		var o = {};
		MotionGuidePlugin.calc(data, data.start, o);
		tween.__rotPathS = Number(o.rotation.toFixed(5));
		MotionGuidePlugin.calc(data, data.end, o);
		tween.__rotPathE = Number(o.rotation.toFixed(5));
		data.orient = false;	//here and now we don't know if we need to
		MotionGuidePlugin.calc(data, data.end, injectProps);
		data.orient = temp;

		// Setup rotation properties
		if(!data.orient){ return endValue; }
		tween.__guideData = data;
		MotionGuidePlugin.testRotData(tween, injectProps);
		return endValue;
	};

	/**
	 * @method testRotData
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.testRotData = function(tween, injectProps){

		// no rotation informat? if we need it come back, if we don't use 0 & ensure we have guide data
		if(tween.__rotGlobalS === undefined || tween.__rotGlobalE === undefined){
			if(tween.__needsRot){ return; }
			if(tween._curQueueProps.rotation !== undefined){
				tween.__rotGlobalS = tween.__rotGlobalE = tween._curQueueProps.rotation;
			} else {
				tween.__rotGlobalS = tween.__rotGlobalE = injectProps.rotation = tween.target.rotation || 0;
			}
		}
		if(tween.__guideData === undefined){ return; }

		// Process rotation properties
		var data = tween.__guideData;
		var rotGlobalD = tween.__rotGlobalE - tween.__rotGlobalS;
		var rotPathD = tween.__rotPathE - tween.__rotPathS;
		var rot = rotGlobalD - rotPathD;

		if(data.orient == "auto"){
			if(rot > 180){			rot -= 360; }
			else if(rot < -180){	rot += 360; }

		} else if(data.orient == "cw"){
			while(rot < 0){ rot += 360; }
			if(rot == 0 && rotGlobalD > 0 && rotGlobalD != 180){ rot += 360; }

		} else if(data.orient == "ccw"){
			rot = rotGlobalD - ((rotPathD > 180)?(360-rotPathD):(rotPathD));	// sign flipping on path
			while(rot > 0){ rot -= 360; }
			if(rot == 0 && rotGlobalD < 0 && rotGlobalD != -180){ rot -= 360; }
		}

		data.rotDelta = rot;
		data.rotOffS = tween.__rotGlobalS - tween.__rotPathS;

		// reset
		tween.__rotGlobalS = tween.__rotGlobalE = tween.__guideData = tween.__needsRot = undefined;
	};

	/**
	 * @method tween
	 * @protected
	 * @static
	 **/
	MotionGuidePlugin.tween = function(tween, prop, value, startValues, endValues, ratio, wait, end) {
		var data = endValues.guide;
		if(data == undefined || data === startValues.guide){ return value; }
		if(data.lastRatio != ratio){
			// first time through so calculate what I need to
			var t = ((data.end-data.start)*(wait?data.end:ratio)+data.start);
			MotionGuidePlugin.calc(data, t, tween.target);
			switch(data.orient){
				case "cw":		// mix in the original rotation
				case "ccw":
				case "auto": tween.target.rotation += data.rotOffS + data.rotDelta*ratio; break;
				case "fixed":	// follow fixed behaviour to solve potential issues
				default: tween.target.rotation += data.rotOffS; break;
			}
			data.lastRatio = ratio;
		}
		if(prop == "rotation" && ((!data.orient) || data.orient == "false")){ return value; }
		return tween.target[prop];
	};

	/**
	 * Determine the appropriate x/y/rotation information about a path for a given ratio along the path.
	 * Assumes a path object with all optional parameters specified.
	 * @param data Data object you would pass to the "guide:" property in a Tween
	 * @param ratio 0-1 Distance along path, values outside 0-1 are "best guess"
	 * @param target Object to copy the results onto, will use a new object if not supplied.
	 * @return {Object} The target object or a new object w/ the tweened properties
	 * @static
	 */
	MotionGuidePlugin.calc = function(data, ratio, target) {
		if(data._segments == undefined){ throw("Missing critical pre-calculated information, please file a bug"); }
		if(target == undefined){ target = {x:0, y:0, rotation:0}; }
		var seg = data._segments;
		var path = data.path;

		// find segment
		var pos = data._length * ratio;
		var cap = seg.length - 2;
		var n = 0;
		while(pos > seg[n] && n < cap){
			pos -= seg[n];
			n+=2;
		}

		// find subline
		var sublines = seg[n+1];
		var i = 0;
		cap = sublines.length-1;
		while(pos > sublines[i] && i < cap){
			pos -= sublines[i];
			i++;
		}
		var t = (i/++cap)+(pos/(cap*sublines[i]));

		// find x/y
		n = (n*2)+2;
		var inv = 1 - t;
		target.x = inv*inv * path[n-2] + 2 * inv * t * path[n+0] + t*t * path[n+2];
		target.y = inv*inv * path[n-1] + 2 * inv * t * path[n+1] + t*t * path[n+3];

		// orientation
		if(data.orient){
			target.rotation = 57.2957795 * Math.atan2(
				(path[n+1]-path[n-1])*inv + (path[n+3]-path[n+1])*t,
				(path[n+0]-path[n-2])*inv + (path[n+2]-path[n+0])*t);
		}

		return target;
	};

	createjs.MotionGuidePlugin = MotionGuidePlugin;

}());
<|endoftext|>


<commit_before>import * as actions from './actions';
import _ from 'lodash';

export default class NetworkTablesWrapper {

  constructor(store) {
    this.store = store;
    this.ntUpdates = {};

    // sets a function that will be called when the websocket connects/disconnects
    NetworkTables.addWsConnectionListener((connected) => {
      this.store.dispatch(actions.ntRobotConnectionChanged(connected));
    }, true);

    // sets a function that will be called when the robot connects/disconnects
    NetworkTables.addRobotConnectionListener((connected) => {
      this.store.dispatch(actions.ntWsConnectionChanged(connected));
    }, true);

    // sets a function that will be called when any NetworkTables key/value changes
    NetworkTables.addGlobalListener((key, value, isNew) => {
      this.ntUpdates[key] = value;
    }, true);

    // Sending NetworkTable updates too quickly causes the dashboard to freeze.
    // Send them in batches every 100ms
    setInterval(() => {
      // Don't dispatch networktables values if currently replaying
      if (!this.isReplaying && !this.isReplayingPaused) {
        this.store.dispatch(actions.ntValueChanged(this.ntUpdates));
        this.ntUpdates = {};
      }
    }, 100);
  }

  get replayState() {
    const state = this.store.getState();
    return state.replay.state;
  }

  get isReplaying() {
    return this.replayState === 'REPLAYING';
  }

  get isReplayingPaused() {
    return this.replayState === 'REPLAYING_PAUSED';
  }

  get isRecording() {
    return this.replayState === 'RECORDING';
  }
}

export function getSubtable(root) {
  let rawValues = dashboard.store.getState().networktables.rawValues;

  let ntKeys = Object.keys(rawValues).filter(key => {
    return key.startsWith(root);
  });

  if (ntKeys.length === 1) {
    return rawValues[ntKeys];
  }
  else {
    let value = _.pick(rawValues, ntKeys);
    return _.mapKeys(value, (value, key) => {
      return key.substring(root.length);
    });
  }
}

export function getType(key) {

  if (!key) {
    return null;
  }

  // Check if this is a camera source
  if (isCameraSource(key)) {
    return 'Camera';
  }

  // Check if value has a primitive or array type
  let value = NetworkTables.getValue(key, null);

  if (_.isArray(value)) {
    return 'array';
  }
  else if (!_.isNull(value)) {
    return typeof value;
  }

  // If it doesn't end with a / then it's not a subtable and it doesn't have a .type
  if (!key.endsWith('/')) {
    return null;
  }

  // Check if value has .type
  let type = NetworkTables.getValue(key + '.type');

  if (type) {
    return type;
  }

  // If there are any keys that start with the passed in key then it's a subtable
  let allKeys = NetworkTables.getKeys();

  for (let i = 0; i < allKeys.length; i++) {
    if (allKeys[i].startsWith(key)) {
      return 'Subtable';
    }
  }

  // Nothing in subtable, so return null
  return null;
}

function isCameraSource(key) {

  if (!key.startsWith('/CameraPublisher')) {
    return false;
  }

  // check if it's an array type
  let value = NetworkTables.getValue(key + 'streams', null);

  return _.isArray(value);
}<commit_msg>Fixed bug where widget table data wasn't being set properly<commit_after>import * as actions from './actions';
import _ from 'lodash';

export default class NetworkTablesWrapper {

  constructor(store) {
    this.store = store;
    this.ntUpdates = {};

    // sets a function that will be called when the websocket connects/disconnects
    NetworkTables.addWsConnectionListener((connected) => {
      this.store.dispatch(actions.ntRobotConnectionChanged(connected));
    }, true);

    // sets a function that will be called when the robot connects/disconnects
    NetworkTables.addRobotConnectionListener((connected) => {
      this.store.dispatch(actions.ntWsConnectionChanged(connected));
    }, true);

    // sets a function that will be called when any NetworkTables key/value changes
    NetworkTables.addGlobalListener((key, value, isNew) => {
      this.ntUpdates[key] = value;
    }, true);

    // Sending NetworkTable updates too quickly causes the dashboard to freeze.
    // Send them in batches every 100ms
    setInterval(() => {
      // Don't dispatch networktables values if currently replaying
      if (!this.isReplaying && !this.isReplayingPaused) {
        this.store.dispatch(actions.ntValueChanged(this.ntUpdates));
        this.ntUpdates = {};
      }
    }, 100);
  }

  get replayState() {
    const state = this.store.getState();
    return state.replay.state;
  }

  get isReplaying() {
    return this.replayState === 'REPLAYING';
  }

  get isReplayingPaused() {
    return this.replayState === 'REPLAYING_PAUSED';
  }

  get isRecording() {
    return this.replayState === 'RECORDING';
  }
}

export function getSubtable(root) {
  let rawValues = dashboard.store.getState().networktables.rawValues;

  let ntKeys = Object.keys(rawValues).filter(key => {
    if (key === root) {
      return true;
    }
    else if (root.endsWith('/')) {
      return key.startsWith(root);
    }
    else {
      return false;
    }
  });

  if (ntKeys.length === 1) {
    return rawValues[ntKeys];
  }
  else {
    let value = _.pick(rawValues, ntKeys);
    return _.mapKeys(value, (value, key) => {
      return key.substring(root.length);
    });
  }
}

export function getType(key) {

  if (!key) {
    return null;
  }

  // Check if this is a camera source
  if (isCameraSource(key)) {
    return 'Camera';
  }

  // Check if value has a primitive or array type
  let value = NetworkTables.getValue(key, null);

  if (_.isArray(value)) {
    return 'array';
  }
  else if (!_.isNull(value)) {
    return typeof value;
  }

  // If it doesn't end with a / then it's not a subtable and it doesn't have a .type
  if (!key.endsWith('/')) {
    return null;
  }

  // Check if value has .type
  let type = NetworkTables.getValue(key + '.type');

  if (type) {
    return type;
  }

  // If there are any keys that start with the passed in key then it's a subtable
  let allKeys = NetworkTables.getKeys();

  for (let i = 0; i < allKeys.length; i++) {
    if (allKeys[i].startsWith(key)) {
      return 'Subtable';
    }
  }

  // Nothing in subtable, so return null
  return null;
}

function isCameraSource(key) {

  if (!key.startsWith('/CameraPublisher')) {
    return false;
  }

  // check if it's an array type
  let value = NetworkTables.getValue(key + 'streams', null);

  return _.isArray(value);
}<|endoftext|>


<commit_before>#!/usr/bin/env node
// TODO : Verifier Self Call functions sans console.log sur linux pb ^M
// TODO : rajouter var() pour les param de type string ou number
/*
 * This file is part of NectarJS
 * Copyright (c) 2017 - 2020 Adrien THIERRY
 * http://nectarjs.com - https://seraum.com/
 *
 * sources : https://github.com/nectarjs/nectarjs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

var VERSION = "0.2.10";
var VALID_COMPILER = ["native", "bc", "qjs"];

global.fs = require('fs');
global.os = require('os');
global.path = require('path');
global.process = require('process');
global.querystring = require('querystring');
global.child_process = require('child_process');
global.execSync = child_process.execSync;

var parseCLI = require('./base/cli/cliParser.js');
var coreHttp = require('./base/util/httpUtils.js');
var getExt = require('./base/util/getExt.js');
var getTips = require('./base/util/getTips.js');
var Flash = require('./base/util/flash.js');
var rmdir = require("./base/util/rmdir.js");
var CURRENT = process.cwd();
var TARGET = require('./base/compiler/target.js');
var PLATFORM = os.platform();
var ARCH = os.arch();

var COMPILER;
var DEFAULT_COMPILER = "native";

var CLI = parseCLI(process.argv);

if(CLI.error)
{
  console.log(CLI.msg);
  return;
}

var ACTION = "build";
if(CLI.cli["--help"] || CLI.cli["-h"]) ACTION = "help";
else if(CLI.cli["--example"] || CLI.cli["--examples"]) ACTION = "example";
else if(CLI.cli["--version"] || CLI.cli["-v"]) ACTION = "version";
else if(CLI.cli["--project"]) ACTION = "showproject";
else if(CLI.cli["--clean"] || CLI.cli["--purge"]) ACTION = "clean";

switch(ACTION)
{
  case "version":
    showVersion();
    break;

  case "help":
    Help();
    break;

  case "example":
    copyExample();
    break;

  case "showproject":
    showProject();
    break;

  case "build":
    Build();
    break;

  case "clean":
    Clean();
    break;

  default:
    Help();
    break;
}

function getExampleFiles (dir, list)
{
    list = list || [];
    var files = fs.readdirSync(dir);
    for (var i in files)
    {
        var name = dir + path.sep + files[i];
        if (fs.statSync(name).isDirectory())
        {
            getExampleFiles(name, list);
        }
        else
        {
            list.push(name);
        }
    }
    return list;
}

function copyExample()
{
  var folder = ["c"];
  var list = getExampleFiles(path.join(__dirname, "example"));
  for(var l in list)
  {
    var name = list[l].split(path.sep);
    if(name[name.length - 2] && folder.indexOf(name[name.length - 2]) > -1)
    {
      try
      {
        fs.mkdirSync(name[name.length - 2]);
      }catch(e){}
      name = name[name.length - 2] + "/" + name[name.length - 1];
    }
    else name = name[name.length - 1];
    var content = fs.readFileSync(list[l]);
    fs.writeFileSync(name, content);
    console.log("[+] Copy of " + name + " done");
  }
}

function showProject()
{
  var project = "project.json";
  if(CLI.stack && CLI.stack.length > 0)
  {
    project = CLI.stack[CLI.stack.length - 1];
  }
  try
  {
    var pConf = fs.readFileSync(project);
    var jConf = JSON.parse(pConf);
    printProject(jConf);
  }
  catch (e)
  {
    console.dir("[!] Error : " + e.message);
  }

}

function Clean(purge)
{
  var project = "project.json";
  if(CLI.stack && CLI.stack.length > 0)
  {
    project = CLI.stack[CLI.stack.length - 1];
  }
  try
  {
    var pConf = fs.readFileSync(project);
    var jConf = JSON.parse(pConf);
    if(jConf.main)
    {
      if( (CLI.cli["--purge"] || purge) && jConf.out)
      {
        var outFile = jConf.out;
        if(jConf.out[0] != path.sep)
        {
          outFile = path.join(path.dirname(project), jConf.out);
        }
        try{fs.unlinkSync(outFile);}catch(e){}
      }
    }
    try{fs.unlinkSync(project)}catch(e){}
  }
  catch (e)
  {
    console.dir("[!] Error : " + e.message);
  }
}

function printProject(obj)
{
  console.log();
  console.log("[*] Project configuration :\n");
  console.log("Main file : " + obj.main);
  console.log("Output    : " + obj.out);
  console.log("Target    : " + obj.target);
  console.log("Preset    : " + obj.preset);
  console.log();
}

function Build(prepare)
{
  if(CLI.cli["--build"]) DEFAULT_COMPILER = CLI.cli["--build"].argument;
  else if(CLI.cli["-b"]) DEFAULT_COMPILER = CLI.cli["-b"].argument;

  COMPILER = require(path.join(__dirname, "compiler", DEFAULT_COMPILER, "compiler.js"));

  if(CLI.cli["--compiler"] && CLI.cli["--compiler"].argument) COMPILER.COMPILER = CLI.cli["--compiler"].argument;

  var preset;
  if(CLI.cli["--preset"] && CLI.cli["--preset"].argument) preset = CLI.cli["--preset"].argument;

  var env;
  if(CLI.cli["--env"] && CLI.cli["--env"].argument) env = CLI.cli["--env"].argument;

  if(!preset) preset = "speed";
  if(!env) env = "std";

  if(!CLI.stack || CLI.stack.length < 1)
  {
    console.error("[!] Missing file to compile or project.json path, 'nectar --help' if you need help");
    return;
  }
  else
  {
	var QUIET = false;
    var _in = CLI.stack[0];

    fs.readFile(_in, function(err, fileData)
    {
      if(err)
      {
        console.error("[!] Error : " + err.message);
        return;
      }
      else
      {

        /* CHECKING */
        Check(_in);
        /* END CHECKING */

        var ext = "js";
        var _Ext = _in.split(".");
        if(_Ext.length > 1) ext = _Ext[_Ext.length - 1];

		/*** CREATE COMPIL ENV ***/
		var _current = process.cwd();
		var _npath = path.join(_current, ".nectar");
		try { fs.mkdirSync(_npath); } catch(e){};
		var _tmp = path.join(_npath, Math.random().toString(36).substr(2, 5));
		try { fs.mkdirSync(_tmp); } catch(e){};

		/*** PREPARE SRC ***/
		COMPILER.Prepare(_tmp);

        var fProject = false;
        var prjectConf = {};
        if(path.basename(_in) == "project.json")
        {
          try
          {
              projectConf = JSON.parse(fileData);
              fProject = true;
              single = false;
          }
          catch (e)
          {
            console.error("[!] Error with project.json : " + e.message);
            return;
          }
        }

		/*** GET FILES NAME ***/
		var _binoutput = "";
		if(fProject)
		{
			_binoutput = projectConf.out;
		}
		else _binoutput = path.basename(_in).slice(0, path.basename(_in).length - path.extname(_in).length);

		if(CLI.cli["-o"])
		{
			_binoutput = CLI.cli["-o"].argument;
		}
		else if(CLI.cli["--out"])
		{
			_binoutput = CLI.cli["--out"].argument;
		}

		_binoutput = path.join(process.cwd(), _binoutput)

		var _cout = path.join(_tmp, path.basename(_in).slice(0, path.basename(_in).length - path.extname(_in).length) + ".cpp");

		_binoutput = COMPILER.Out(_binoutput);

		var projTo = "";
		var tmp = _in.split("/");

		projTo = _binoutput;

		var main = _in.split(path.sep);
		main = main[main.length - 1];

		var tips = "";

		if(!QUIET) console.log("[*] Generating source file");

		var _code = fs.readFileSync(path.resolve(_in)).toString();
		COMPILER.Parse(_code);
		fs.writeFileSync(_cout, COMPILER.MAIN);

		var _args = [_in, "-o", _cout];

		//process.chdir(_tmp);

		if(CLI.cli["--preset"] && CLI.cli["--preset"].argument == "speed")
		{
			COMPILER.OPTION += " -Ofast";
		}
		else if(CLI.cli["--preset"] && CLI.cli["--preset"].argument == "size")
		{
			COMPILER.OPTION += " -Os";
		}
		else
		{
			COMPILER.OPTION += " -O1";
		}
		if(!QUIET) console.log("[*] Compiling");
		try
		{
			COMPILER.Compile(_tmp, _cout);
			fs.chmodSync(_binoutput, "755");
		}
		catch(e)
		{
			console.log("[!] Compilation error");
			console.log(e);
			process.exit(1);
		}

		if(!CLI.cli["--conserve"])
		{
			process.chdir(_current);
			rmdir(_tmp, function() {});
		}

		var verb = false;
		if(CLI.cli["--verbose"]) verb = true;

		var bin = fs.statSync(_binoutput);

		if(verb)
		{
			console.log("[+] Compilation done\n");
			console.log("[*] Informations :\n");
			var size = "Size      : ";
			if(bin.size < 1000) size += bin.size + " o";
			else if(bin.size < 1000000) size += (bin.size / 1000) + " ko";
			else size += (bin.size / 1000000) + " mo";
			console.log(size);
			console.log("Main file : " + main);
			console.log("Output    : " + projTo);
			console.log("Preset    : " + preset);
		}

		//if(CLI.cli["--tips"] && tips && tips.length > 0) console.log("\n" + tips + "\n");

		if(CLI.cli["--flash"]) Flash(to, CLI.cli["--flash"].argument, target, verb);

		if(CLI.cli["--run"])
		{
			var _binexec = child_process.spawnSync(_binoutput,
			[],
			{
				stdio: [process.stdin, process.stdout, process.stderr],
				cwd: process.cwd(),
				env: process.env
			});
			if(_binexec.error)
			{
				console.log(_binexec.error);
			}
		}
		/*
		  if(!CLI.cli["--prepare"])
          {
			  var _current = path.dirname(path.resolve(process.argv[1]));
			  var _native = path.join(_current, "core", "nativejs");
			  var _to = path.resolve(to);
			  var _fullPathCompile = path.resolve(fName);
			  console.log(child_process.execSync("cd " + _native + " && node njs " + _fullPathCompile + " --compiler " + DEFAULT_COMPILER + " -o " + _to));
		  }
          else
          {
	           var pObj = {main: main, out:projTo, target:target, preset:preset};
	            printProject(pObj);
          }
		*/
      }
    });
  }
}

function showVersion()
{
  console.log("NectarJS v" + VERSION);
}

function Check(file)
{
  if(file.split('.').pop() != "js") return;

  if(CLI.cli["--check"]) process.exit();
}

function Help()
{
  showVersion();
  console.log("\n[*] Compile :\nnectar [--target the-target] [--run] [--preset speed|size] [-o output] [--tips] [--flash device] source.js|project.json\n");
  console.log("[*] Show project :\nnectar [--project] [project.json]\n");
  console.log("[*] Clean project :\nnectar [--clean] [--purge] [path_to_project.json]\n");
  console.log("[*] Copy example files :\nnectar --example\n");
  console.log("[*] Nectar version :\nnectar --version\n");
}
<commit_msg>Updated<commit_after>#!/usr/bin/env node
// TODO : Verifier Self Call functions sans console.log sur linux pb ^M
// TODO : rajouter var() pour les param de type string ou number
/*
 * This file is part of NectarJS
 * Copyright (c) 2017 - 2020 Adrien THIERRY
 * http://nectarjs.com - https://seraum.com/
 *
 * sources : https://github.com/nectarjs/nectarjs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

var VERSION = "0.2.10";
var VALID_COMPILER = ["native", "bc", "qjs"];

global.fs = require('fs');
global.os = require('os');
global.path = require('path');
global.process = require('process');
global.querystring = require('querystring');
global.child_process = require('child_process');
global.execSync = child_process.execSync;

var parseCLI = require('./base/cli/cliParser.js');
var coreHttp = require('./base/util/httpUtils.js');
var getExt = require('./base/util/getExt.js');
var getTips = require('./base/util/getTips.js');
var Flash = require('./base/util/flash.js');
var rmdir = require("./base/util/rmdir.js");
var CURRENT = process.cwd();
var TARGET = require('./base/compiler/target.js');
var PLATFORM = os.platform();
var ARCH = os.arch();

var COMPILER;
var DEFAULT_COMPILER = "native";

var CLI = parseCLI(process.argv);

if(CLI.error)
{
  console.log(CLI.msg);
  return;
}

var ACTION = "build";
if(CLI.cli["--help"] || CLI.cli["-h"]) ACTION = "help";
else if(CLI.cli["--example"] || CLI.cli["--examples"]) ACTION = "example";
else if(CLI.cli["--version"] || CLI.cli["-v"]) ACTION = "version";
else if(CLI.cli["--project"]) ACTION = "showproject";
else if(CLI.cli["--clean"] || CLI.cli["--purge"]) ACTION = "clean";

switch(ACTION)
{
  case "version":
    showVersion();
    break;

  case "help":
    Help();
    break;

  case "example":
    copyExample();
    break;

  case "showproject":
    showProject();
    break;

  case "build":
    Build();
    break;

  case "clean":
    Clean();
    break;

  default:
    Help();
    break;
}

function getExampleFiles (dir, list)
{
    list = list || [];
    var files = fs.readdirSync(dir);
    for (var i in files)
    {
        var name = dir + path.sep + files[i];
        if (fs.statSync(name).isDirectory())
        {
            getExampleFiles(name, list);
        }
        else
        {
            list.push(name);
        }
    }
    return list;
}

function copyExample()
{
  var folder = ["c"];
  var list = getExampleFiles(path.join(__dirname, "example"));
  for(var l in list)
  {
    var name = list[l].split(path.sep);
    if(name[name.length - 2] && folder.indexOf(name[name.length - 2]) > -1)
    {
      try
      {
        fs.mkdirSync(name[name.length - 2]);
      }catch(e){}
      name = name[name.length - 2] + "/" + name[name.length - 1];
    }
    else name = name[name.length - 1];
    var content = fs.readFileSync(list[l]);
    fs.writeFileSync(name, content);
    console.log("[+] Copy of " + name + " done");
  }
}

function showProject()
{
  var project = "project.json";
  if(CLI.stack && CLI.stack.length > 0)
  {
    project = CLI.stack[CLI.stack.length - 1];
  }
  try
  {
    var pConf = fs.readFileSync(project);
    var jConf = JSON.parse(pConf);
    printProject(jConf);
  }
  catch (e)
  {
    console.dir("[!] Error : " + e.message);
  }

}

function Clean(purge)
{
  var project = "project.json";
  if(CLI.stack && CLI.stack.length > 0)
  {
    project = CLI.stack[CLI.stack.length - 1];
  }
  try
  {
    var pConf = fs.readFileSync(project);
    var jConf = JSON.parse(pConf);
    if(jConf.main)
    {
      if( (CLI.cli["--purge"] || purge) && jConf.out)
      {
        var outFile = jConf.out;
        if(jConf.out[0] != path.sep)
        {
          outFile = path.join(path.dirname(project), jConf.out);
        }
        try{fs.unlinkSync(outFile);}catch(e){}
      }
    }
    try{fs.unlinkSync(project)}catch(e){}
  }
  catch (e)
  {
    console.dir("[!] Error : " + e.message);
  }
}

function printProject(obj)
{
  console.log();
  console.log("[*] Project configuration :\n");
  console.log("Main file : " + obj.main);
  console.log("Output    : " + obj.out);
  console.log("Target    : " + obj.target);
  console.log("Preset    : " + obj.preset);
  console.log();
}

function Build(prepare)
{
  if(CLI.cli["--build"]) DEFAULT_COMPILER = CLI.cli["--build"].argument;
  else if(CLI.cli["-b"]) DEFAULT_COMPILER = CLI.cli["-b"].argument;

  COMPILER = require(path.join(__dirname, "compiler", DEFAULT_COMPILER, "compiler.js"));

  if(CLI.cli["--compiler"] && CLI.cli["--compiler"].argument) COMPILER.COMPILER = CLI.cli["--compiler"].argument;

  var preset;
  if(CLI.cli["--preset"] && CLI.cli["--preset"].argument) preset = CLI.cli["--preset"].argument;

  var env;
  if(CLI.cli["--env"] && CLI.cli["--env"].argument) env = CLI.cli["--env"].argument;

  if(!preset) preset = "speed";
  if(!env) env = "std";

  if(!CLI.stack || CLI.stack.length < 1)
  {
    console.error("[!] Missing file to compile or project.json path, 'nectar --help' if you need help");
    return;
  }
  else
  {
	var QUIET = false;
    var _in = CLI.stack[0];

    fs.readFile(_in, function(err, fileData)
    {
      if(err)
      {
        console.error("[!] Error : " + err.message);
        return;
      }
      else
      {

        /* CHECKING */
        Check(_in);
        /* END CHECKING */

        var ext = "js";
        var _Ext = _in.split(".");
        if(_Ext.length > 1) ext = _Ext[_Ext.length - 1];

		/*** CREATE COMPIL ENV ***/
		var _current = process.cwd();
		var _npath = path.join(_current, ".nectar");
		try { fs.mkdirSync(_npath); } catch(e){};
		var _tmp = path.join(_npath, Math.random().toString(36).substr(2, 5));
		try { fs.mkdirSync(_tmp); } catch(e){};

		/*** PREPARE SRC ***/
		COMPILER.Prepare(_tmp);

        var fProject = false;
        var prjectConf = {};
        if(path.basename(_in) == "project.json")
        {
          try
          {
              projectConf = JSON.parse(fileData);
              fProject = true;
              single = false;
          }
          catch (e)
          {
            console.error("[!] Error with project.json : " + e.message);
            return;
          }
        }

		/*** GET FILES NAME ***/
		var _binoutput = "";
		if(fProject)
		{
			_binoutput = projectConf.out;
		}
		else _binoutput = path.basename(_in).slice(0, path.basename(_in).length - path.extname(_in).length);

		if(CLI.cli["-o"])
		{
			_binoutput = CLI.cli["-o"].argument;
		}
		else if(CLI.cli["--out"])
		{
			_binoutput = CLI.cli["--out"].argument;
		}

		_binoutput = path.join(process.cwd(), _binoutput)

		var _cout = path.join(_tmp, path.basename(_in).slice(0, path.basename(_in).length - path.extname(_in).length) + ".cpp");

		_binoutput = COMPILER.Out(_binoutput);

		var projTo = "";
		var tmp = _in.split("/");

		projTo = _binoutput;

		var main = _in.split(path.sep);
		main = main[main.length - 1];

		var tips = "";

		if(!QUIET) console.log("[*] Generating source file");

		var _code = fs.readFileSync(path.resolve(_in)).toString();
		COMPILER.Parse(_code);
		fs.writeFileSync(_cout, COMPILER.MAIN);

		var _args = [_in, "-o", _cout];

		//process.chdir(_tmp);

		if(CLI.cli["--preset"] && CLI.cli["--preset"].argument == "speed")
		{
			COMPILER.OPTION += " -Ofast";
		}
		else if(CLI.cli["--preset"] && CLI.cli["--preset"].argument == "size")
		{
			COMPILER.OPTION += " -Os";
		}

		if(!QUIET) console.log("[*] Compiling");
		try
		{
			COMPILER.Compile(_tmp, _cout);
			fs.chmodSync(_binoutput, "755");
		}
		catch(e)
		{
			console.log("[!] Compilation error");
			console.log(e);
			process.exit(1);
		}

		if(!CLI.cli["--conserve"])
		{
			process.chdir(_current);
			rmdir(_tmp, function() {});
		}

		var verb = false;
		if(CLI.cli["--verbose"]) verb = true;

		var bin = fs.statSync(_binoutput);

		if(verb)
		{
			console.log("[+] Compilation done\n");
			console.log("[*] Informations :\n");
			var size = "Size      : ";
			if(bin.size < 1000) size += bin.size + " o";
			else if(bin.size < 1000000) size += (bin.size / 1000) + " ko";
			else size += (bin.size / 1000000) + " mo";
			console.log(size);
			console.log("Main file : " + main);
			console.log("Output    : " + projTo);
			console.log("Preset    : " + preset);
		}

		//if(CLI.cli["--tips"] && tips && tips.length > 0) console.log("\n" + tips + "\n");

		if(CLI.cli["--flash"]) Flash(to, CLI.cli["--flash"].argument, target, verb);

		if(CLI.cli["--run"])
		{
			var _binexec = child_process.spawnSync(_binoutput,
			[],
			{
				stdio: [process.stdin, process.stdout, process.stderr],
				cwd: process.cwd(),
				env: process.env
			});
			if(_binexec.error)
			{
				console.log(_binexec.error);
			}
		}
		/*
		  if(!CLI.cli["--prepare"])
          {
			  var _current = path.dirname(path.resolve(process.argv[1]));
			  var _native = path.join(_current, "core", "nativejs");
			  var _to = path.resolve(to);
			  var _fullPathCompile = path.resolve(fName);
			  console.log(child_process.execSync("cd " + _native + " && node njs " + _fullPathCompile + " --compiler " + DEFAULT_COMPILER + " -o " + _to));
		  }
          else
          {
	           var pObj = {main: main, out:projTo, target:target, preset:preset};
	            printProject(pObj);
          }
		*/
      }
    });
  }
}

function showVersion()
{
  console.log("NectarJS v" + VERSION);
}

function Check(file)
{
  if(file.split('.').pop() != "js") return;

  if(CLI.cli["--check"]) process.exit();
}

function Help()
{
  showVersion();
  console.log("\n[*] Compile :\nnectar [--target the-target] [--run] [--preset speed|size] [-o output] [--tips] [--flash device] source.js|project.json\n");
  console.log("[*] Show project :\nnectar [--project] [project.json]\n");
  console.log("[*] Clean project :\nnectar [--clean] [--purge] [path_to_project.json]\n");
  console.log("[*] Copy example files :\nnectar --example\n");
  console.log("[*] Nectar version :\nnectar --version\n");
}
<|endoftext|>


<commit_before>var $ = require('jquery');
var $osf = require('osfHelpers');
var bootbox = require('bootbox');

//initialize treebeard
var ProjectNotifications = require('./project-settings-treebeard.js');
new ProjectNotifications(window.contextVars.notificationsData);
<commit_msg>Remove unused imports in osfNotifications.js<commit_after>//initialize treebeard
var ProjectNotifications = require('./project-settings-treebeard.js');
new ProjectNotifications(window.contextVars.notificationsData);
<|endoftext|>