<commit_before>'use strict';

var electron = require('electron'),
    app = electron.app,
    BrowserWindow = electron.BrowserWindow;

var path = require('path');

var {
  assign,
  forEach
} = require('min-dash');

var fetch = require('node-fetch'),
    fs = require('fs'),
    FormData = require('form-data');

/**
 * automatically report crash reports
 *
 * @see http://electron.atom.io/docs/v0.34.0/api/crash-reporter/
 */
// TODO(nikku): do we want to do this?
// require('crash-reporter').start();

var Platform = require('./platform'),
    Config = require('./config'),
    ClientConfig = require('./client-config'),
    FileSystem = require('./file-system'),
    Workspace = require('./workspace'),
    Dialog = require('./dialog'),
    Menu = require('./menu'),
    Cli = require('./cli'),
    Plugins = require('./plugins'),
    deploy = require('./createDeployer')({ fetch, fs, FormData });

var browserOpen = require('./util/browser-open'),
    renderer = require('./util/renderer');

var config = Config.load(path.join(app.getPath('userData'), 'config.json'));

Platform.create(process.platform, app, config);

// variable for developing (reloading and devtools toggling)
app.developmentMode = false;

app.version = require('../package').version;
app.name = 'Camunda Modeler';

// this is shared variable between main and renderer processes
global.metaData = {
  version: app.version,
  name: app.name
};

// get directory of executable
var appPath = path.dirname(app.getPath('exe'));

app.plugins = new Plugins({
  paths: [
    app.getPath('userData'),
    appPath
  ]
});

// set global modeler directory
global.modelerDirectory = appPath;

var menu = new Menu(process.platform);

// bootstrap workspace behavior
new Workspace(config);

// bootstrap client config behavior
var clientConfig = new ClientConfig(app);

// bootstrap dialog
var dialog = new Dialog({
  dialog: electron.dialog,
  config: config,
  userDesktopPath: app.getPath('userDesktop')
});

// bootstrap filesystem
var fileSystem = new FileSystem({
  dialog: dialog
});

// make app a singleton
if (config.get('single-instance', true)) {

  const gotLock = app.requestSingleInstanceLock();

  if (gotLock) {

    app.on('second-instance', (event, commandLine, workingDirectory) => {

      app.emit('app:parse-cmd', commandLine, workingDirectory);

      // focus existing running instance window
      if (app.mainWindow) {
        if (app.mainWindow.isMinimized()) {
          app.mainWindow.restore();
        }

        app.mainWindow.focus();
      }
    });
  } else {
    app.quit();
  }
}

// external //////////

renderer.on('external:open-url', function(options) {
  var url = options.url;

  browserOpen(url);
});

// dialogs //////////

renderer.on('dialog:open-files', async function(options, done) {
  const {
    activeFile
  } = options;

  if (activeFile && activeFile.path) {
    assign(options, {
      defaultPath: path.dirname(activeFile.path)
    });
  }

  const filePaths = await dialog.showOpenDialog(options);

  done(null, filePaths);
});

renderer.on('dialog:open-file-error', async function(options, done) {
  const response = await dialog.showOpenFileErrorDialog(options);

  done(null, response);
});

renderer.on('dialog:save-file', async function(options, done) {
  const { file } = options;

  const { path: originalFilePath } = file;

  if (originalFilePath) {
    assign(options, {
      defaultPath: path.dirname(originalFilePath)
    });
  }

  const filePath = await dialog.showSaveDialog(options);

  done(null, filePath);
});

renderer.on('dialog:show', async function(options, done) {
  const response = await dialog.showDialog(options, done);

  done(null, response);
});

// deploying //////////
// TODO: remove and add as plugin instead

renderer.on('deploy', function(data, done) {
  var workspaceConfig = config.get('workspace', { endpoints: [] });

  var endpointUrl = (workspaceConfig.endpoints || [])[0];

  if (!endpointUrl) {

    let err = new Error('no deploy endpoint configured');

    console.error('failed to deploy', err);
    return done(err.message);
  }

  deploy(endpointUrl, data, function(err, result) {

    if (err) {
      console.error('failed to deploy', err);

      return done(err.message);
    }

    done(null, result);
  });

});

// filesystem //////////

renderer.on('file:read', function(filePath, options = {}, done) {
  try {
    const newFile = fileSystem.readFile(filePath, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

renderer.on('file:read-stats', function(file, done) {
  const newFile = fileSystem.readFileStats(file);

  done(null, newFile);
});

renderer.on('file:write', async function(filePath, file, options = {}, done) {
  try {
    const newFile = fileSystem.writeFile(filePath, file, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

// client config //////////

renderer.on('client-config:get', function(...args) {

  var done = args[args.length - 1];

  try {
    clientConfig.get(...args);
  } catch (e) {
    if (typeof done === 'function') {
      done(e);
    }
  }
});

// open file handling //////////

// list of files that should be opened by the editor
app.openFiles = [];

app.on('app:parse-cmd', function(argv, cwd) {
  console.log('app:parse-cmd', argv.join(' '), cwd);

  // will result in opening dev.js as file
  var files = Cli.extractFiles(argv, cwd);

  files.forEach(function(file) {
    app.emit('app:open-file', file);
  });
});

app.on('app:open-file', function(filePath) {
  var file;

  console.log('app:open-file', filePath);

  if (!app.clientReady) {

    // defer file open
    return app.openFiles.push(filePath);
  }

  try {
    file = fileSystem.readFile(filePath);
  } catch (e) {
    dialog.showOpenFileErrorDialog({
      name: path.basename(filePath)
    });
  }

  // open file immediately
  renderer.send('client:open-files', [ file ]);
});

app.on('app:client-ready', function() {
  var files = [];

  console.log('app:client-ready');

  forEach(app.openFiles, function(filePath) {
    try {
      files.push(fileSystem.readFile(filePath));
    } catch (e) {
      dialog.showOpenFileErrorDialog({
        name: path.basename(filePath)
      });
    }
  });

  // renderer.send('client:open-files', files);

  renderer.send('client:started');
});

renderer.on('client:ready', function() {
  app.clientReady = true;

  app.emit('app:client-ready');
});

app.on('web-contents-created', (event, webContents) => {

  // open all external links in new window
  webContents.on('new-window', function(event, url) {
    event.preventDefault();

    browserOpen(url);
  });

  // disable web-view (not used)
  webContents.on('will-attach-webview', () => {
    event.preventDefault();
  });

  // open in-page links externally by default
  // @see https://github.com/electron/electron/issues/1344#issuecomment-171516636
  webContents.on('will-navigate', (event, url) => {

    if (url !== webContents.getURL()) {
      event.preventDefault();

      browserOpen(url);
    }
  });
});

/**
 * Create the main window that represents the editor.
 *
 * @return {BrowserWindow}
 */
app.createEditorWindow = function() {

  var windowOptions = {
    resizable: true,
    show: false,
    title: 'Camunda Modeler'
  };

  if (process.platform === 'linux') {
    windowOptions.icon = path.join(__dirname + '/../resources/favicon.png');
  }

  var mainWindow = app.mainWindow = new BrowserWindow(windowOptions);

  dialog.setActiveWindow(mainWindow);

  menu.init();

  var url = 'file://' + path.resolve(__dirname + '/../public/index.html');

  if (app.developmentMode) {
    url = 'http://localhost:3000';
  }

  mainWindow.loadURL(url);

  // handling case when user clicks on window close button
  mainWindow.on('close', function(e) {
    console.log('Initiating close of main window');

    if (app.quitAllowed) {
      // dereferencing main window and resetting client state
      app.mainWindow = null;
      dialog.setActiveWindow(null);

      app.clientReady = false;

      return console.log('Main window closed');
    }

    // preventing window from closing until client allows to do so
    e.preventDefault();

    console.log('Asking client to allow application quit');

    app.emit('app:quit-denied');

    renderer.send('menu:action', 'quit');
  });

  mainWindow.on('focus', function() {
    console.log('Window focused');
    renderer.send('client:window-focused');
  });

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.webContents.on('dom-ready', function() {
    mainWindow.maximize();
  });

  app.emit('app:window-created', mainWindow);

  // only set by client, when it is ok to exit
  app.quitAllowed = false;
};

/**
 * Application entry point
 * Emitted when Electron has finished initialization.
 */
app.on('ready', function() {

  // quit command from menu/shortcut
  app.on('app:quit', function() {
    console.log('Initiating termination of the application');

    renderer.send('menu:action', 'quit');
  });

  // client quit verification event
  renderer.on('app:quit-allowed', function() {
    console.log('Quit allowed');

    app.quitAllowed = true;

    app.mainWindow.close();
  });

  app.createEditorWindow();

  app.emit('app:parse-cmd', process.argv, process.cwd());
});

// expose app
module.exports = app;
<commit_msg>chore(app): simplify dialog:save-file callback<commit_after>'use strict';

var electron = require('electron'),
    app = electron.app,
    BrowserWindow = electron.BrowserWindow;

var path = require('path');

var {
  assign,
  forEach
} = require('min-dash');

var fetch = require('node-fetch'),
    fs = require('fs'),
    FormData = require('form-data');

/**
 * automatically report crash reports
 *
 * @see http://electron.atom.io/docs/v0.34.0/api/crash-reporter/
 */
// TODO(nikku): do we want to do this?
// require('crash-reporter').start();

var Platform = require('./platform'),
    Config = require('./config'),
    ClientConfig = require('./client-config'),
    FileSystem = require('./file-system'),
    Workspace = require('./workspace'),
    Dialog = require('./dialog'),
    Menu = require('./menu'),
    Cli = require('./cli'),
    Plugins = require('./plugins'),
    deploy = require('./createDeployer')({ fetch, fs, FormData });

var browserOpen = require('./util/browser-open'),
    renderer = require('./util/renderer');

var config = Config.load(path.join(app.getPath('userData'), 'config.json'));

Platform.create(process.platform, app, config);

// variable for developing (reloading and devtools toggling)
app.developmentMode = false;

app.version = require('../package').version;
app.name = 'Camunda Modeler';

// this is shared variable between main and renderer processes
global.metaData = {
  version: app.version,
  name: app.name
};

// get directory of executable
var appPath = path.dirname(app.getPath('exe'));

app.plugins = new Plugins({
  paths: [
    app.getPath('userData'),
    appPath
  ]
});

// set global modeler directory
global.modelerDirectory = appPath;

var menu = new Menu(process.platform);

// bootstrap workspace behavior
new Workspace(config);

// bootstrap client config behavior
var clientConfig = new ClientConfig(app);

// bootstrap dialog
var dialog = new Dialog({
  dialog: electron.dialog,
  config: config,
  userDesktopPath: app.getPath('userDesktop')
});

// bootstrap filesystem
var fileSystem = new FileSystem({
  dialog: dialog
});

// make app a singleton
if (config.get('single-instance', true)) {

  const gotLock = app.requestSingleInstanceLock();

  if (gotLock) {

    app.on('second-instance', (event, commandLine, workingDirectory) => {

      app.emit('app:parse-cmd', commandLine, workingDirectory);

      // focus existing running instance window
      if (app.mainWindow) {
        if (app.mainWindow.isMinimized()) {
          app.mainWindow.restore();
        }

        app.mainWindow.focus();
      }
    });
  } else {
    app.quit();
  }
}

// external //////////

renderer.on('external:open-url', function(options) {
  var url = options.url;

  browserOpen(url);
});

// dialogs //////////

renderer.on('dialog:open-files', async function(options, done) {
  const {
    activeFile
  } = options;

  if (activeFile && activeFile.path) {
    assign(options, {
      defaultPath: path.dirname(activeFile.path)
    });
  }

  const filePaths = await dialog.showOpenDialog(options);

  done(null, filePaths);
});

renderer.on('dialog:open-file-error', async function(options, done) {
  const response = await dialog.showOpenFileErrorDialog(options);

  done(null, response);
});

renderer.on('dialog:save-file', async function(options, done) {
  const { file } = options;

  if (file.path) {
    assign(options, {
      defaultPath: path.dirname(file.path)
    });
  }

  const filePath = await dialog.showSaveDialog(options);

  done(null, filePath);
});

renderer.on('dialog:show', async function(options, done) {
  const response = await dialog.showDialog(options, done);

  done(null, response);
});

// deploying //////////
// TODO: remove and add as plugin instead

renderer.on('deploy', function(data, done) {
  var workspaceConfig = config.get('workspace', { endpoints: [] });

  var endpointUrl = (workspaceConfig.endpoints || [])[0];

  if (!endpointUrl) {

    let err = new Error('no deploy endpoint configured');

    console.error('failed to deploy', err);
    return done(err.message);
  }

  deploy(endpointUrl, data, function(err, result) {

    if (err) {
      console.error('failed to deploy', err);

      return done(err.message);
    }

    done(null, result);
  });

});

// filesystem //////////

renderer.on('file:read', function(filePath, options = {}, done) {
  try {
    const newFile = fileSystem.readFile(filePath, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

renderer.on('file:read-stats', function(file, done) {
  const newFile = fileSystem.readFileStats(file);

  done(null, newFile);
});

renderer.on('file:write', async function(filePath, file, options = {}, done) {
  try {
    const newFile = fileSystem.writeFile(filePath, file, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

// client config //////////

renderer.on('client-config:get', function(...args) {

  var done = args[args.length - 1];

  try {
    clientConfig.get(...args);
  } catch (e) {
    if (typeof done === 'function') {
      done(e);
    }
  }
});

// open file handling //////////

// list of files that should be opened by the editor
app.openFiles = [];

app.on('app:parse-cmd', function(argv, cwd) {
  console.log('app:parse-cmd', argv.join(' '), cwd);

  // will result in opening dev.js as file
  var files = Cli.extractFiles(argv, cwd);

  files.forEach(function(file) {
    app.emit('app:open-file', file);
  });
});

app.on('app:open-file', function(filePath) {
  var file;

  console.log('app:open-file', filePath);

  if (!app.clientReady) {

    // defer file open
    return app.openFiles.push(filePath);
  }

  try {
    file = fileSystem.readFile(filePath);
  } catch (e) {
    dialog.showOpenFileErrorDialog({
      name: path.basename(filePath)
    });
  }

  // open file immediately
  renderer.send('client:open-files', [ file ]);
});

app.on('app:client-ready', function() {
  var files = [];

  console.log('app:client-ready');

  forEach(app.openFiles, function(filePath) {
    try {
      files.push(fileSystem.readFile(filePath));
    } catch (e) {
      dialog.showOpenFileErrorDialog({
        name: path.basename(filePath)
      });
    }
  });

  // renderer.send('client:open-files', files);

  renderer.send('client:started');
});

renderer.on('client:ready', function() {
  app.clientReady = true;

  app.emit('app:client-ready');
});

app.on('web-contents-created', (event, webContents) => {

  // open all external links in new window
  webContents.on('new-window', function(event, url) {
    event.preventDefault();

    browserOpen(url);
  });

  // disable web-view (not used)
  webContents.on('will-attach-webview', () => {
    event.preventDefault();
  });

  // open in-page links externally by default
  // @see https://github.com/electron/electron/issues/1344#issuecomment-171516636
  webContents.on('will-navigate', (event, url) => {

    if (url !== webContents.getURL()) {
      event.preventDefault();

      browserOpen(url);
    }
  });
});

/**
 * Create the main window that represents the editor.
 *
 * @return {BrowserWindow}
 */
app.createEditorWindow = function() {

  var windowOptions = {
    resizable: true,
    show: false,
    title: 'Camunda Modeler'
  };

  if (process.platform === 'linux') {
    windowOptions.icon = path.join(__dirname + '/../resources/favicon.png');
  }

  var mainWindow = app.mainWindow = new BrowserWindow(windowOptions);

  dialog.setActiveWindow(mainWindow);

  menu.init();

  var url = 'file://' + path.resolve(__dirname + '/../public/index.html');

  if (app.developmentMode) {
    url = 'http://localhost:3000';
  }

  mainWindow.loadURL(url);

  // handling case when user clicks on window close button
  mainWindow.on('close', function(e) {
    console.log('Initiating close of main window');

    if (app.quitAllowed) {
      // dereferencing main window and resetting client state
      app.mainWindow = null;
      dialog.setActiveWindow(null);

      app.clientReady = false;

      return console.log('Main window closed');
    }

    // preventing window from closing until client allows to do so
    e.preventDefault();

    console.log('Asking client to allow application quit');

    app.emit('app:quit-denied');

    renderer.send('menu:action', 'quit');
  });

  mainWindow.on('focus', function() {
    console.log('Window focused');
    renderer.send('client:window-focused');
  });

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.webContents.on('dom-ready', function() {
    mainWindow.maximize();
  });

  app.emit('app:window-created', mainWindow);

  // only set by client, when it is ok to exit
  app.quitAllowed = false;
};

/**
 * Application entry point
 * Emitted when Electron has finished initialization.
 */
app.on('ready', function() {

  // quit command from menu/shortcut
  app.on('app:quit', function() {
    console.log('Initiating termination of the application');

    renderer.send('menu:action', 'quit');
  });

  // client quit verification event
  renderer.on('app:quit-allowed', function() {
    console.log('Quit allowed');

    app.quitAllowed = true;

    app.mainWindow.close();
  });

  app.createEditorWindow();

  app.emit('app:parse-cmd', process.argv, process.cwd());
});

// expose app
module.exports = app;
<|endoftext|>


<commit_before>/* Router for RPC interface */
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    RPCrouter = express.Router(),
    jayson = require('jayson'),
    http = require('http');

var exportDataToFile = function exportDataToFile (ref, data) {

    switch (ref) {

      case 'uplink' :

          var packetsdatabase = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/packets.json'), 'utf8'));
          var data = data;

          packetsdatabase.push(data);

          fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(packetsdatabase));

          break;

      case 'erase' :

          fs.writeFileSync(path.join(__dirname, './../config/device.json'), JSON.stringify({}));

          break;
    }
};

var decode1m2mpayload = function (obj) {

    return new Promise ( function (resolve, reject) {

        console.log('1m2m payload to make human readable: ', obj);

        var hex_o =  Buffer.from(obj.toString(), 'base64').toString('hex');
        var url = 'http://1m2m.eu/services/GETPAYLOAD?Human=0&PL=' + hex_o;

        http.get(url, function (res) {

          const { statusCode } = res;
          const contentType = res.headers['content-type'];

          let error;

          if (statusCode !== 200) {

            error = new Error('Request Failed.\n' +
                              `Status Code: ${statusCode}`);
          }

          if (error) {

            console.error(error.message);
            // consume response data to free up memory
            res.resume();
            return;
          }

          let rawData = '';

          res.on('data', function (chunk) { rawData += chunk; });

          res.on('end', function () {

            try {
              const parsedData = JSON.parse(rawData);
              console.log('Parsed response data', parsedData.toString());
              resolve( parsedData );

            } catch (e) {
              console.error(e.message);
            }
          });

        }).on('error', (e) => {
          console.error(`Got error: ${e.message}`);
        });
    });
};

var getQualityIndex = function (AnIn1, AnIn2) {

    var quality;

    if ( Anin1 < 250 && AnIn2 < 250 ) {
        quality = 'clean';
    } else if ( Anin1 < 250 && AnIn2 > 3000 ) {
        quality = 'light';
    } else if ( Anin1 > 3000 && AnIn2 < 250 ) {
        quality = 'medium';
    } else if ( Anin1 > 3000 && AnIn2 > 3000 ) {
        quality = 'high';
    }

    return quality;
};

var catchRpc = function catchRpc (req, res, next) {

    var io = req.app.get('socketio');

    console.log('req value from RPCRouter.post(*): ', req.body);

    // Create a promise for decoding the 1m2m payload before sending it to the listen.pug view
    decode1m2mpayload(req.body.params.payload).then( function (obj) {

          req.body.params.humanpayload = obj;

          // set the polluton scale for the winsen ZP01-MP503 module if the data is present
          if (req.body.params.humanpayload.AnIn1) {
              req.body.params.pollutionlevel = getQualityIndex(parseInt(req.body.params.humanpayload.AnIn1, 10), parseInt(req.body.params.humanpayload.AnIn2, 10));
          }

          console.log('Added decoded payload to req.body: ', req.body);

          io.emit("rpcrequest", req.body);
    }) ;

    next();
};

// RPC methods for Everynet and 1m2m devices
var methods = {

    uplink: jayson.Method(function (args, done) {

     /* Parameters in the request
      * uplink method only needs to return 'ok'
      * args.dev_eui
      * args.dev_addr
      * args.rx_time
      * args.counter_up
      * args.port
      * args.encrypted_payload
      * args.radio [includes numerous sub params]
      */

      console.log('data from uplink() method', args);

      exportDataToFile('uplink', args);

      done(null, 'ok');
  }),
  outdated: function (args, done) {

     /* Parameters in the request
      * same as in uplink method
      * this method delivers packets that were accumulated while application
      * was unable to receive request from the network server [batch]
      */

      done(null, 'ok');
  },
  status: function (args, done) {

   /* Parameters in the request
    * args.dev_eui
    * args.dev_addr
    * args.battery [battery level: 1-254, 0=external power source, 255=unknown]
    * args.snr [signal to noise ratio]
    */

    done(null, 'ok');
  },
  satus_request: function (args, done) {

   /* Parameters in the request
    *
    * args.api_key
    * args.dev_eui
    */

    done(null, 'ok');
  },
  downlink: jayson.Method(function (args, done) {

      // Make a Redis DB and work from there

      var currentdevice = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/device.json'), 'utf8'));

    /* Parameters in the request
     * args.dev_eui
     * args.dev_addr
     * args.tx_time
     * args.max_size
     * args.counter_down
     */

      if ( !currentdevice.encrypted_payload ) {

          console.log('encrypted payload missing');

          done(null, { "pending": false,
                       "confirmed": false,
                       "payload": "" });

      // if the dev_eui from the Network Server matches what's on file we send the payload
      } else if ( currentdevice.encrypted_payload && args.dev_eui == currentdevice.dev_eui ) {

          var result = { "pending": false,
                         "confirmed": false,
                         "payload": encryptedpayload };

          exportDataToFile('erase', {});

          done(null, result);

      }  else {

          console.log('nothing in storage');

          done(null, { "pending": false,
                       "confirmed": false,
                       "payload": "" });
      }
  }),
  post_uplink: function (args, done) {

   /* Parameters in the request
    * this type of request contains redundant packets obtained through other gateways
    * only the timestamp for aquisition by the gateway varies
    * args.dev_eui
    * args.dev_addr
    * args.rx_time
    * args.counter_up
    * args.port
    * args.encrypted_payload
    * args.radio [includes numerous sub params]
    */

    done(null, 'ok');
  },
  notify: function (args, done) {

     /* Parameters in the request
      * only for always-on 'class C' devices
      * notifies the network server of packets available for uplink
      * network server then emits a 'downlink' request which can be replied to with a payload
      * args.api_key
      * args.dev_eui
      */

      done(null, 'ok');
  },
  join: jayson.Method (function (args, done) {

      /*
       * The join() method is not called if app_key was provided to the network by the user
       */

        done(null, 'ok');
  })

};

// Any request coming to /lora/rpc will be handled by the jayson server
var jaysonserver = jayson.server(methods, {params: Object});

RPCrouter.post('*', catchRpc, jaysonserver.middleware());

module.exports = RPCrouter;
<commit_msg>fixed condition for Analog data<commit_after>/* Router for RPC interface */
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    RPCrouter = express.Router(),
    jayson = require('jayson'),
    http = require('http');

var exportDataToFile = function exportDataToFile (ref, data) {

    switch (ref) {

      case 'uplink' :

          var packetsdatabase = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/packets.json'), 'utf8'));
          var data = data;

          packetsdatabase.push(data);

          fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(packetsdatabase));

          break;

      case 'erase' :

          fs.writeFileSync(path.join(__dirname, './../config/device.json'), JSON.stringify({}));

          break;
    }
};

var decode1m2mpayload = function (obj) {

    return new Promise ( function (resolve, reject) {

        console.log('1m2m payload to make human readable: ', obj);

        var hex_o =  Buffer.from(obj.toString(), 'base64').toString('hex');
        var url = 'http://1m2m.eu/services/GETPAYLOAD?Human=0&PL=' + hex_o;

        http.get(url, function (res) {

          const { statusCode } = res;
          const contentType = res.headers['content-type'];

          let error;

          if (statusCode !== 200) {

            error = new Error('Request Failed.\n' +
                              `Status Code: ${statusCode}`);
          }

          if (error) {

            console.error(error.message);
            // consume response data to free up memory
            res.resume();
            return;
          }

          let rawData = '';

          res.on('data', function (chunk) { rawData += chunk; });

          res.on('end', function () {

            try {
              const parsedData = JSON.parse(rawData);
              console.log('Parsed response data', parsedData.toString());
              resolve( parsedData );

            } catch (e) {
              console.error(e.message);
            }
          });

        }).on('error', (e) => {
          console.error(`Got error: ${e.message}`);
        });
    });
};

var getQualityIndex = function (AnIn1, AnIn2) {

    var quality;

    if ( Anin1 < 250 && AnIn2 < 250 ) {
        quality = 'clean';
    } else if ( Anin1 < 250 && AnIn2 > 3000 ) {
        quality = 'light';
    } else if ( Anin1 > 3000 && AnIn2 < 250 ) {
        quality = 'medium';
    } else if ( Anin1 > 3000 && AnIn2 > 3000 ) {
        quality = 'high';
    }

    return quality;
};

var catchRpc = function catchRpc (req, res, next) {

    var io = req.app.get('socketio');

    console.log('req value from RPCRouter.post(*): ', req.body);

    // Create a promise for decoding the 1m2m payload before sending it to the listen.pug view
    decode1m2mpayload(req.body.params.payload).then( function (obj) {

          req.body.params.humanpayload = obj;

          // set the polluton scale for the winsen ZP01-MP503 module if the analog data is present
          if (req.body.params.humanpayload.MsgID == 'Analog') {
              req.body.params.pollutionlevel = getQualityIndex(parseInt(req.body.params.humanpayload.AnIn1, 10), parseInt(req.body.params.humanpayload.AnIn2, 10));
          }

          console.log('Added decoded payload to req.body: ', req.body);

          io.emit("rpcrequest", req.body);
    }) ;

    next();
};

// RPC methods for Everynet and 1m2m devices
var methods = {

    uplink: jayson.Method(function (args, done) {

     /* Parameters in the request
      * uplink method only needs to return 'ok'
      * args.dev_eui
      * args.dev_addr
      * args.rx_time
      * args.counter_up
      * args.port
      * args.encrypted_payload
      * args.radio [includes numerous sub params]
      */

      console.log('data from uplink() method', args);

      exportDataToFile('uplink', args);

      done(null, 'ok');
  }),
  outdated: function (args, done) {

     /* Parameters in the request
      * same as in uplink method
      * this method delivers packets that were accumulated while application
      * was unable to receive request from the network server [batch]
      */

      done(null, 'ok');
  },
  status: function (args, done) {

   /* Parameters in the request
    * args.dev_eui
    * args.dev_addr
    * args.battery [battery level: 1-254, 0=external power source, 255=unknown]
    * args.snr [signal to noise ratio]
    */

    done(null, 'ok');
  },
  satus_request: function (args, done) {

   /* Parameters in the request
    *
    * args.api_key
    * args.dev_eui
    */

    done(null, 'ok');
  },
  downlink: jayson.Method(function (args, done) {

      // Make a Redis DB and work from there

      var currentdevice = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/device.json'), 'utf8'));

    /* Parameters in the request
     * args.dev_eui
     * args.dev_addr
     * args.tx_time
     * args.max_size
     * args.counter_down
     */

      if ( !currentdevice.encrypted_payload ) {

          console.log('encrypted payload missing');

          done(null, { "pending": false,
                       "confirmed": false,
                       "payload": "" });

      // if the dev_eui from the Network Server matches what's on file we send the payload
      } else if ( currentdevice.encrypted_payload && args.dev_eui == currentdevice.dev_eui ) {

          var result = { "pending": false,
                         "confirmed": false,
                         "payload": encryptedpayload };

          exportDataToFile('erase', {});

          done(null, result);

      }  else {

          console.log('nothing in storage');

          done(null, { "pending": false,
                       "confirmed": false,
                       "payload": "" });
      }
  }),
  post_uplink: function (args, done) {

   /* Parameters in the request
    * this type of request contains redundant packets obtained through other gateways
    * only the timestamp for aquisition by the gateway varies
    * args.dev_eui
    * args.dev_addr
    * args.rx_time
    * args.counter_up
    * args.port
    * args.encrypted_payload
    * args.radio [includes numerous sub params]
    */

    done(null, 'ok');
  },
  notify: function (args, done) {

     /* Parameters in the request
      * only for always-on 'class C' devices
      * notifies the network server of packets available for uplink
      * network server then emits a 'downlink' request which can be replied to with a payload
      * args.api_key
      * args.dev_eui
      */

      done(null, 'ok');
  },
  join: jayson.Method (function (args, done) {

      /*
       * The join() method is not called if app_key was provided to the network by the user
       */

        done(null, 'ok');
  })

};

// Any request coming to /lora/rpc will be handled by the jayson server
var jaysonserver = jayson.server(methods, {params: Object});

RPCrouter.post('*', catchRpc, jaysonserver.middleware());

module.exports = RPCrouter;
<|endoftext|>


<commit_before>'use strict';
const os = require('os');
const electron = require('electron');
const {dialog} = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const shell = electron.shell;
const appName = app.getName();

const {addDomain, about} = require('./windowmanager');

function sendAction(action) {
	const win = BrowserWindow.getAllWindows()[0];

	if (process.platform === 'darwin') {
		win.restore();
	}

	win.webContents.send(action);
}

function clearCache() {
	const win = BrowserWindow.getAllWindows()[0];
	const ses = win.webContents.session;
	ses.clearCache(function(){
		dialog.showMessageBox({type:"info",buttons:[], message: "Cache cleared!"});
	});
}

const viewSubmenu = [
	{
		label: 'Reload',
		click(item, focusedWindow) {
			if (focusedWindow) {
				focusedWindow.reload();
			}
		}
	},
	{
		type: 'separator'
	},
	{
		role: 'togglefullscreen'
	},
	{
		label: 'Zoom In',
		accelerator: 'CommandOrControl+=',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomIn');
			}
		}
	},
	{
		label: 'Zoom Out',
		accelerator: 'CommandOrControl+-',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomOut');
			}
		}
	},
	{
		label: 'Actual Size',
		accelerator: 'CommandOrControl+0',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomActualSize');
			}
		}
	},
	{
		type: 'separator'
	},
	{
		label: 'Toggle Developer Tools',
		accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
		click(item, focusedWindow) {
			if (focusedWindow) {
				focusedWindow.webContents.toggleDevTools();
			}
		}
	}
];

const helpSubmenu = [
	{
		label: `${appName} Website`,
		click() {
			shell.openExternal('https://zulip.org');
		}
	},
	{
		label: `${appName + 'Desktop'} - ${app.getVersion()}`,
		enabled: false
	},
	{
		label: 'Clear Cache',
		click() {
			clearCache();
		}
	},
	{
		label: 'Report an Issue...',
		click() {
			const body = `
<!-- Please succinctly describe your issue and steps to reproduce it. -->
-
${app.getName()} ${app.getVersion()}
Electron ${process.versions.electron}
${process.platform} ${process.arch} ${os.release()}`;

			shell.openExternal(`https://github.com/zulip/zulip-electron/issues/new?body=${encodeURIComponent(body)}`);
		}
	}
];

const darwinTpl = [

	{
		label: `${app.getName()}`,
		submenu: [
			{
				label: 'Zulip desktop',
				click() {
					about();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Change Zulip Server',
				accelerator: 'Cmd+,',
				click() {
					addDomain();
				}
			},
			{
				label: 'Keyboard shortcuts',
				accelerator: 'Cmd+K',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('shortcut');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Log Out',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('log-out');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'undo'
			},
			{
				role: 'redo'
			},
			{
				type: 'separator'
			},
			{
				role: 'cut'
			},
			{
				role: 'copy'
			},
			{
				role: 'paste'
			},
			{
				role: 'pasteandmatchstyle'
			},
			{
				role: 'delete'
			},
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: viewSubmenu
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			},
			{
				type: 'separator'
			},
			{
				role: 'front'
			}
		]
	},
	{
		role: 'help',
		submenu: helpSubmenu
	}
];

const otherTpl = [
	{
		label: 'File',
		submenu: [
			{
				label: 'Zulip desktop',
				click() {
					about();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Change Zulip Server',
				accelerator: 'Ctrl+,',
				click() {
					addDomain();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Keyboard shortcuts',
				accelerator: 'Ctrl+K',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('shortcut');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Log Out',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('log-out');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'undo'
			},
			{
				role: 'redo'
			},
			{
				type: 'separator'
			},
			{
				role: 'cut'
			},
			{
				role: 'copy'
			},
			{
				role: 'paste'
			},
			{
				role: 'pasteandmatchstyle'
			},
			{
				role: 'delete'
			},
			{
				type: 'separator'
			},
			{
				role: 'selectall'
			}

		]
	},
	{
		label: 'View',
		submenu: viewSubmenu
	},
	{
		role: 'help',
		submenu: helpSubmenu
	}
];

const tpl = process.platform === 'darwin' ? darwinTpl : otherTpl;

module.exports = electron.Menu.buildFromTemplate(tpl);
<commit_msg>Added clear cache option<commit_after>'use strict';
const os = require('os');
const electron = require('electron');
const {dialog} = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const shell = electron.shell;
const appName = app.getName();

const {addDomain, about} = require('./windowmanager');

function sendAction(action) {
	const win = BrowserWindow.getAllWindows()[0];

	if (process.platform === 'darwin') {
		win.restore();
	}

	win.webContents.send(action);
}

function clearCache() {
	const win = BrowserWindow.getAllWindows()[0];
	const ses = win.webContents.session;
	ses.clearCache(function(){
		dialog.showMessageBox({type:"info",buttons:[], message: "Cache cleared!"});
	});
}

const viewSubmenu = [
	{
		label: 'Reload',
		click(item, focusedWindow) {
			if (focusedWindow) {
				focusedWindow.reload();
			}
		}
	},
	{
		type: 'separator'
	},
	{
		role: 'togglefullscreen'
	},
	{
		label: 'Zoom In',
		accelerator: 'CommandOrControl+=',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomIn');
			}
		}
	},
	{
		label: 'Zoom Out',
		accelerator: 'CommandOrControl+-',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomOut');
			}
		}
	},
	{
		label: 'Actual Size',
		accelerator: 'CommandOrControl+0',
		click(item, focusedWindow) {
			if (focusedWindow) {
				sendAction('zoomActualSize');
			}
		}
	},
	{
		type: 'separator'
	},
	{
		label: 'Toggle Developer Tools',
		accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
		click(item, focusedWindow) {
			if (focusedWindow) {
				focusedWindow.webContents.toggleDevTools();
			}
		}
	}
];

const helpSubmenu = [
	{
		label: `${appName} Website`,
		click() {
			shell.openExternal('https://zulip.org');
		}
	},
	{
		label: `${appName + 'Desktop'} - ${app.getVersion()}`,
		enabled: false
	},
	{
		label: 'Report an Issue...',
		click() {
			const body = `
<!-- Please succinctly describe your issue and steps to reproduce it. -->
-
${app.getName()} ${app.getVersion()}
Electron ${process.versions.electron}
${process.platform} ${process.arch} ${os.release()}`;

			shell.openExternal(`https://github.com/zulip/zulip-electron/issues/new?body=${encodeURIComponent(body)}`);
		}
	}
];

const darwinTpl = [

	{
		label: `${app.getName()}`,
		submenu: [
			{
				label: 'Zulip desktop',
				click() {
					about();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Change Zulip Server',
				accelerator: 'Cmd+,',
				click() {
					addDomain();
				}
			},
			{
				label: 'Keyboard shortcuts',
				accelerator: 'Cmd+K',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('shortcut');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Clear Cache',
				click() {
					clearCache();
				}
			},
			{
				label: 'Log Out',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('log-out');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'undo'
			},
			{
				role: 'redo'
			},
			{
				type: 'separator'
			},
			{
				role: 'cut'
			},
			{
				role: 'copy'
			},
			{
				role: 'paste'
			},
			{
				role: 'pasteandmatchstyle'
			},
			{
				role: 'delete'
			},
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: viewSubmenu
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			},
			{
				type: 'separator'
			},
			{
				role: 'front'
			}
		]
	},
	{
		role: 'help',
		submenu: helpSubmenu
	}
];

const otherTpl = [
	{
		label: 'File',
		submenu: [
			{
				label: 'Zulip desktop',
				click() {
					about();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Change Zulip Server',
				accelerator: 'Ctrl+,',
				click() {
					addDomain();
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Keyboard shortcuts',
				accelerator: 'Ctrl+K',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('shortcut');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				label: 'Clear Cache',
				click() {
					clearCache();
				}
			},
			{
				label: 'Log Out',
				click(item, focusedWindow) {
					if (focusedWindow) {
						sendAction('log-out');
					}
				}
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'undo'
			},
			{
				role: 'redo'
			},
			{
				type: 'separator'
			},
			{
				role: 'cut'
			},
			{
				role: 'copy'
			},
			{
				role: 'paste'
			},
			{
				role: 'pasteandmatchstyle'
			},
			{
				role: 'delete'
			},
			{
				type: 'separator'
			},
			{
				role: 'selectall'
			}

		]
	},
	{
		label: 'View',
		submenu: viewSubmenu
	},
	{
		role: 'help',
		submenu: helpSubmenu
	}
];

const tpl = process.platform === 'darwin' ? darwinTpl : otherTpl;

module.exports = electron.Menu.buildFromTemplate(tpl);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
// var winston = require('winston');
//
// var logger = new (winston.Logger)({
//     transports: [
//         new (winston.transports.File)({ filename: '/root/concepts-json/node_modules/sct-snapshot-rest-api/search.log' })
//     ]
// });

router.get('/', function(req, res) {
    var uri=req.query.uri;
    console.log("uri:" + uri);
    // var bar=req.query.uri.lastIndexOf("/");
    // var id=uristr.substring(bar + 1);
    // var format="json";
    // if (req.query.format) {
    //     format = req.query.format.toLowerCase();
    // }
    // console.log("format:" + format);
    // console.log("id:" + id);
    // if (format=="json"){
    //     var db=process.env.TS_MONGO_DB;
    //     var collection=process.env.TS_MONGO_COLLECTION;
    //     console.log("db:" + db + " , collection:" + collection);
    //     req.url="/" + db + "/" + collection + "/concepts/" + id;
    //     return app._router.handle(req, res, next);
    // }else{
    //     req.url="http://ihmi.termspace.com/?perspective=full&conceptId1=" + id + "&edition=en-edition&release=v20180731&langRefset=900000000000509007";
    //
    //     return app._router.handle(req, res, next);
    // }

});
module.exports = router;
<commit_msg>testing redirection<commit_after>var express = require('express');
var router = express.Router();
var winston = require('winston');

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({ filename: '/root/concepts-json/node_modules/sct-snapshot-rest-api/search.log' })
    ]
});

router.get('/', function(req, res) {
    var uri=req.query.uri;
    console.log("uri:" + uri);
    if (uri.indexOf("http://snomed.info/")<0){

        res.status(400);
        res.send("{Error:400, message:'system not found'}");
        return ;
    }
    var bar=req.query.uri.lastIndexOf("/");
    var id=uristr.substring(bar + 1);
    var format="json";
    if (req.query.format) {
        format = req.query.format.toLowerCase();
    }
    console.log("format:" + format);
    console.log("id:" + id);
    if (format=="json"){
        var db=process.env.TS_MONGO_DB;
        var collection=process.env.TS_MONGO_COLLECTION;
        console.log("db:" + db + " , collection:" + collection);
        req.url="/" + db + "/" + collection + "/concepts/" + id;
        return app._router.handle(req, res, next);
    }else{
        req.url="http://ihmi.termspace.com/?perspective=full&conceptId1=" + id + "&edition=en-edition&release=v20180731&langRefset=900000000000509007";

        return app._router.handle(req, res, next);
    }

});
module.exports = router;
<|endoftext|>


<commit_before>var utils = require('../../../utils');

/**
 * Utility methods for Sprite/Texture tinting.
 * @static
 * @class
 * @memberof PIXI
 */
var CanvasTinter = {};
module.exports = CanvasTinter;

/**
 * Basically this method just needs a sprite and a color and tints the sprite with the given color.
 *
 * @param sprite {Sprite} the sprite to tint
 * @param color {number} the color to use to tint the sprite with
 * @return {HTMLCanvasElement} The tinted canvas
 */
CanvasTinter.getTintedTexture = function (sprite, color)
{
    var texture = sprite.texture;

    color = CanvasTinter.roundColor(color);

    var stringColor = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);

    texture.tintCache = texture.tintCache || {};

    if (texture.tintCache[stringColor])
    {
        return texture.tintCache[stringColor];
    }

     // clone texture..
    var canvas = CanvasTinter.canvas || document.createElement('canvas');

    //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
    CanvasTinter.tintMethod(texture, color, canvas);

    if (CanvasTinter.convertTintToImage)
    {
        // is this better?
        var tintImage = new Image();
        tintImage.src = canvas.toDataURL();

        texture.tintCache[stringColor] = tintImage;
    }
    else
    {
        texture.tintCache[stringColor] = canvas;
        // if we are not converting the texture to an image then we need to lose the reference to the canvas
        CanvasTinter.canvas = null;
    }

    return canvas;
};

/**
 * Tint a texture using the 'multiply' operation.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithMultiply = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var crop = texture.crop;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);

    context.fillRect(0, 0, crop.width, crop.height);

    context.globalCompositeOperation = 'multiply';

    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    context.globalCompositeOperation = 'destination-atop';

    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );
};

/**
 * Tint a texture using the 'overlay' operation.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithOverlay = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var crop = texture.crop;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.globalCompositeOperation = 'copy';
    context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);
    context.fillRect(0, 0, crop.width, crop.height);

    context.globalCompositeOperation = 'destination-atop';
    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    // context.globalCompositeOperation = 'copy';
};

/**
 * Tint a texture pixel per pixel.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithPerPixel = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var crop = texture.crop;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.globalCompositeOperation = 'copy';
    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    var rgbValues = utils.hex2rgb(color);
    var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];

    var pixelData = context.getImageData(0, 0, crop.width, crop.height);

    var pixels = pixelData.data;

    for (var i = 0; i < pixels.length; i += 4)
    {
        pixels[i+0] *= r;
        pixels[i+1] *= g;
        pixels[i+2] *= b;
    }

    context.putImageData(pixelData, 0, 0);
};

/**
 * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel.
 *
 * @param color {number} the color to round, should be a hex color
 */
CanvasTinter.roundColor = function (color)
{
    var step = CanvasTinter.cacheStepsPerColorChannel;

    var rgbValues = utils.hex2rgb(color);

    rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
    rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
    rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);

    return utils.rgb2hex(rgbValues);
};

/**
 * Number of steps which will be used as a cap when rounding colors.
 *
 * @member
 */
CanvasTinter.cacheStepsPerColorChannel = 8;

/**
 * Tint cache boolean flag.
 *
 * @member
 */
CanvasTinter.convertTintToImage = false;

/**
 * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
 *
 * @member
 */
CanvasTinter.canUseMultiply = utils.canUseNewCanvasBlendModes();

/**
 * The tinting method that will be used.
 *
 */
CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply :  CanvasTinter.tintWithPerPixel;
<commit_msg>Cherry picking.<commit_after>var utils = require('../../../utils');

/**
 * Utility methods for Sprite/Texture tinting.
 * @static
 * @class
 * @memberof PIXI
 */
var CanvasTinter = {};
module.exports = CanvasTinter;

/**
 * Basically this method just needs a sprite and a color and tints the sprite with the given color.
 *
 * @param sprite {Sprite} the sprite to tint
 * @param color {number} the color to use to tint the sprite with
 * @return {HTMLCanvasElement} The tinted canvas
 */
CanvasTinter.getTintedTexture = function (sprite, color)
{
    var texture = sprite.texture;

    color = CanvasTinter.roundColor(color);

    var stringColor = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);

    texture.tintCache = texture.tintCache || {};

    if (texture.tintCache[stringColor])
    {
        return texture.tintCache[stringColor];
    }

     // clone texture..
    var canvas = CanvasTinter.canvas || document.createElement('canvas');

    //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
    CanvasTinter.tintMethod(texture, color, canvas);

    if (CanvasTinter.convertTintToImage)
    {
        // is this better?
        var tintImage = new Image();
        tintImage.src = canvas.toDataURL();

        texture.tintCache[stringColor] = tintImage;
    }
    else
    {
        texture.tintCache[stringColor] = canvas;
        // if we are not converting the texture to an image then we need to lose the reference to the canvas
        CanvasTinter.canvas = null;
    }

    return canvas;
};

/**
 * Tint a texture using the 'multiply' operation.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithMultiply = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var resolution = texture.baseTexture.resolution;

    var crop = texture.crop.clone();
    crop.x *= resolution;
    crop.y *= resolution;
    crop.width *= resolution
    crop.height *= resolution;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);

    context.fillRect(0, 0, crop.width, crop.height);

    context.globalCompositeOperation = 'multiply';

    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    context.globalCompositeOperation = 'destination-atop';

    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );
};

/**
 * Tint a texture using the 'overlay' operation.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithOverlay = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var resolution = texture.baseTexture.resolution;

    var crop = texture.crop.clone();
    crop.x *= resolution;
    crop.y *= resolution;
    crop.width *= resolution
    crop.height *= resolution;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.globalCompositeOperation = 'copy';
    context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6);
    context.fillRect(0, 0, crop.width, crop.height);

    context.globalCompositeOperation = 'destination-atop';
    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    // context.globalCompositeOperation = 'copy';
};

/**
 * Tint a texture pixel per pixel.
 *
 * @param texture {Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */
CanvasTinter.tintWithPerPixel = function (texture, color, canvas)
{
    var context = canvas.getContext( '2d' );

    var resolution = texture.baseTexture.resolution;

    var crop = texture.crop.clone();
    crop.x *= resolution;
    crop.y *= resolution;
    crop.width *= resolution
    crop.height *= resolution;

    canvas.width = crop.width;
    canvas.height = crop.height;

    context.globalCompositeOperation = 'copy';
    context.drawImage(
        texture.baseTexture.source,
        crop.x,
        crop.y,
        crop.width,
        crop.height,
        0,
        0,
        crop.width,
        crop.height
    );

    var rgbValues = utils.hex2rgb(color);
    var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];

    var pixelData = context.getImageData(0, 0, crop.width, crop.height);

    var pixels = pixelData.data;

    for (var i = 0; i < pixels.length; i += 4)
    {
        pixels[i+0] *= r;
        pixels[i+1] *= g;
        pixels[i+2] *= b;
    }

    context.putImageData(pixelData, 0, 0);
};

/**
 * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel.
 *
 * @param color {number} the color to round, should be a hex color
 */
CanvasTinter.roundColor = function (color)
{
    var step = CanvasTinter.cacheStepsPerColorChannel;

    var rgbValues = utils.hex2rgb(color);

    rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
    rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
    rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);

    return utils.rgb2hex(rgbValues);
};

/**
 * Number of steps which will be used as a cap when rounding colors.
 *
 * @member
 */
CanvasTinter.cacheStepsPerColorChannel = 8;

/**
 * Tint cache boolean flag.
 *
 * @member
 */
CanvasTinter.convertTintToImage = false;

/**
 * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
 *
 * @member
 */
CanvasTinter.canUseMultiply = utils.canUseNewCanvasBlendModes();

/**
 * The tinting method that will be used.
 *
 */
CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply :  CanvasTinter.tintWithPerPixel;
<|endoftext|>


<commit_before>var Config = require("./config");
var mongoose = require('mongoose');

/*
 * Mongoose by default sets the auto_reconnect option to true.
 * We recommend setting socket options at both the server and replica set level.
 * We recommend a 30 second connection timeout because it allows for
 * plenty of time in most operating environments.
 */
var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
                replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };

//REMOTE DB
// mongoose.connect(Config.database.dburl, options);

//LOCAL DB
mongoose.connect('mongodb://127.0.0.1:27017/camunity');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function (callback) {
	console.log("database connection successful");
});<commit_msg>remote db again<commit_after>var Config = require("./config");
var mongoose = require('mongoose');

/*
 * Mongoose by default sets the auto_reconnect option to true.
 * We recommend setting socket options at both the server and replica set level.
 * We recommend a 30 second connection timeout because it allows for
 * plenty of time in most operating environments.
 */
var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
                replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };

//REMOTE DB
mongoose.connect(Config.database.dburl, options);

//LOCAL DB
// mongoose.connect('mongodb://127.0.0.1:27017/camunity');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function (callback) {
	console.log("database connection successful");
});<|endoftext|>


<commit_before><commit_msg>[fuchun] #Tech add sql script<commit_after>
const dateEq = () => {

}

const dateNotEq = () => {

}

const dateInclude = () => {

}

const textRange = () => {

}

module.exports = {
  dateEq,
  dateNotEq,
  dateInclude,
  textRange
}<|endoftext|>


<commit_before>
import io from 'socket.io';
import dl from 'delivery';
import fs from 'fs';

function getPeers() {
  // get list of n best peers

  return 0;
}

function sendShred() {
  // send shred to specific host

  return 0;
}

function receiveShred() {
  // open channel/socket to receive a shred

  // 5001 could be any random port else given that kadmelia gives the sender that random port
  const listener = io.listen(5001);

  listener.sockets.on('connection', (socket) => {
    const delivery = dl.listen(socket);
    delivery.on('receive.success', (file) => {
      fs.writeFile(file.name, file.buffer, (err) => {
        if (err) {
          console.log('File could not be saved: ', err);
        } else {
          console.log('File ', file.name, ' saved');
        }
      });
    });
  });

  return 0;
}

export { getPeers, sendShred, receiveShred };
<commit_msg>add file transfer functionality<commit_after>
import socketio from 'socket.io';
import socketclient from 'socket.io-client';
import dl from 'delivery';
import fs from 'fs';

function getPeers() {
  // get list of n best peers

  return 0;
}

function sendShred(ip, port, filename, filepath) {
  const address = `http://${ip}:${port}`;
  const socket = socketclient(address);

  // send shred to specific host
  socket.on('connect', () => {
    const delivery = dl.listen(socket);

    delivery.connect();

    delivery.on('delivery.connect', (delivery2) => {
      delivery2.send({
        name: filename,
        path: filepath
      });
    });

    delivery.on('send.success', (file) => {
      console.log(`File: ${file} sent successfully!`);
    });
  });

  return 0;
}

function receiveShred() {
  // open channel/socket to receive a shred

  // 5001 could be any random port else given that kadmelia gives the sender that random port
  const listener = socketio.listen(5001);

  listener.sockets.on('connection', (socket) => {
    const delivery = dl.listen(socket);
    delivery.on('receive.success', (file) => {
      fs.writeFile(file.name, file.buffer, (err) => {
        if (err) {
          console.log('File could not be saved: ', err);
        } else {
          console.log('File ', file.name, ' saved');
        }
      });
    });
  });

  return 0;
}

export { getPeers, sendShred, receiveShred };
<|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates correctly formatted tooltip for Apps
//-------------------------------------------------------------------
d3plus.tooltip.app = function(params) {

  var vars = params.vars,
      d = params.data,
      ex = params.ex,
      mouse = params.mouseevents ? params.mouseevents : false,
      arrow = params.arrow ? params.arrow : true

  if (d3.event.type == "click" && (vars.tooltip.html || vars.tooltip.value.long)) {
    var fullscreen = true,
        arrow = false,
        mouse = true,
        length = "long",
        footer = vars.footer.value

    vars.covered = true
  }
  else {
    var fullscreen = false,
        align = vars.style.tooltip.anchor,
        length = "short",
        footer = vars.footer_text()
  }

  if (params.x) {
    var x = params.x
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var x = d3.event.clientX
  }
  else {
    var x = d.d3plus.x
  }

  if (params.y) {
    var y = params.y
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var y = d3.event.clientY
  }
  else {
    var y = d.d3plus.y
  }

  if (params.offset) {
    var offset = params.offset
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var offset = 3
  }
  else {
    var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2
  }

  function make_tooltip(html) {

    var active = vars.active.key ? d3plus.variable.value(vars,d,vars.active.key) : d.d3plus.active,
        total = vars.total.key ? d3plus.variable.value(vars,d,vars.total.key) : d.d3plus.total

    if (active > 1 && active != total) {
      if (!ex) ex = {}
      ex.fill = active+"/"+total+" ("+vars.format((active/total)*100,"share")+"%)"
    }
    else if (d.d3plus.share) {
      if (!ex) ex = {}
      ex.share = vars.format(d.d3plus.share*100,"share")+"%"
    }

    var icon = d3plus.variable.value(vars,d,vars.icon.key),
        title = d3plus.variable.value(vars,d,vars.text.key),
        tooltip_data = d3plus.tooltip.data(vars,d,length,ex),
        id = d3plus.variable.value(vars,d,vars.id.key)

    if (!title) {
      title = id
    }

    d3plus.tooltip.create({
      "align": align,
      "arrow": arrow,
      "background": vars.style.tooltip.background,
      "fontcolor": vars.style.tooltip.font.color,
      "fontfamily": vars.style.tooltip.font.family,
      "fontweight": vars.style.tooltip.font.weight,
      "data": tooltip_data,
      "color": d3plus.variable.color(vars,d),
      "footer": footer,
      "fullscreen": fullscreen,
      "html": html,
      "icon": icon,
      "id": vars.type.value,
      "mouseevents": mouse,
      "offset": offset,
      "parent": vars.parent,
      "style": vars.style.icon,
      "title": title,
      "x": x,
      "y": y,
      "rtl": vars.style.labels.dir == "rtl"
    })

  }

  if (fullscreen) {

    if (typeof vars.tooltip.html == "string") {
      make_tooltip(vars.tooltip.html)
    }
    else if (typeof vars.tooltip.html == "function") {
      make_tooltip(vars.tooltip.html(id))
    }
    else if (vars.tooltip.html && typeof vars.tooltip.html == "object" && vars.tooltip.html.url) {
      d3.json(vars.tooltip.html.url,function(data){
        var html = vars.tooltip.html.callback ? vars.tooltip.html.callback(data) : data
        make_tooltip(html)
      })
    }
    else {
      make_tooltip("")
    }

  }
  else {
    make_tooltip("")
  }

}
<commit_msg>using new .html() method<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates correctly formatted tooltip for Apps
//-------------------------------------------------------------------
d3plus.tooltip.app = function(params) {

  var vars = params.vars,
      d = params.data,
      ex = params.ex,
      mouse = params.mouseevents ? params.mouseevents : false,
      arrow = params.arrow ? params.arrow : true

  if (d3.event.type == "click" && (vars.html.value || vars.tooltip.value.long)) {
    var fullscreen = true,
        arrow = false,
        mouse = true,
        length = "long",
        footer = vars.footer.value

    vars.covered = true
  }
  else {
    var fullscreen = false,
        align = vars.style.tooltip.anchor,
        length = "short",
        footer = vars.footer_text()
  }

  if (params.x) {
    var x = params.x
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var x = d3.event.clientX
  }
  else {
    var x = d.d3plus.x
  }

  if (params.y) {
    var y = params.y
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var y = d3.event.clientY
  }
  else {
    var y = d.d3plus.y
  }

  if (params.offset) {
    var offset = params.offset
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var offset = 3
  }
  else {
    var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2
  }

  function make_tooltip(html) {

    var active = vars.active.key ? d3plus.variable.value(vars,d,vars.active.key) : d.d3plus.active,
        total = vars.total.key ? d3plus.variable.value(vars,d,vars.total.key) : d.d3plus.total

    if (active > 1 && active != total) {
      if (!ex) ex = {}
      ex.fill = active+"/"+total+" ("+vars.format((active/total)*100,"share")+"%)"
    }
    else if (d.d3plus.share) {
      if (!ex) ex = {}
      ex.share = vars.format(d.d3plus.share*100,"share")+"%"
    }

    var icon = d3plus.variable.value(vars,d,vars.icon.key),
        title = d3plus.variable.value(vars,d,vars.text.key),
        tooltip_data = d3plus.tooltip.data(vars,d,length,ex),
        id = d3plus.variable.value(vars,d,vars.id.key)

    if (!title) {
      title = id
    }

    d3plus.tooltip.create({
      "align": align,
      "arrow": arrow,
      "background": vars.style.tooltip.background,
      "fontcolor": vars.style.tooltip.font.color,
      "fontfamily": vars.style.tooltip.font.family,
      "fontweight": vars.style.tooltip.font.weight,
      "data": tooltip_data,
      "color": d3plus.variable.color(vars,d),
      "footer": footer,
      "fullscreen": fullscreen,
      "html": html,
      "icon": icon,
      "id": vars.type.value,
      "mouseevents": mouse,
      "offset": offset,
      "parent": vars.parent,
      "style": vars.style.icon,
      "title": title,
      "x": x,
      "y": y,
      "rtl": vars.style.labels.dir == "rtl"
    })

  }

  if (fullscreen) {

    if (typeof vars.html.value == "string") {
      make_tooltip(vars.html.value)
    }
    else if (typeof vars.html.value == "function") {
      make_tooltip(vars.html.value(id))
    }
    else if (vars.html.value && typeof vars.html.value == "object" && vars.html.value.url) {
      d3.json(vars.html.value.url,function(data){
        var html = vars.html.value.callback ? vars.html.value.callback(data) : data
        make_tooltip(html)
      })
    }
    else {
      make_tooltip("")
    }

  }
  else {
    make_tooltip("")
  }

}
<|endoftext|>


<commit_before>'use strict';

var Sinon = require('sinon'),
	Chai = require('chai'),
	expect = Chai.expect;

var _ = require('lodash');

var base = process.cwd();

var ConfigurableTaskRunnerFactory = require(base + '/src/core/configurable_runner_factory'),
	ConfigurableTaskFactory = require(base + '/src/core/configurable_task_factory'),
	Configuration = require(base + '/src/core/configuration'),
	ConfigurationError = require(base + '/src/core/configuration_error');

var createFakeStuff = require(base + '/test/fake/stuff'),
	FakeGulp = require(base + '/test/fake/gulp');

describe('Core', function () {
	describe('ConfigurableTaskFactory', function () {
		var gulp, factory;

		beforeEach(function() {
			var stuff = createFakeStuff(),
				registry = {
					register: function() {}
				};
			gulp = new FakeGulp();
			factory = new ConfigurableTaskFactory(gulp, stuff, new ConfigurableTaskRunnerFactory(stuff), registry);
		});

		describe('#create()', function () {
			var taskInfo, taskConfig, stream, configurableRunner;

			taskInfo = {
				name: 'configurable-task',
				visibility: Configuration.CONSTANT.VISIBILITY.NORMAL,
				runtime: Configuration.CONSTANT.RUNTIME.ALL
			};

			taskConfig = {
				name: 'taskConfig'
			};

			stream = {
				name: 'fake stream'
			};

			function done(err) {
			}

			beforeEach(function() {
				configurableRunner = Sinon.spy();
			});

			it('should return a ConfigurableTask (a function with run() method)', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				expect(actual).to.be.a('function');
				expect(actual.run).to.be.a('function');
				expect(actual.displayName).to.equal(taskInfo.name);
				expect(actual.visibility).to.equal(taskInfo.visibility);
				expect(actual.runtime).to.equal(taskInfo.runtime);
			});
			it('should return a ConfigurableTask with the given prefix name', function () {
				var prefix = 'dev:',
					actual = factory.create(prefix, taskInfo, taskConfig, configurableRunner);
				expect(actual.displayName).to.equal(prefix + taskInfo.name);
			});
			it('should invoke configurableRunner() when act as a gulp task', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.call(gulp, done);
				expect(configurableRunner.calledWith(gulp, taskConfig, null, done)).to.be.true;
			});
			it('should invoke configurableRunner() in run() method whe act as a configurable task', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.run(gulp, taskConfig, stream, done);
				expect(configurableRunner.calledWith(gulp, taskConfig, stream, done)).to.be.true;
			});
			it('should be able to inject value and resolve config at runtime when act as a configurable task', function () {
				var taskConfig = {
						template: 'inject-value: {{inject-value}}'
					},
					injectConfig = {
						'inject-value': 'resolved-value'
					},
					expectedConfig = {
						template: 'inject-value: resolved-value',
						'inject-value': 'resolved-value'
					};
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.run(gulp, injectConfig, stream, done);
				expect(configurableRunner.calledWith(gulp, expectedConfig, stream, done)).to.be.true;
			});
		});
		describe('#one()', function () {
			it('should resolve a recipe task', function () {
				var actual = factory.one('', 'recipe-task', {}, {});
				expect(actual).to.be.a('function');
			});
			it('should resolve a stream task', function () {
				var actual = factory.one('', 'stream-task', {}, {});
				expect(actual).to.be.a('function');
			});
			it('should resolve a non-existent task with sub-task configs to a merge stream task', function () {
				var actual = factory.one('', 'non-existent-stream-task-with-sub-task-configs', {
					'recipe-task': {},
					'stream-task': {},
					'non-existent-but-with-src-and-dest-defined': {
						src: 'src',
						dest: 'dist'
					}
				}, {});
				expect(actual).to.be.a('function');
			});
			it('should throw if can not resolve to a task', function () {
				expect(function () { factory.one('', 'non-existent', {}, {}) }).to.throw(ConfigurationError);
			});
		});
		describe('#multiple()', function () {
			it('should process each config defined in subTaskConfigs', function () {
				Sinon.spy(factory, 'one');
				var actual = factory.multiple('', {
					'recipe-task': {},
					'stream-task': {}
				}, {});
				expect(factory.one.calledTwice).to.be.true;
				expect(actual).to.be.an('array');
				expect(actual.length).to.be.equal(2);
				factory.one.restore();
			});
		});
	});
});
<commit_msg>fix test for: allow empty task config infer to noop task<commit_after>'use strict';

var Sinon = require('sinon'),
	Chai = require('chai'),
	expect = Chai.expect;

var _ = require('lodash');

var base = process.cwd();

var ConfigurableTaskRunnerFactory = require(base + '/src/core/configurable_runner_factory'),
	ConfigurableTaskFactory = require(base + '/src/core/configurable_task_factory'),
	Configuration = require(base + '/src/core/configuration'),
	ConfigurationError = require(base + '/src/core/configuration_error');

var createFakeStuff = require(base + '/test/fake/stuff'),
	FakeGulp = require(base + '/test/fake/gulp');

describe('Core', function () {
	describe('ConfigurableTaskFactory', function () {
		var gulp, factory;

		beforeEach(function() {
			var stuff = createFakeStuff(),
				registry = {
					register: function() {}
				};
			gulp = new FakeGulp();
			factory = new ConfigurableTaskFactory(gulp, stuff, new ConfigurableTaskRunnerFactory(stuff), registry);
		});

		describe('#create()', function () {
			var taskInfo, taskConfig, stream, configurableRunner;

			taskInfo = {
				name: 'configurable-task',
				visibility: Configuration.CONSTANT.VISIBILITY.NORMAL,
				runtime: Configuration.CONSTANT.RUNTIME.ALL
			};

			taskConfig = {
				name: 'taskConfig'
			};

			stream = {
				name: 'fake stream'
			};

			function done(err) {
			}

			beforeEach(function() {
				configurableRunner = Sinon.spy();
			});

			it('should return a ConfigurableTask (a function with run() method)', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				expect(actual).to.be.a('function');
				expect(actual.run).to.be.a('function');
				expect(actual.displayName).to.equal(taskInfo.name);
				expect(actual.visibility).to.equal(taskInfo.visibility);
				expect(actual.runtime).to.equal(taskInfo.runtime);
			});
			it('should return a ConfigurableTask with the given prefix name', function () {
				var prefix = 'dev:',
					actual = factory.create(prefix, taskInfo, taskConfig, configurableRunner);
				expect(actual.displayName).to.equal(prefix + taskInfo.name);
			});
			it('should invoke configurableRunner() when act as a gulp task', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.call(gulp, done);
				expect(configurableRunner.calledWith(gulp, taskConfig, null, done)).to.be.true;
			});
			it('should invoke configurableRunner() in run() method whe act as a configurable task', function () {
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.run(gulp, taskConfig, stream, done);
				expect(configurableRunner.calledWith(gulp, taskConfig, stream, done)).to.be.true;
			});
			it('should be able to inject value and resolve config at runtime when act as a configurable task', function () {
				var taskConfig = {
						template: 'inject-value: {{inject-value}}'
					},
					injectConfig = {
						'inject-value': 'resolved-value'
					},
					expectedConfig = {
						template: 'inject-value: resolved-value',
						'inject-value': 'resolved-value'
					};
				var actual = factory.create('', taskInfo, taskConfig, configurableRunner);
				actual.run(gulp, injectConfig, stream, done);
				expect(configurableRunner.calledWith(gulp, expectedConfig, stream, done)).to.be.true;
			});
		});
		describe('#one()', function () {
			it('should resolve a recipe task', function () {
				var actual = factory.one('', 'recipe-task', {}, {});
				expect(actual).to.be.a('function');
			});
			it('should resolve a stream task', function () {
				var actual = factory.one('', 'stream-task', {}, {});
				expect(actual).to.be.a('function');
			});
			it('should resolve a non-existent task with sub-task configs to a merge stream task', function () {
				var actual = factory.one('', 'non-existent-stream-task-with-sub-task-configs', {
					'recipe-task': {},
					'stream-task': {},
					'non-existent-but-with-src-and-dest-defined': {
						src: 'src',
						dest: 'dist'
					}
				}, {});
				expect(actual).to.be.a('function');
			});
			it('should not throw even can not resolve to a task', function () {
				var actual = factory.one('', 'non-existent', {}, {});
				expect(actual).to.be.a('function');
			});
		});
		describe('#multiple()', function () {
			it('should process each config defined in subTaskConfigs', function () {
				Sinon.spy(factory, 'one');
				var actual = factory.multiple('', {
					'recipe-task': {},
					'stream-task': {}
				}, {});
				expect(factory.one.calledTwice).to.be.true;
				expect(actual).to.be.an('array');
				expect(actual.length).to.be.equal(2);
				factory.one.restore();
			});
		});
	});
});
<|endoftext|>


<commit_before>var config = require('./config.json');
var keystone = require('keystone');
var srs = require('secure-random-string');

keystone.init({

	'name': 'cocorico',
	'brand': 'cocorico',
	'admin path': 'admin',

	'views': 'templates/views',
	'view engine': 'jade',

	'wysiwyg images': true,
	'wysiwyg menubar': true,
	'wysiwyg additional plugins': 'table',

	'mongo' : config.mongo.uri,

	'auto update': false,
	'session': true,
	'auth': true,
	'user model': 'Admin',
	'cookie secret': srs(64)
});

keystone.import('models');

keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

keystone.set('routes', require('./routes'));
keystone.set('nav', {
	'apps': 'apps',
	'pages': 'pages',
	'votes': 'votes'
});

keystone.start();
<commit_msg>Group API models into categories on the admin home page.<commit_after>var config = require('./config.json');
var keystone = require('keystone');
var srs = require('secure-random-string');

keystone.init({

	'name': 'cocorico',
	'brand': 'cocorico',
	'admin path': 'admin',

	'views': 'templates/views',
	'view engine': 'jade',

	'wysiwyg images': true,
	'wysiwyg menubar': true,
	'wysiwyg additional plugins': 'table',

	'mongo' : config.mongo.uri,

	'auto update': false,
	'session': true,
	'auth': true,
	'user model': 'Admin',
	'cookie secret': srs(64)
});

keystone.import('models');

keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

keystone.set('routes', require('./routes'));
keystone.set('nav', {
	'apps': 'apps',
	'pages': ['Page', 'Media'],
	'votes': ['Vote', 'Ballot', 'Source', 'Like']
});

keystone.start();
<|endoftext|>


<commit_before>import React from 'react';
import Backbone from 'backbone';
import BootstrapModalMixin from 'components/mixins/BootstrapModalMixin.react';

export default React.createClass({
    displayName: "ExternalLinkDeleteModal",

    mixins: [BootstrapModalMixin],

    propTypes: {
          external_link: React.PropTypes.instanceOf(Backbone.Model).isRequired
    },

    //
    // Internal Modal Callbacks
    // ------------------------
    //

    cancel: function () {
      this.hide();
    },

    confirm: function () {
      this.hide();
      this.props.onConfirm();
    },

    //
    // Render
    // ------
    //

    renderBody: function () {
      var link = this.props.external_link;
      return (

            {"Are you sure you want to delete the link "}
            {link.get('name')}
            {"?"}

            {"The link will be destroyed and "}
            all data will be permanently lost
            {"."}

      );
    },

    render: function () {

      return (

                {this.renderCloseButton()}
                Delete Link

                {this.renderBody()}

                <button type="button" className="btn btn-danger" onClick={this.cancel}>
                  Cancel
                </button>
                <button type="button" className="btn btn-primary" onClick={this.confirm}>
                  Yes, delete this link
                </button>

      );
    }
});
<commit_msg>Remove harsh warning<commit_after>import React from 'react';
import Backbone from 'backbone';
import BootstrapModalMixin from 'components/mixins/BootstrapModalMixin.react';

export default React.createClass({
    displayName: "ExternalLinkDeleteModal",

    mixins: [BootstrapModalMixin],

    propTypes: {
          external_link: React.PropTypes.instanceOf(Backbone.Model).isRequired
    },

    //
    // Internal Modal Callbacks
    // ------------------------
    //

    cancel: function () {
      this.hide();
    },

    confirm: function () {
      this.hide();
      this.props.onConfirm();
    },

    //
    // Render
    // ------
    //

    renderBody: function () {
      var link = this.props.external_link;
      return (

            {"Are you sure you want to delete the link "}
            {link.get('name')}
            {"?"}

      );
    },

    render: function () {

      return (

                {this.renderCloseButton()}
                Delete Link

                {this.renderBody()}

                <button type="button" className="btn btn-danger" onClick={this.cancel}>
                  Cancel
                </button>
                <button type="button" className="btn btn-primary" onClick={this.confirm}>
                  Yes, delete this link
                </button>

      );
    }
});
<|endoftext|>


<commit_before>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the current theme
 */

$(document).ready(function() {
	// menu drop downs
	if (use_click_menu)
		$('#main_menu, ul.admin_menu, ul.sidebar_menu, ul.poster, ul.quickbuttons, #sort_by').superclick({speed: 150, animation: {opacity:'show', height:'toggle'}});
	else
		$('#main_menu, ul.admin_menu, ul.sidebar_menu, ul.poster, ul.quickbuttons, #sort_by').superfish({delay : 300, speed: 175});

	// Smooth scroll to top.
	$("a[href=#top]").bind("click", function(e) {
		e.preventDefault();
		$("html,body").animate({scrollTop: 0}, 1200);
	});

	// Smooth scroll to bottom.
	$("a[href=#bot]").bind("click", function(e) {
		e.preventDefault();

		// Don't scroll all the way down to the footer, just the content bottom
		var link = $('#bot'),
		link_y = link.height();

		$("html,body").animate({scrollTop:link.offset().top + link_y - $(window).height()}, 1200);
	});

	// Tooltips
	$('.preview').SiteTooltip({hoverIntent: {sensitivity: 10, interval: 750, timeout: 50}});

	// Find all nested linked images and turn off the border
	$('a.bbc_link img.bbc_img').parent().css('border', '0');

	// Fix code blocks
	if (typeof elk_codefix === 'function')
		elk_codefix();

	$('.expand_pages').expand_pages();

	// Collapsabile fieldsets, pure candy
	$('legend').click(function(){
		$(this).siblings().slideToggle("fast");
		$(this).parent().toggleClass("collapsed");
	}).each(function () {
		if ($(this).data('collapsed'))
		{
			$(this).siblings().css({display: "none"});
			$(this).parent().toggleClass("collapsed");
		}
	});

	// Spoiler
	$('.spoilerheader').click(function() {
		$(this).next().children().slideToggle("fast");
	});
});

// Toggles the element height and width styles of an image.
function elk_ToggleImageDimensions()
{
	var oImages = document.getElementsByTagName('IMG');
	for (oImage in oImages)
	{
		// Not a resized image? Skip it.
		if (oImages[oImage].className === undefined || oImages[oImage].className.indexOf('bbc_img resized') === -1)
			continue;

		oImages[oImage].style.cursor = 'pointer';
		oImages[oImage].onclick = function() {
			this.style.width = this.style.height = this.style.width === 'auto' ? null : 'auto';
		};
	}
}

// Add a load event for the function above.
addLoadEvent(elk_ToggleImageDimensions);

// Adds a button to a certain button strip.
function elk_addButton(sButtonStripId, bUseImage, oOptions)
{
	var oButtonStrip = document.getElementById(sButtonStripId);
	var aItems = oButtonStrip.getElementsByTagName('span');

	// Remove the 'last' class from the last item.
	if (aItems.length > 0)
	{
		var oLastSpan = aItems[aItems.length - 1];
		oLastSpan.className = oLastSpan.className.replace(/\s*last/, 'position_holder');
	}

	// Add the button.
	var oButtonStripList = oButtonStrip.getElementsByTagName('ul')[0];
	var oNewButton = document.createElement('li');
	var oRole = document.createAttribute('role');
	oRole.value = 'menuitem';
	oNewButton.setAttributeNode(oRole);

	if ('sId' in oOptions)
		oNewButton.id = oOptions.sId;
	setInnerHTML(oNewButton, '' + oOptions.sText + '');

	oButtonStripList.appendChild(oNewButton);
}<commit_msg>! I think that is a better toggle function for bbc images<commit_after>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the current theme
 */

$(document).ready(function() {
	// Menu drop downs
	if (use_click_menu)
		$('#main_menu, ul.admin_menu, ul.sidebar_menu, ul.poster, ul.quickbuttons, #sort_by').superclick({speed: 150, animation: {opacity:'show', height:'toggle'}});
	else
		$('#main_menu, ul.admin_menu, ul.sidebar_menu, ul.poster, ul.quickbuttons, #sort_by').superfish({delay : 300, speed: 175});

	// Smooth scroll to top.
	$("a[href=#top]").bind("click", function(e) {
		e.preventDefault();
		$("html,body").animate({scrollTop: 0}, 1200);
	});

	// Smooth scroll to bottom.
	$("a[href=#bot]").bind("click", function(e) {
		e.preventDefault();

		// Don't scroll all the way down to the footer, just the content bottom
		var link = $('#bot'),
		link_y = link.height();

		$("html,body").animate({scrollTop:link.offset().top + link_y - $(window).height()}, 1200);
	});

	// Tooltips
	$('.preview').SiteTooltip({hoverIntent: {sensitivity: 10, interval: 750, timeout: 50}});

	// Find all nested linked images and turn off the border
	$('a.bbc_link img.bbc_img').parent().css('border', '0');

	// Fix code blocks so they are as compact as possible
	if (typeof elk_codefix === 'function')
		elk_codefix();

	// Enable the ... page expansion
	$('.expand_pages').expand_pages();

	// Collapsabile fieldsets, pure candy
	$('legend').click(function(){
		$(this).siblings().slideToggle("fast");
		$(this).parent().toggleClass("collapsed");
	}).each(function () {
		if ($(this).data('collapsed'))
		{
			$(this).siblings().css({display: "none"});
			$(this).parent().toggleClass("collapsed");
		}
	});

	// Spoiler
	$('.spoilerheader').click(function() {
		$(this).next().children().slideToggle("fast");
	});

	// BBC [img] element toggle for height and width styles of an image.
	$('img').each(function() {
		// Not a resized image? Skip it.
		if ($(this).hasClass('bbc_img resized') === false)
			return true;

		$(this).css({'cursor': 'pointer'});
		$(this).click(function() {
			var $this = $(this),
				height,
				width;

			// No saved data, then lets set it to autp
			if ($.isEmptyObject($this.data()))
			{
				$this.data( "original", { width: $this.css('width'), height: $this.css('height')});
				$this.css({'width': $this.css('width') === 'auto' ? null : 'auto'});
				$this.css({'height': $this.css('width') === 'auto' ? null : 'auto'});
			}
			else
			{
				// Was clicked and saved, so set it back
				height = $this.data("original").height;
				width = $this.data("original").width;
				$this.css({'width': width});
				$this.css({'height': height});

				// Remove the data
				$this.removeData();
			}
		});
	});
});

// Adds a button to a certain button strip.
function elk_addButton(sButtonStripId, bUseImage, oOptions)
{
	var oButtonStrip = document.getElementById(sButtonStripId);
	var aItems = oButtonStrip.getElementsByTagName('span');

	// Remove the 'last' class from the last item.
	if (aItems.length > 0)
	{
		var oLastSpan = aItems[aItems.length - 1];
		oLastSpan.className = oLastSpan.className.replace(/\s*last/, 'position_holder');
	}

	// Add the button.
	var oButtonStripList = oButtonStrip.getElementsByTagName('ul')[0],
		oNewButton = document.createElement('li'),
		oRole = document.createAttribute('role');

	oRole.value = 'menuitem';
	oNewButton.setAttributeNode(oRole);

	if ('sId' in oOptions)
		oNewButton.id = oOptions.sId;
	setInnerHTML(oNewButton, '' + oOptions.sText + '');

	oButtonStripList.appendChild(oNewButton);
}<|endoftext|>


<commit_before>"use strict";

if (!jxcore.utils.OSInfo().isMobile) {
  return;
}

var tape = require('../lib/thali-tape');

test('Can call Start/StopListeningForAdvertisements', function (t) {
  Mobile('StartListeningForAdvertisements').callNative(function (err) {
    t.notOk(err, 'Can call StartListeningForAdvertisements without error');
    Mobile('StopListeningForAdvertisements').callNative(function (err) {
      t.notOk(err, 'Can call StopListeningForAdvertisements without error');
      t.end();
    });
  });
});

test('Calling StopListeningForAdvertisements before Start is an error', function (t) {
  Mobile('StopListeningForAdvertisements').callNative(function (err) {
    t.Ok(err, 'Calling Stop before Start is an error');
    t.end();
  });
});

test('Can call Start/StopUpdateAdvertisingAndListenForIncomingConnections', function (t) {
  Mobile('StartUpdateAdvertisingAndListenForIncomingConnections').callNative(function (err) {
    t.notOk(err, 'Can call StartUpdateAdvertisingAndListenForIncomingConnections without error');
    Mobile('Can StopUpdateAdvertisingAndListenForIncomingConnections').callNative(function (err) {
      t.notOk(err, 'Can call StopUpdateAdvertisingAndListenForIncomingConnections without error');
      t.end();
    });
  });
});

test('Calling StopUpdateAdvertisingAndListenForIncomingConnectionsStopUAALFIC before start is an error", function (t) {
  Mobile('StopUpdateAdvertisingAndListenForIncomingConnections').callNative(function (err) {
    t.notOk(err, 'Calling Stop before Start is an error');
    t.end();
  });
});
<commit_msg>Add fixture setup<commit_after>"use strict";

if (!jxcore.utils.OSInfo().isMobile) {
  return;
}

var tape = require('../lib/thali-tape');

var test = tape({
  setup: function(t) {
    t.end();
  },
  teardown: function(t) {
    t.end();
  }
});

test('Can call Start/StopListeningForAdvertisements', function (t) {
  Mobile('StartListeningForAdvertisements').callNative(function (err) {
    t.notOk(err, 'Can call StartListeningForAdvertisements without error');
    Mobile('StopListeningForAdvertisements').callNative(function (err) {
      t.notOk(err, 'Can call StopListeningForAdvertisements without error');
      t.end();
    });
  });
});

test('Calling StartListeningForAdvertisements twice is an error', function (t) {
  Mobile('StartListeningForAdvertisements').callNative(function (err) {
    t.notOk(err, 'Can call StartListeningForAdvertisements without error');
    Mobile('StartListeningForAdvertisements').callNative(function (err) {
      t.notOk(err == "Call Stop!", 'Calling Start twice is an error');
      t.end();
    });
  });
});
<|endoftext|>