<commit_before>export const extend = (matrixOps, overField) => {
  const ops = matrixOps;

  const extendBasis = (v, bs) => {
    const [nrows, ncols] = bs == null ? [0, v.length] : ops.shape(bs);
    if (v.length != ncols)
      throw Error("shapes don't match");

    let rowBs = 0;
    let colBs = 0;
    let colV = 0;

    while (rowBs < nrows && colBs < ncols) {
      const b = bs[rowBs];
      while (colBs < ncols && ops.eq(b[colBs], 0))
        ++colBs;

      while (colV < ncols && ops.eq(v[colV], 0))
        ++colV;

      if (colV < colBs || colV >= ncols || colBs >= ncols)
        break;
      else if (colV == colBs) {
        if (overField || ops.eq(0, ops.mod(v[colV], b[colV]))) {
          v = ops.minus(v, ops.times(b, ops.div(v[colV], b[colV])));
        }
        else {
          const [x, r, s, t, u] = ops.gcdex(b[colV], v[colV]);
          bs[rowBs] = ops.plus(ops.times(b, r), ops.times(v, s));
          if (ops.lt(ops.times(r, u), ops.times(s, t)))
            bs[rowBs] = ops.negative(bs[rowBs]);
          v = ops.plus(ops.times(b, t), ops.times(v, u));
        }
      }

      ++rowBs;
    }

    while (colV < ncols && ops.eq(v[colV], 0))
      ++colV;

    if (colV < ncols) {
      if ((nrows - rowBs) % 2 != 0)
        v = ops.negative(v);

      if (nrows == 0)
        return [v];
      else
        return bs.slice(0, rowBs).concat([v], bs.slice(rowBs));
    }
    else
      return bs;
  };

  const triangularBasis = rows => {
    let bs = null;
    for (const v of rows)
      bs = extendBasis(v, bs);
    return bs;
  };

  const rank = rows => {
    const bs = triangularBasis(rows);
    return bs == null ? 0 : bs.length;
  };

  const determinant = rows => {
    const [nrows, ncols] = ops.shape(rows);
    if (nrows != ncols)
      throw new Error('must be a square matrix');

    const bs = triangularBasis(rows);

    if (bs == null || bs.length < nrows)
      return 0;
    else
      return bs.map((v, i) => v[i]).reduce((a, x) => ops.times(a, x));
  };

  const reducedBasis = rows => {
    const div = overField ? ops.div : ops.idiv;
    const bs = triangularBasis(rows);

    if (bs == null)
      return null;

    let col = 0;
    for (let row = 0; row < bs.length; ++row) {
      while (ops.eq(bs[row][col], 0))
        ++col;

      if (ops.lt(bs[row][col], 0))
        bs[row] = ops.negative(bs[row]);

      if (overField && ops.ne(bs[row][col], 1))
        bs[row] = div(bs[row], bs[row][col]);

      const p = bs[row][col];

      for (let i = 0; i < row; ++i) {
        if (overField || ops.ge(bs[i][col], p) || ops.lt(bs[i][col], 0))
          bs[i] = ops.minus(bs[i], ops.times(bs[row], div(bs[i][col], p)));
      }
    }

    return bs;
  };

  const _solveDiophantine = (vec, val) => {
    if (vec.length == 1) {
      if (ops.eq(ops.mod(val, vec[0]), 0))
        return [ops.div(val, vec[0])];
      else
        return null;
    }
    else {
      const [x, a, b, c, d] = ops.gcdex(vec[0], vec[1]);
      const t = _solveDiophantine([x].concat(vec.slice(2)), val);

      if (t == null)
        return null;
      else
        return [ops.times(a, t[0]), ops.times(b, t[0])].concat(t.slice(1));
    }
  };

  const _leadingPositions = bs => {
    const result = [];

    if (bs != null) {
      let col = 0;
      for (let row = 0; row < bs.length; ++row) {
        while (ops.eq(bs[row][col], 0))
          ++col;
        result.push(col);
      }
    }

    return result;
  };

  const solve = (lft, rgt) => {
    const [rowsRgt, colsRgt] = ops.shape(lft);
    const [rowsLft, colsLft] = ops.shape(lft);
    if (rowsLft != rowsRgt)
      throw new Error('left and right side must have equal number of rows');

    const bs = reducedBasis(lft.map((v, i) => v.concat(rgt[i])));
    if (bs == null)
      return ops.matrix(rowsRgt, colsLft);

    const [rows, cols] = ops.shape(bs);
    const leading = _leadingPositions(bs);

    if (leading[rows - 1] >= colsLft)
      return null;

    leading.push(colsLft);

    const result = [];

    for (let j = colsLft; j < cols; ++j) {
      let out = [];

      for (let k = rows - 1; k >= 0; --k) {
        const b = bs[k];
        const [from, to] = [leading[k], leading[k + 1]];
        const s = ops.minus(b[j], ops.times(out, b.slice(to, colsLft)));

        if (overField) {
          out = ops.vector(to - from).concat(out);
          out[0] = ops.div(s, b[from]);
        }
        else {
          const w = _solveDiophantine(b.slice(from, to), s);
          if (w == null)
            return null;
          else
            out = w.concat(out);
        }
      }

      if (leading[0] > 0)
        out = ops.vector(leading[0]).concat(out);

      result.push(out);
    }

    return ops.transposed(result);
  };

  const leftNullSpace = mat => {
    const [nrows, ncols] = ops.shape(mat);
    const I = ops.identityMatrix(nrows);
    const ext = reducedBasis(mat.map((v, i) => v.concat(I[i])));
    const leading = _leadingPositions(ext);
    const k = leading.findIndex(x => x >= ncols);

    if (k >= 0)
      return ext.slice(k).map(v => v.slice(ncols));
    else
      return null;
  };

  const nullSpace = mat => {
    const lns = leftNullSpace(ops.transposed(mat));
    if (lns == null)
      return null;
    else
      return ops.transposed(lns);
  };

  const methods = {
    extendBasis: {
      Vector: {
        Null: extendBasis,
        Matrix: extendBasis
      }
    },

    triangularBasis: {
      Null: _ => null,
      Matrix: triangularBasis
    },

    reducedBasis: {
      Null: _ => null,
      Matrix: reducedBasis
    },

    rank: {
      Null: _ => 0,
      Matrix: rank
    },

    determinant: {
      Null: _ => 0,
      Matrix: determinant
    },

    solve: {
      Matrix: {
        Matrix: solve
      }
    },

    inverse: {
      Null: _ => null,
      Matrix: mat => solve(mat, ops.identityMatrix(ops.dimension(mat)))
    },

    leftNullSpace: {
      Null: _ => null,
      Matrix: leftNullSpace
    },

    nullSpace: {
      Null: _ => null,
      Matrix: nullSpace
    }
  };

  return ops.register(methods);
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  const types = require('./types');
  const ops = extend(types.rationalMatrices, false);

  const A = [[5,1,2],[10,8,5],[5,7,3]];
  const v = [[3],[7],[0]];
  const b = ops.times(A, v);

  console.log(`A = ${A}`);
  console.log(`v = ${v}`);
  console.log(`b := A * v = ${b}`);
  console.log(`A * x = b ~> x = ${ops.solve(A, b)}`);
}
<commit_msg>use a better solver over modules<commit_after>export const extend = (matrixOps, overField) => {
  const ops = matrixOps;

  const extendBasis = (v, bs) => {
    const [nrows, ncols] = bs == null ? [0, v.length] : ops.shape(bs);
    if (v.length != ncols)
      throw Error("shapes don't match");

    let rowBs = 0;
    let colBs = 0;
    let colV = 0;

    while (rowBs < nrows && colBs < ncols) {
      const b = bs[rowBs];
      while (colBs < ncols && ops.eq(b[colBs], 0))
        ++colBs;

      while (colV < ncols && ops.eq(v[colV], 0))
        ++colV;

      if (colV < colBs || colV >= ncols || colBs >= ncols)
        break;
      else if (colV == colBs) {
        if (overField || ops.eq(0, ops.mod(v[colV], b[colV]))) {
          v = ops.minus(v, ops.times(b, ops.div(v[colV], b[colV])));
        }
        else {
          const [x, r, s, t, u] = ops.gcdex(b[colV], v[colV]);
          bs[rowBs] = ops.plus(ops.times(b, r), ops.times(v, s));
          if (ops.lt(ops.times(r, u), ops.times(s, t)))
            bs[rowBs] = ops.negative(bs[rowBs]);
          v = ops.plus(ops.times(b, t), ops.times(v, u));
        }
      }

      ++rowBs;
    }

    while (colV < ncols && ops.eq(v[colV], 0))
      ++colV;

    if (colV < ncols) {
      if ((nrows - rowBs) % 2 != 0)
        v = ops.negative(v);

      if (nrows == 0)
        return [v];
      else
        return bs.slice(0, rowBs).concat([v], bs.slice(rowBs));
    }
    else
      return bs;
  };

  const triangularBasis = rows => {
    let bs = null;
    for (const v of rows)
      bs = extendBasis(v, bs);
    return bs;
  };

  const rank = rows => {
    const bs = triangularBasis(rows);
    return bs == null ? 0 : bs.length;
  };

  const determinant = rows => {
    const [nrows, ncols] = ops.shape(rows);
    if (nrows != ncols)
      throw new Error('must be a square matrix');

    const bs = triangularBasis(rows);

    if (bs == null || bs.length < nrows)
      return 0;
    else
      return bs.map((v, i) => v[i]).reduce((a, x) => ops.times(a, x));
  };

  const reducedBasis = rows => {
    const div = overField ? ops.div : ops.idiv;
    const bs = triangularBasis(rows);

    if (bs == null)
      return null;

    let col = 0;
    for (let row = 0; row < bs.length; ++row) {
      while (ops.eq(bs[row][col], 0))
        ++col;

      if (ops.lt(bs[row][col], 0))
        bs[row] = ops.negative(bs[row]);

      if (overField && ops.ne(bs[row][col], 1))
        bs[row] = div(bs[row], bs[row][col]);

      const p = bs[row][col];

      for (let i = 0; i < row; ++i) {
        if (overField || ops.ge(bs[i][col], p) || ops.lt(bs[i][col], 0))
          bs[i] = ops.minus(bs[i], ops.times(bs[row], div(bs[i][col], p)));
      }
    }

    return bs;
  };

  const _leadingPositions = bs => {
    const result = [];

    if (bs != null) {
      let col = 0;
      for (let row = 0; row < bs.length; ++row) {
        while (ops.eq(bs[row][col], 0))
          ++col;
        result.push(col);
      }
    }

    return result;
  };

  const _solveReducedOverField = (bs, colsLft) => {
    const [rows, cols] = ops.shape(bs);
    const leading = _leadingPositions(bs);

    if (leading[rows - 1] >= colsLft)
      return null;

    leading.push(colsLft);

    const result = [];

    for (let j = colsLft; j < cols; ++j) {
      let out = [];

      for (let k = rows - 1; k >= 0; --k) {
        const b = bs[k];
        const [from, to] = [leading[k], leading[k + 1]];
        const s = ops.minus(b[j], ops.times(out, b.slice(to, colsLft)));

        out = ops.vector(to - from).concat(out);
        out[0] = ops.div(s, b[from]);
      }

      if (leading[0] > 0)
        out = ops.vector(leading[0]).concat(out);

      result.push(out);
    }

    return ops.transposed(result);
  };

  const _solveReducedOverModule = (bs, m) => {
    const n = bs.length;
    const lft = bs.map(v => v.slice(0, m));
    const rgt = bs.map(v => v.slice(m));

    const I = ops.identityMatrix(m);
    const vs = reducedBasis(ops.transposed(lft).map((v, i) => v.concat(I[i])));
    const U = ops.transposed(vs).slice(n);
    const B = ops.transposed(vs.slice(0, n)).slice(0, n);
    const Binv = solve(B, ops.identityMatrix(n), true);
    const y = ops.times(Binv, rgt).concat(ops.matrix(m - n, rgt[0].length));

    if (y.every(v => v.every(x => ops.isInteger(x)))) // TODO generalize test
      return ops.times(U, y);
    else
      return null;
  };

  const solve = (lft, rgt, overField=true) => {
    const [rowsLft, colsLft] = ops.shape(lft);
    const [rowsRgt, colsRgt] = ops.shape(rgt);
    if (rowsLft != rowsRgt)
      throw new Error('left and right side must have equal number of rows');

    const bs = reducedBasis(lft.map((v, i) => v.concat(rgt[i])));

    if (bs == null)
      return ops.matrix(colsLft, colsRgt);
    else if (overField)
      return _solveReducedOverField(bs, colsLft);
    else
      return _solveReducedOverModule(bs, colsLft);
  };

  const leftNullSpace = mat => {
    const [nrows, ncols] = ops.shape(mat);
    const I = ops.identityMatrix(nrows);
    const ext = reducedBasis(mat.map((v, i) => v.concat(I[i])));
    const leading = _leadingPositions(ext);
    const k = leading.findIndex(x => x >= ncols);

    if (k >= 0)
      return ext.slice(k).map(v => v.slice(ncols));
    else
      return null;
  };

  const nullSpace = mat => {
    const lns = leftNullSpace(ops.transposed(mat));
    if (lns == null)
      return null;
    else
      return ops.transposed(lns);
  };

  const methods = {
    extendBasis: {
      Vector: {
        Null: extendBasis,
        Matrix: extendBasis
      }
    },

    triangularBasis: {
      Null: _ => null,
      Matrix: triangularBasis
    },

    reducedBasis: {
      Null: _ => null,
      Matrix: reducedBasis
    },

    rank: {
      Null: _ => 0,
      Matrix: rank
    },

    determinant: {
      Null: _ => 0,
      Matrix: determinant
    },

    solve: {
      Matrix: {
        Matrix: (lft, rgt) => solve(lft, rgt, overField)
      }
    },

    inverse: {
      Null: _ => null,
      Matrix: mat => solve(mat, ops.identityMatrix(mat.length), overField)
    },

    leftNullSpace: {
      Null: _ => null,
      Matrix: leftNullSpace
    },

    nullSpace: {
      Null: _ => null,
      Matrix: nullSpace
    }
  };

  return ops.register(methods);
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  const types = require('./types');
  const ops = extend(types.rationalMatrices, false);

  const test = (A, v) => {
    const b = ops.times(A, v);

    console.log(`A = ${A}`);
    console.log(`v = ${v}`);
    console.log(`b := A * v = ${b}`);

    const x = ops.solve(A, b);
    console.log(`A * x = b ~> x = ${x}`);
    console.log(`check A * x = ${ops.times(A, x)}`);

    console.log();
  };

  test([[5,1,2],[10,8,5],[5,7,3]], [[3],[7],[0]]);
  test([[5,1,2],[10,8,5],[5,7,3]], [[ops.div(3, 5)],[7],[0]]);
  test([[0,0,0],[ 0,0,0],[0,0,0]], [[0],[0],[0]]);
}
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')
const {app, Menu, shell, ipcMain} = require('electron')
const tray = require('./tray')
const appMenu = require('./menus')

const updater = require('./updater')
const analytics = require('./analytics')
const isPlatform = require('./../common/is-platform')
const window = require('./window.js')

const renderer = {
  styles: '../renderer/styles',
  js: '../renderer/js'
}

/**
 * Register Windows
 */

window.register('main', {
  url: 'https://www.instagram.com/',
  useLastState: true,
  fakeUserAgent: true,
  defaultWindowEvents: false,
  show: false,
  minHeight: 400,
  minWidth: 460,
  maxWidth: 550,
  maximizable: false,
  fullscreenable: false,
  titleBarStyle: 'hidden-inset',
  autoHideMenuBar: true,
  webPreferences: {
    preload: path.join(__dirname, renderer.js, 'index.js'),
    nodeIntegration: false
  }
})

window.register('preload', {
  url: path.join('file://', __dirname, '../renderer/html/preload.html'),
  useLastState: true,
  width: 200,
  height: 400,
  resizable: false,
  fullscreenable: false,
  maximizable: false,
  frame: false
})

/**
 * Singleton
 */
let shouldQuit = app.makeSingleInstance(() => {
  // Someone tried to run a second instance, we should focus our window.
  window.each(win => {
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()
    }
  })
})

if (shouldQuit && window.countOpen() > 0) {
  app.quit()
}

/**
 * Kick off!
 */
app.on('ready', () => {
  // Open preload window
  window.open('preload')

  // Open main window
  let mainWindow = window.open('main')
  setupWindowEvents(mainWindow)

  // Create menus
  Menu.setApplicationMenu(appMenu)
  tray.createTray(mainWindow)

  // Update and analytics
  updater.init(mainWindow)
  analytics.init()

  // Setup events
  setupWebContentsEvents(mainWindow.webContents)
})

app.on('activate', () => {
  window.get('main').show()
})

app.on('before-quit', () => {
  shouldQuit = true
})

/**
 * Communicate with renderer process (web page)
 */
ipcMain.on('back', (e, arg) => {
  let page = e.sender.webContents
  if (page.canGoBack()) {
    page.goBack()
  }
})

ipcMain.on('home', (e, arg) => {
  let page = e.sender.webContents
  page.loadURL('https://www.instagram.com/')
  page.clearHistory()
})

/**
 * setupWindowEvents
 */
function setupWindowEvents (win) {
  win.on('close', e => {
    if (!shouldQuit) {
      e.preventDefault()

      if (isPlatform('macOS')) {
        app.hide()
      } else {
        win.hide()
      }
    }
  })

  win.on('page-title-updated', e => {
    e.preventDefault()
  })
}

/**
 * mainWindowEvents
 */
function setupWebContentsEvents (page) {
  page.on('did-navigate-in-page', (event, arg) => {
    // Get back menu item and disable/enable it
    const menuBackBtn = appMenu.items[1].submenu.items[0]
    menuBackBtn.enabled = page.canGoBack()
    // Notify back-button in sidebar about the state change
    page.send('set-button-state', menuBackBtn.enabled)
  })

  // Inject styles when dom is ready
  page.on('dom-ready', () => {
    page.insertCSS(fs.readFileSync(path.join(__dirname, renderer.styles, 'app.css'), 'utf8'))
    page.insertCSS(fs.readFileSync(path.join(__dirname, renderer.styles, 'theme-dark/main.css'), 'utf8'))

    window.close('preload') // Close preload window
    window.get('main').show() // Show main window
  })

  // Open links in external applications
  page.on('new-window', (e, url) => {
    e.preventDefault()
    shell.openExternal(url)
  })
}
<commit_msg>Fix singleton Check if a window is visible in the singleton and show it if it is not. Remove check for window count with singleton to allow for proper functionality.<commit_after>const path = require('path')
const fs = require('fs')
const {app, Menu, shell, ipcMain} = require('electron')
const tray = require('./tray')
const appMenu = require('./menus')

const updater = require('./updater')
const analytics = require('./analytics')
const isPlatform = require('./../common/is-platform')
const window = require('./window.js')

const renderer = {
  styles: '../renderer/styles',
  js: '../renderer/js'
}

/**
 * Singleton
 */
let shouldQuit = app.makeSingleInstance(() => {
  // Someone tried to run a second instance, we should focus our window.
  window.each(win => {
    if (win) {
      if (!win.isVisible()) {
        win.show()
      } else {
        if (win.isMinimized()) win.restore()
        win.focus()
      }
    }
  })
})

if (shouldQuit) {
  app.quit()
}

/**
 * Register Windows
 */

window.register('main', {
  url: 'https://www.instagram.com/',
  useLastState: true,
  fakeUserAgent: true,
  defaultWindowEvents: false,
  show: false,
  minHeight: 400,
  minWidth: 460,
  maxWidth: 550,
  maximizable: false,
  fullscreenable: false,
  titleBarStyle: 'hidden-inset',
  autoHideMenuBar: true,
  webPreferences: {
    preload: path.join(__dirname, renderer.js, 'index.js'),
    nodeIntegration: false
  }
})

window.register('preload', {
  url: path.join('file://', __dirname, '../renderer/html/preload.html'),
  useLastState: true,
  width: 200,
  height: 400,
  resizable: false,
  fullscreenable: false,
  maximizable: false,
  frame: false
})

/**
 * Kick off!
 */
app.on('ready', () => {
  // Open preload window
  window.open('preload')

  // Open main window
  let mainWindow = window.open('main')
  setupWindowEvents(mainWindow)

  // Create menus
  Menu.setApplicationMenu(appMenu)
  tray.createTray(mainWindow)

  // Update and analytics
  updater.init(mainWindow)
  analytics.init()

  // Setup events
  setupWebContentsEvents(mainWindow.webContents)
})

app.on('activate', () => {
  window.get('main').show()
})

app.on('before-quit', () => {
  shouldQuit = true
})

/**
 * Communicate with renderer process (web page)
 */
ipcMain.on('back', (e, arg) => {
  let page = e.sender.webContents
  if (page.canGoBack()) {
    page.goBack()
  }
})

ipcMain.on('home', (e, arg) => {
  let page = e.sender.webContents
  page.loadURL('https://www.instagram.com/')
  page.clearHistory()
})

/**
 * setupWindowEvents
 */
function setupWindowEvents (win) {
  win.on('close', e => {
    if (!shouldQuit) {
      e.preventDefault()

      if (isPlatform('macOS')) {
        app.hide()
      } else {
        win.hide()
      }
    }
  })

  win.on('page-title-updated', e => {
    e.preventDefault()
  })
}

/**
 * mainWindowEvents
 */
function setupWebContentsEvents (page) {
  page.on('did-navigate-in-page', (event, arg) => {
    // Get back menu item and disable/enable it
    const menuBackBtn = appMenu.items[1].submenu.items[0]
    menuBackBtn.enabled = page.canGoBack()
    // Notify back-button in sidebar about the state change
    page.send('set-button-state', menuBackBtn.enabled)
  })

  // Inject styles when dom is ready
  page.on('dom-ready', () => {
    page.insertCSS(fs.readFileSync(path.join(__dirname, renderer.styles, 'app.css'), 'utf8'))
    page.insertCSS(fs.readFileSync(path.join(__dirname, renderer.styles, 'theme-dark/main.css'), 'utf8'))

    window.close('preload') // Close preload window
    window.get('main').show() // Show main window
  })

  // Open links in external applications
  page.on('new-window', (e, url) => {
    e.preventDefault()
    shell.openExternal(url)
  })
}
<|endoftext|>


<commit_before>chrome.browserAction.onClicked.addListener(pinCallback);

chrome.tabs.onCreated.addListener(newTabCallback);
<commit_msg>Comments to background.js<commit_after>// When new tab is created, add tab info to localStorage
chrome.tabs.onCreated.addListener(newTabCallback);

// When navigate to new URL, delete duplicate tabs

// When tab is deleted, remove tab info from localStorage

// Toggle pinning and unpinning with Omnibox icon
chrome.browserAction.onClicked.addListener(pinCallback);<|endoftext|>


<commit_before>// Copyright 2012 The Obvious Corporation.

/*
 * Modules used
 */

"use strict";

var assert = require("assert");
var events = require("events");

var Sink = require("../").Sink;

var EventCollector = require("./eventcoll").EventCollector;
var emit = require("./emit").emit;

/*
 * Tests
 */

/**
 * Make sure the constructor doesn't fail off the bat.
 */
function constructor() {
    new Sink(new events.EventEmitter());
}

/**
 * Test expected constructor failures.
 */
function needSource() {
    function f1() {
        new Sink();
    }
    assert.throws(f1, /Missing source/);

    function f2() {
        new Sink(["hello"]);
    }
    assert.throws(f2, /Source not an EventEmitter/);
}

/**
 * Test that no events get added spontaneously.
 */
function noInitialEvents() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    sink.pause();
    coll.listenAllCommon(sink);
    sink.resume();
    assert.equal(coll.events.length, 0);
}

/**
 * Test that `readable` is true until an end-type event comes through.
 */
function readableTransition() {
    tryWith(false, "end");
    tryWith(false, "close");
    tryWith(false, "error", new Error("criminy"));
    tryWith(true, "end");
    tryWith(true, "close");
    tryWith(true, "error", new Error("criminy"));

    function tryWith(pauseFirst, name, arg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        assert.ok(sink.readable);

        if (pauseFirst) {
            sink.pause();
        }

        emit(source, name, arg);

        if (pauseFirst) {
            assert.equal(coll.events.length, 0);
            assert.ok(sink.readable);
            sink.resume();
        }

        assert.equal(coll.events.length, (name === "error") ? 1 : 2);
        assert.ok(!sink.readable);
    }
}

/**
 * Test that no further events get emitted after an end-type event.
 */
function eventsAfterEnd() {
    tryWith(false, "end");
    tryWith(false, "close");
    tryWith(false, "error", new Error("oy"));
    tryWith(true, "end");
    tryWith(true, "close");
    tryWith(true, "error", new Error("oy"));

    function tryWith(extraData, name, arg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        emit(source, name, arg);
        assert.equal(coll.events.length, (name === "error") ? 1 : 2);
        coll.reset();

        if (extraData) {
            source.emit("data", "huzzah");
            assert.equal(coll.events.length, 0);
        }

        source.emit("end");
        assert.equal(coll.events.length, 0);

        source.emit("close");
        assert.equal(coll.events.length, 0);

        source.emit("error", new Error("eek"));
        assert.equal(coll.events.length, 0);
    }
}

/**
 * Test a few no-data-events cases.
 */
function noDataEvents() {
    tryWith("end", undefined);
    tryWith("close", undefined);
    tryWith("error", new Error("yow"));

    function tryWith(endEvent, endArg) {
        var isError = (endEvent === "error");
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        emit(source, endEvent, endArg);

        assert.equal(coll.events.length, isError ? 1 : 2);

        if (isError) {
            coll.assertEvent(0, sink, "error", [endArg]);
        } else {
            coll.assertEvent(0, sink, "end", undefined);
            coll.assertEvent(1, sink, "close", undefined);
        }
    }
}

/**
 * Test a few single data event cases.
 */
function singleDataEvent() {
    var theData = new Buffer("stuff");

    tryWith("end", undefined);
    tryWith("close", undefined);
    tryWith("error", new Error("yow"));

    function tryWith(endEvent, endArg) {
        var isError = (endEvent === "error");
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        source.emit("data", theData);
        emit(source, endEvent, endArg);

        assert.equal(coll.events.length, isError ? 2 : 3);
        coll.assertEvent(0, sink, "data", [theData]);

        if (isError) {
            coll.assertEvent(1, sink, "error", [endArg]);
        } else {
            coll.assertEvent(1, sink, "end", undefined);
            coll.assertEvent(2, sink, "close", undefined);
        }
    }
}

/**
 * Test the collection of multiple data events.
 */
function multipleDataEvents() {
    for (var i = 1; i < 200; i += 17) {
        tryWith(i);
    }

    function tryWith(count) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();
        var expect = "";

        coll.listenAllCommon(sink);

        for (var i = 0; i < count; i++) {
            var buf = bufFor(i);
            expect += buf.toString();
            source.emit("data", buf);
        }

        assert.equal(coll.events.length, 0);
        source.emit("end");
        assert.equal(coll.events.length, 3);

        coll.assertEvent(0, sink, "data", [new Buffer(expect)]);
        coll.assertEvent(1, sink, "end", undefined);
        coll.assertEvent(2, sink, "close", undefined);
    }

    function bufFor(val) {
        return new Buffer("#" + val);
    }
}

/**
 * Check that emit-side encoding works as expected.
 */
function setEncoding() {
    tryWith(undefined);
    tryWith("ascii");
    tryWith("utf8");
    tryWith("base64");

    function tryWith(name) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        source.emit("data", "testing");
        source.emit("data", "123");
        sink.setEncoding(name);
        source.emit("end");

        var expect = new Buffer("testing123");
        if (name) {
            expect = expect.toString(name);
        }

        coll.assertEvent(0, sink, "data", [expect]);
        coll.assertEvent(1, sink, "end", undefined);
        coll.assertEvent(2, sink, "close", undefined);
    }
}

/**
 * Ensure that no events get passed after a `destroy()` call. Also, proves
 * that the valve isn't even listening for events from the source anymore.
 */
function afterDestroy() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    coll.listenAllCommon(sink);
    sink.destroy();
    source.emit("data", "yes?");
    source.emit("end");
    source.emit("close");

    assert.equal(coll.events.length, 0);

    assert.equal(source.listeners("close").length, 0);
    assert.equal(source.listeners("data").length, 0);
    assert.equal(source.listeners("end").length, 0);
    assert.equal(source.listeners("error").length, 0);
}

/**
 * Ensure that things don't go haywire if a sink is destroyed in the
 * middle of being resumed.
 */
function destroyDuringResume() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    sink.on("data", function() { sink.destroy(); });
    coll.listenAllCommon(sink);
    source.emit("data", "stuff");
    source.emit("end");

    assert.equal(coll.events.length, 3);
    coll.assertEvent(0, sink, "data", [new Buffer("stuff")]);
}

/**
 * Test that `getData()` returns `undefined` before there is data
 * and an appropriate value after.
 */
function appropriateGetData() {
    var theData = new Buffer("stuffy stuff");

    tryWith(false, "end", undefined);
    tryWith(false, "close", undefined);
    tryWith(false, "error", new Error("yow"));
    tryWith(true, "end", undefined);
    tryWith(true, "close", undefined);
    tryWith(true, "error", new Error("yow"));

    function tryWith(doData, endEvent, endArg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var expect = doData ? theData : undefined;
        var coll = new EventCollector();

        assert.equal(sink.getData(), undefined);
        coll.listenAllCommon(sink); // just to capture the error, if any

        if (doData) {
            source.emit("data", theData);
            assert.equal(sink.getData(), undefined);
        }

        emit(source, endEvent, endArg);
        assert.equal(sink.getData(), expect);
    }
}

/**
 * Test that `getError()` returns `undefined` before there is an error
 * and an appropriate value after.
 */
function appropriateGetError() {
    var theError = new Error("Missing muffin");

    tryWith(undefined, false);
    tryWith(undefined, true);
    tryWith(theError, false);
    tryWith(theError, true);

    function tryWith(error, doData) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        assert.equal(sink.getError(), undefined);
        coll.listenAllCommon(sink); // just to capture the error

        if (doData) {
            source.emit("data", "howdy");
            assert.equal(sink.getError(), undefined);
        }

        source.emit("error", error);
        assert.equal(sink.getError(), error);
    }
}

/**
 * Test that `gotError()` returns `false` before there is an error
 * and `true` after.
 */
function appropriateGotError() {
    var theError = new Error("Missing scone");

    tryWith(undefined, false);
    tryWith(undefined, true);
    tryWith(theError, false);
    tryWith(theError, true);

    function tryWith(error, doData) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        assert.ok(!sink.gotError());
        coll.listenAllCommon(sink); // just to capture the error

        if (doData) {
            source.emit("data", "howdy");
            assert.ok(!sink.gotError());
        }

        source.emit("error", error);
        assert.ok(sink.gotError());
    }
}

/**
 * Test that `setIncomingEncoding()` operates properly.
 */
function setIncomingEncoding() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);

    // Default to utf-8.
    source.emit("data", "\u168c-gort"); // "OGHAM LETTER GORT"

    sink.setIncomingEncoding("base64");
    source.emit("data", "LWJpc2N1aXRzCg=="); // "-biscuits\n"

    sink.setIncomingEncoding("ascii");
    source.emit("data", "scones");

    sink.setIncomingEncoding("utf8");
    source.emit("data", "-\u1683-fearn"); // "OGHAM LETTER FEARN"
    source.emit("end");

    assert.equal(sink.getData().toString(),
                 "\u168c-gort-biscuits\nscones-\u1683-fearn");
}

function test() {
    constructor();
    needSource();
    noInitialEvents();
    readableTransition();
    eventsAfterEnd();
    noDataEvents();
    singleDataEvent();
    multipleDataEvents();
    setEncoding();
    afterDestroy();
    destroyDuringResume();
    appropriateGetData();
    appropriateGetError();
    appropriateGotError();
    setIncomingEncoding();
}

module.exports = {
    test: test
};
<commit_msg>Test encoding error cases.<commit_after>// Copyright 2012 The Obvious Corporation.

/*
 * Modules used
 */

"use strict";

var assert = require("assert");
var events = require("events");

var Sink = require("../").Sink;

var EventCollector = require("./eventcoll").EventCollector;
var emit = require("./emit").emit;

/*
 * Tests
 */

/**
 * Make sure the constructor doesn't fail off the bat.
 */
function constructor() {
    new Sink(new events.EventEmitter());
}

/**
 * Test expected constructor failures.
 */
function needSource() {
    function f1() {
        new Sink();
    }
    assert.throws(f1, /Missing source/);

    function f2() {
        new Sink(["hello"]);
    }
    assert.throws(f2, /Source not an EventEmitter/);
}

/**
 * Test that invalid encodings are rejected.
 */
function badEncodings() {
    var sink = new Sink(new events.EventEmitter());

    function f1() {
        sink.setEncoding("hex");
    }
    assert.throws(f1, /Invalid encoding name/);

    function f2() {
        sink.setIncomingEncoding("hex");
    }
    assert.throws(f2, /Invalid encoding name/);
}

/**
 * Test that no events get added spontaneously.
 */
function noInitialEvents() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    sink.pause();
    coll.listenAllCommon(sink);
    sink.resume();
    assert.equal(coll.events.length, 0);
}

/**
 * Test that `readable` is true until an end-type event comes through.
 */
function readableTransition() {
    tryWith(false, "end");
    tryWith(false, "close");
    tryWith(false, "error", new Error("criminy"));
    tryWith(true, "end");
    tryWith(true, "close");
    tryWith(true, "error", new Error("criminy"));

    function tryWith(pauseFirst, name, arg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        assert.ok(sink.readable);

        if (pauseFirst) {
            sink.pause();
        }

        emit(source, name, arg);

        if (pauseFirst) {
            assert.equal(coll.events.length, 0);
            assert.ok(sink.readable);
            sink.resume();
        }

        assert.equal(coll.events.length, (name === "error") ? 1 : 2);
        assert.ok(!sink.readable);
    }
}

/**
 * Test that no further events get emitted after an end-type event.
 */
function eventsAfterEnd() {
    tryWith(false, "end");
    tryWith(false, "close");
    tryWith(false, "error", new Error("oy"));
    tryWith(true, "end");
    tryWith(true, "close");
    tryWith(true, "error", new Error("oy"));

    function tryWith(extraData, name, arg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        emit(source, name, arg);
        assert.equal(coll.events.length, (name === "error") ? 1 : 2);
        coll.reset();

        if (extraData) {
            source.emit("data", "huzzah");
            assert.equal(coll.events.length, 0);
        }

        source.emit("end");
        assert.equal(coll.events.length, 0);

        source.emit("close");
        assert.equal(coll.events.length, 0);

        source.emit("error", new Error("eek"));
        assert.equal(coll.events.length, 0);
    }
}

/**
 * Test a few no-data-events cases.
 */
function noDataEvents() {
    tryWith("end", undefined);
    tryWith("close", undefined);
    tryWith("error", new Error("yow"));

    function tryWith(endEvent, endArg) {
        var isError = (endEvent === "error");
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        emit(source, endEvent, endArg);

        assert.equal(coll.events.length, isError ? 1 : 2);

        if (isError) {
            coll.assertEvent(0, sink, "error", [endArg]);
        } else {
            coll.assertEvent(0, sink, "end", undefined);
            coll.assertEvent(1, sink, "close", undefined);
        }
    }
}

/**
 * Test a few single data event cases.
 */
function singleDataEvent() {
    var theData = new Buffer("stuff");

    tryWith("end", undefined);
    tryWith("close", undefined);
    tryWith("error", new Error("yow"));

    function tryWith(endEvent, endArg) {
        var isError = (endEvent === "error");
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        source.emit("data", theData);
        emit(source, endEvent, endArg);

        assert.equal(coll.events.length, isError ? 2 : 3);
        coll.assertEvent(0, sink, "data", [theData]);

        if (isError) {
            coll.assertEvent(1, sink, "error", [endArg]);
        } else {
            coll.assertEvent(1, sink, "end", undefined);
            coll.assertEvent(2, sink, "close", undefined);
        }
    }
}

/**
 * Test the collection of multiple data events.
 */
function multipleDataEvents() {
    for (var i = 1; i < 200; i += 17) {
        tryWith(i);
    }

    function tryWith(count) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();
        var expect = "";

        coll.listenAllCommon(sink);

        for (var i = 0; i < count; i++) {
            var buf = bufFor(i);
            expect += buf.toString();
            source.emit("data", buf);
        }

        assert.equal(coll.events.length, 0);
        source.emit("end");
        assert.equal(coll.events.length, 3);

        coll.assertEvent(0, sink, "data", [new Buffer(expect)]);
        coll.assertEvent(1, sink, "end", undefined);
        coll.assertEvent(2, sink, "close", undefined);
    }

    function bufFor(val) {
        return new Buffer("#" + val);
    }
}

/**
 * Check that emit-side encoding works as expected.
 */
function setEncoding() {
    tryWith(undefined);
    tryWith("ascii");
    tryWith("utf8");
    tryWith("base64");

    function tryWith(name) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        coll.listenAllCommon(sink);
        source.emit("data", "testing");
        source.emit("data", "123");
        sink.setEncoding(name);
        source.emit("end");

        var expect = new Buffer("testing123");
        if (name) {
            expect = expect.toString(name);
        }

        coll.assertEvent(0, sink, "data", [expect]);
        coll.assertEvent(1, sink, "end", undefined);
        coll.assertEvent(2, sink, "close", undefined);
    }
}

/**
 * Ensure that no events get passed after a `destroy()` call. Also, proves
 * that the valve isn't even listening for events from the source anymore.
 */
function afterDestroy() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    coll.listenAllCommon(sink);
    sink.destroy();
    source.emit("data", "yes?");
    source.emit("end");
    source.emit("close");

    assert.equal(coll.events.length, 0);

    assert.equal(source.listeners("close").length, 0);
    assert.equal(source.listeners("data").length, 0);
    assert.equal(source.listeners("end").length, 0);
    assert.equal(source.listeners("error").length, 0);
}

/**
 * Ensure that things don't go haywire if a sink is destroyed in the
 * middle of being resumed.
 */
function destroyDuringResume() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);
    var coll = new EventCollector();

    sink.on("data", function() { sink.destroy(); });
    coll.listenAllCommon(sink);
    source.emit("data", "stuff");
    source.emit("end");

    assert.equal(coll.events.length, 3);
    coll.assertEvent(0, sink, "data", [new Buffer("stuff")]);
}

/**
 * Test that `getData()` returns `undefined` before there is data
 * and an appropriate value after.
 */
function appropriateGetData() {
    var theData = new Buffer("stuffy stuff");

    tryWith(false, "end", undefined);
    tryWith(false, "close", undefined);
    tryWith(false, "error", new Error("yow"));
    tryWith(true, "end", undefined);
    tryWith(true, "close", undefined);
    tryWith(true, "error", new Error("yow"));

    function tryWith(doData, endEvent, endArg) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var expect = doData ? theData : undefined;
        var coll = new EventCollector();

        assert.equal(sink.getData(), undefined);
        coll.listenAllCommon(sink); // just to capture the error, if any

        if (doData) {
            source.emit("data", theData);
            assert.equal(sink.getData(), undefined);
        }

        emit(source, endEvent, endArg);
        assert.equal(sink.getData(), expect);
    }
}

/**
 * Test that `getError()` returns `undefined` before there is an error
 * and an appropriate value after.
 */
function appropriateGetError() {
    var theError = new Error("Missing muffin");

    tryWith(undefined, false);
    tryWith(undefined, true);
    tryWith(theError, false);
    tryWith(theError, true);

    function tryWith(error, doData) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        assert.equal(sink.getError(), undefined);
        coll.listenAllCommon(sink); // just to capture the error

        if (doData) {
            source.emit("data", "howdy");
            assert.equal(sink.getError(), undefined);
        }

        source.emit("error", error);
        assert.equal(sink.getError(), error);
    }
}

/**
 * Test that `gotError()` returns `false` before there is an error
 * and `true` after.
 */
function appropriateGotError() {
    var theError = new Error("Missing scone");

    tryWith(undefined, false);
    tryWith(undefined, true);
    tryWith(theError, false);
    tryWith(theError, true);

    function tryWith(error, doData) {
        var source = new events.EventEmitter();
        var sink = new Sink(source);
        var coll = new EventCollector();

        assert.ok(!sink.gotError());
        coll.listenAllCommon(sink); // just to capture the error

        if (doData) {
            source.emit("data", "howdy");
            assert.ok(!sink.gotError());
        }

        source.emit("error", error);
        assert.ok(sink.gotError());
    }
}

/**
 * Test that `setIncomingEncoding()` operates properly.
 */
function setIncomingEncoding() {
    var source = new events.EventEmitter();
    var sink = new Sink(source);

    // Default to utf-8.
    source.emit("data", "\u168c-gort"); // "OGHAM LETTER GORT"

    sink.setIncomingEncoding("base64");
    source.emit("data", "LWJpc2N1aXRzCg=="); // "-biscuits\n"

    sink.setIncomingEncoding("ascii");
    source.emit("data", "scones");

    sink.setIncomingEncoding("utf8");
    source.emit("data", "-\u1683-fearn"); // "OGHAM LETTER FEARN"
    source.emit("end");

    assert.equal(sink.getData().toString(),
                 "\u168c-gort-biscuits\nscones-\u1683-fearn");
}

function test() {
    constructor();
    needSource();
    badEncodings();
    noInitialEvents();
    readableTransition();
    eventsAfterEnd();
    noDataEvents();
    singleDataEvent();
    multipleDataEvents();
    setEncoding();
    afterDestroy();
    destroyDuringResume();
    appropriateGetData();
    appropriateGetError();
    appropriateGotError();
    setIncomingEncoding();
}

module.exports = {
    test: test
};
<|endoftext|>


<commit_before>var app = app || {};

$(function () {
	'use strict';

	app.CodemagicView = Backbone.View.extend({
		that: this,
		el: '#container',
		events : {
			'click #update': 'updateResults',
			'click #prettify': 'prettify',
			'click #fullscreen': 'toggleFullscreen',
			'click .editor-fullscreen-toggle': 'editorFullscreen',
			'mousedown .resizer': 'resizeInitialize',
			'mouseup': 'resizeFinalize',
			'mousemove': 'resizeRefresh',
			'click .editor-options-toggle': 'toggleTargetedEditorOptions',
			'change .codeChoice': 'toggleSelectedEditorOptions',
			'click .editor-toggle': 'toggleEditorState'
		},
		prettify: function () {
			// TODO: parameterize these depending on the editor's settings
			// https://github.com/einars/js-beautify#options
			if ($('#markupChoice').val() === 'HTML') {
				app.editors.htmlSession.setValue(html_beautify(app.editors.htmlSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': [],
					'indent-inner-html': true
				}));

				app.editors.htmlSession.selection.moveCursorFileStart();
			}

			if ($('#styleChoice').val() === 'CSS') {
				app.editors.cssSession.setValue(css_beautify(app.editors.cssSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': []
				}));

				app.editors.cssSession.selection.moveCursorFileStart();
			}

			if ($('#scriptChoice').val() === 'JavaScript') {
				app.editors.jsSession.setValue(js_beautify(app.editors.jsSession.getValue(), {
					'indent_size': 1,
					'indent_char': '\t',
					'preserve_newlines': true,
					'jslint_happy': true,
					'brace_style': 'collapse',
					'keep_array_indentation': false,
					'keep_function_indentation': false,
					'eval_code': false,
					'unescape_strings': false,
					'break_chained_methods': false
				}));

				app.editors.jsSession.selection.moveCursorFileStart();
			}
		},
		toggleEditorState: function (selector) {
			var target;
			if(selector instanceof Array){
				for (var i = 0; i < selector.length; i++) {
					$(selector[i]).toggleClass('enabled');
					$('#' + selector[i] + '-editor').closest('.editor-module').toggleClass('enabled');
					$('#' + selector[i] + '-editor-toggle').toggleClass('enabled');
				}
				target = false;
			}else if(typeof selector === 'object'){
				target = $(selector.currentTarget).prop('id').replace('-editor-toggle', '');
			} else {
				target = selector;
			}

			if(target !== false){
				$('#' + target + '-editor-toggle').toggleClass('enabled');
				$('#' + target + '-editor').closest('.editor-module').toggleClass('enabled');
				app.utils.toggleEditorState(target);
			}
		},
		toggleSelectedEditorOptions: function (e) {
			var value = $(e.currentTarget).val();
			var editorTarget = $(e.currentTarget).parent();
			var target = editorTarget.parent().find('.editor-option-title');
			$(target).html(value);
			this.toggleTargetedEditorOptions(e);
			app.utils.setEditorMode(editorTarget.prop('id').replace('-editor-options', ''), value.toLowerCase());
		},
		toggleTargetedEditorOptions: function (e) {
			if($(e.currentTarget).prop('tagName') === 'SELECT'){
				this.toggleEditorOptions($(e.currentTarget).parent());
			} else if(e.container !== undefined){
				var temp = $(e.container).prop('id').replace('-editor', '');
				this.toggleEditorOptions($('#' + temp + '-editor-options'));
			} else {
				this.toggleEditorOptions($(e.currentTarget).next());
			}
		},
		toggleEditorOptions: function (target) {
			$(target).toggleClass('enabled');
		},
		resizeInitialize: function (e) {
			app.session.resize = e.pageY;
			app.session.resizeTarget = app.session.resizeTarget || {};
			app.session.resizeTarget.id = $(e.currentTarget).prev().find('.editor');
			app.session.resizeTarget.id = app.session.resizeTarget.id.prop('id');
			app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).parent().height();
		},
		resizeRefresh: function (e) {
			if (app.session.resize) {
				$('#editors').css('padding-bottom', '30%');
				$('#' + app.session.resizeTarget.id).parent().height(app.session.resizeTarget.height + e.pageY - app.session.resize);
				app.utils.updateLayout(app.editors);
			}
		},
		resizeFinalize: function () {
			app.session.resize = false;
			if(typeof app.session.resizeTarget !== 'undefined'){
				if(typeof app.session.resizeTarget.height !== 'undefined'){
					app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).height();
				}
			}
			app.utils.updateLayout(app.editors);
			$('#editors').css('padding-bottom', '0');
		},
		toggleFullscreen: function () {
			var target = document.querySelector('#result iframe');
			app.utils.toggleFullscreenMode(target);
		},
		editorFullscreen: function (e) {
			var target;
			if(e.container !== undefined){
				target = $(e.container).prop('id');
			}else{
				target = $(e.currentTarget).prop('id');
				target = target.replace('-editor-fullscreen-toggle', '') + '-editor';
			}
			target = document.getElementById(target);
			app.utils.toggleFullscreenMode(target);
		},
		updateResults: function () {
			$('#console-editor').html('');

			var content = '';
			var style= '';
			var script= '';

			if ($('#markupChoice').val() === 'Markdown') {
				content = marked(app.editors.html.getValue());
			} else if ($('#markupChoice').val() === 'HAML') {
				app.utils.consoleLog('HAML support is not ready yet');
			} else if ($('#markupChoice').val() === 'Jade') {
				app.utils.consoleLog('Jade support is not ready yet');
			} else {
				content = app.editors.html.getValue();
			}

			if ($('#styleChoice').val() === 'Less') {
				var parser = new(less.Parser)();

				parser.parse(app.editors.css.getValue(), function (e, tree) {
					if (e) {
						// TODO: error handling in console
						$('#console-editor').append('> ' + e.message + '
');
						console.log(e);
					}
					style = tree.toCSS();
				});
			} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
				app.utils.consoleLog('SASS/SCSS support is not ready yet');
			} else if ($('#styleChoice').val() === 'Stylus') {
				app.utils.consoleLog('Stylus support is not ready yet');
			} else {
				style = app.editors.css.getValue();
			}

			if ($('#styleChoice').val() === 'CoffeeScript') {
			} else {
				script = app.editors.js.getValue();
			}

			// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit
			var logger = '';

			var head = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">';
			var body = '' + content + '';

			var result = head + body;

			var iframeContainer = document.getElementById('result');

			$('#result iframe').remove();

			// TODO: write the lines below in JQuery (if performance and stability allow it)
			var iframe = document.createElement('iframe');

			iframeContainer.appendChild(iframe);

			var iDoc = iframe.contentDocument;
			iDoc.open();
			iDoc.write(result);
			iDoc.close();

			$('iframe').height(Math.max($('#editors').height(), $('iframe').height()));
		},
		initialize: function () {
			this.template = _.template($('#codemagic-template').html());
			this.render();

			// populate editors with example content
			app.editors.htmlSession.setValue('
Hello World
\n\n
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, nobis, inventore, cupiditate, itaque quae quas commodi reprehenderit expedita aliquid nulla vero voluptatem esse modi quasi similique atque sequi tempore dolore ut nesciunt aliquam quidem dolorum ipsa totam eaque accusamus odit maiores fugiat incidunt iste. Itaque necessitatibus cupiditate consequatur vitae maxime.
');
			app.editors.cssSession.setValue('body{ margin: 0; padding: 1rem; }\n\nh1{\n	margin-top: 0;\n	color: #666;\n}\n\np{\n	color: #999;\n}');
			app.editors.jsSession.setValue('var x = document.querySelector("p");\nx.style.textAlign = "justify";\nx.style.textIndent= "1rem";');
			this.updateResults();
		},
		render: function () {
			this.$el.append(this.template());

			/* *******************************************************
				Editors
			******************************************************* */

			app.session = {
				settings : {
					title : 'codeMagic',
					description : '',
					author : '',
					html : {
						state : true,
						mode : 'html',
						content : ''
					},
					css : {
						state : true,
						mode : 'css',
						content : ''
					},
					js : {
						state : true,
						content : ''
					},
					console : {
						state : false,
						content : ''
					},
					theme : app.utils.getSettings('editor.theme') || 'tomorrow',
					tabSize : parseInt(app.utils.getSettings('editor.tabSize'), 10) || 4,
					showPrintMargin : app.utils.getSettings('editor.showPrintMargin') || false,
					useWrapMode : app.utils.getSettings('editor.useWrapMode') || true,
					useWorker : true,
					fontSize : parseInt(app.utils.getSettings('editor.fontSize'), 10) || 12,
					showInvisibles : app.utils.getSettings('editor.showInvisibles') || false,
					behavioursEnabled : app.utils.getSettings('editor.behavioursEnabled') || true
				}
			};

			app.utils.setSettings('editor.theme', app.session.settings.theme);
			app.utils.setSettings('editor.tabSize', app.session.settings.tabSize);
			app.utils.setSettings('editor.showPrintMargin', app.session.settings.showPrintMargin);
			app.utils.setSettings('editor.useWrapMode', app.session.settings.useWrapMode);
			app.utils.setSettings('editor.useWorker', app.session.settings.useWorker);
			app.utils.setSettings('editor.fontSize', app.session.settings.fontSize);
			app.utils.setSettings('editor.showInvisibles', app.session.settings.showInvisibles);
			app.utils.setSettings('editor.behavioursEnabled', app.session.settings.behavioursEnabled);

			app.editors = {};
			app.editors.html = ace.edit('html-editor');
			app.editors.css = ace.edit('css-editor');
			app.editors.js = ace.edit('js-editor');
			app.editors.htmlSession = app.editors.html.getSession();
			app.editors.cssSession = app.editors.css.getSession();
			app.editors.jsSession = app.editors.js.getSession();

			ace.config.set("basePath", "assets/js/ace");
			app.emmet = ace.require('ace/ext/emmet');
			app.language_tools = ace.require('ace/ext/language_tools');

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.commands.removeCommand('showSettingsMenu');
				editor.commands.addCommand({
					name: 'fullscreen',
					bindKey: {
						win: 'Ctrl-Shift-F',
						mac: 'Command-Shift-F'
					},
					exec: function (e) {
						app.codemagicView.editorFullscreen(e);
					},
					readOnly: true
				});
				editor.commands.addCommand({
					name: 'updateResults',
					bindKey: {
						win: 'Ctrl-Enter',
						mac: 'Command-Enter'
					},
					exec: function (e) {
						app.codemagicView.updateResults();
					},
					readOnly: true
				});
				editor.commands.addCommand({
					name: 'toggleEditorOptions',
					bindKey: {
						win: 'Ctrl-Alt-O',
						mac: 'Command-Alt-O'
					},
					exec: function (e) {
						app.codemagicView.toggleTargetedEditorOptions(e);
					},
					readOnly: true
				});
				editor.setOptions({
					enableSnippets: true,
					enableLiveAutoComplete: true,
					enableBasicAutocompletion: true,
					showPrintMargin: app.session.settings.showPrintMargin,
					useSoftTabs: false,
					fontSize: app.session.settings.fontSize,
					showInvisibles: app.session.settings.showInvisibles,
					behavioursEnabled: app.session.settings.behavioursEnabled,
					tabSize: app.session.settings.tabSize,
					wrap: app.session.settings.useWrapMode,
					useWorker: app.session.settings.useWorker,
					highlightActiveLine: false,
					enableEmmet: true
				});
			});

			// editor syntax highlighting modes
			app.editors.htmlSession.setMode('ace/mode/' + app.session.settings.html.mode);
			app.editors.cssSession.setMode('ace/mode/' + app.session.settings.css.mode);
			app.editors.jsSession.setMode('ace/mode/javascript');

			// set the Default theme
			app.utils.setTheme(app.editors, app.session.settings.theme);

			this.toggleEditorState(['html', 'css', 'js']);

			return this;
		}
	});
});
<commit_msg>removed unused that=this assignment<commit_after>var app = app || {};

$(function () {
	'use strict';

	app.CodemagicView = Backbone.View.extend({
		el: '#container',
		events : {
			'click #update': 'updateResults',
			'click #prettify': 'prettify',
			'click #fullscreen': 'toggleFullscreen',
			'click .editor-fullscreen-toggle': 'editorFullscreen',
			'mousedown .resizer': 'resizeInitialize',
			'mouseup': 'resizeFinalize',
			'mousemove': 'resizeRefresh',
			'click .editor-options-toggle': 'toggleTargetedEditorOptions',
			'change .codeChoice': 'toggleSelectedEditorOptions',
			'click .editor-toggle': 'toggleEditorState'
		},
		prettify: function () {
			// TODO: parameterize these depending on the editor's settings
			// https://github.com/einars/js-beautify#options
			if ($('#markupChoice').val() === 'HTML') {
				app.editors.htmlSession.setValue(html_beautify(app.editors.htmlSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': [],
					'indent-inner-html': true
				}));

				app.editors.htmlSession.selection.moveCursorFileStart();
			}

			if ($('#styleChoice').val() === 'CSS') {
				app.editors.cssSession.setValue(css_beautify(app.editors.cssSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': []
				}));

				app.editors.cssSession.selection.moveCursorFileStart();
			}

			if ($('#scriptChoice').val() === 'JavaScript') {
				app.editors.jsSession.setValue(js_beautify(app.editors.jsSession.getValue(), {
					'indent_size': 1,
					'indent_char': '\t',
					'preserve_newlines': true,
					'jslint_happy': true,
					'brace_style': 'collapse',
					'keep_array_indentation': false,
					'keep_function_indentation': false,
					'eval_code': false,
					'unescape_strings': false,
					'break_chained_methods': false
				}));

				app.editors.jsSession.selection.moveCursorFileStart();
			}
		},
		toggleEditorState: function (selector) {
			var target;
			if(selector instanceof Array){
				for (var i = 0; i < selector.length; i++) {
					$(selector[i]).toggleClass('enabled');
					$('#' + selector[i] + '-editor').closest('.editor-module').toggleClass('enabled');
					$('#' + selector[i] + '-editor-toggle').toggleClass('enabled');
				}
				target = false;
			}else if(typeof selector === 'object'){
				target = $(selector.currentTarget).prop('id').replace('-editor-toggle', '');
			} else {
				target = selector;
			}

			if(target !== false){
				$('#' + target + '-editor-toggle').toggleClass('enabled');
				$('#' + target + '-editor').closest('.editor-module').toggleClass('enabled');
				app.utils.toggleEditorState(target);
			}
		},
		toggleSelectedEditorOptions: function (e) {
			var value = $(e.currentTarget).val();
			var editorTarget = $(e.currentTarget).parent();
			var target = editorTarget.parent().find('.editor-option-title');
			$(target).html(value);
			this.toggleTargetedEditorOptions(e);
			app.utils.setEditorMode(editorTarget.prop('id').replace('-editor-options', ''), value.toLowerCase());
		},
		toggleTargetedEditorOptions: function (e) {
			if($(e.currentTarget).prop('tagName') === 'SELECT'){
				this.toggleEditorOptions($(e.currentTarget).parent());
			} else if(e.container !== undefined){
				var temp = $(e.container).prop('id').replace('-editor', '');
				this.toggleEditorOptions($('#' + temp + '-editor-options'));
			} else {
				this.toggleEditorOptions($(e.currentTarget).next());
			}
		},
		toggleEditorOptions: function (target) {
			$(target).toggleClass('enabled');
		},
		resizeInitialize: function (e) {
			app.session.resize = e.pageY;
			app.session.resizeTarget = app.session.resizeTarget || {};
			app.session.resizeTarget.id = $(e.currentTarget).prev().find('.editor');
			app.session.resizeTarget.id = app.session.resizeTarget.id.prop('id');
			app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).parent().height();
		},
		resizeRefresh: function (e) {
			if (app.session.resize) {
				$('#editors').css('padding-bottom', '30%');
				$('#' + app.session.resizeTarget.id).parent().height(app.session.resizeTarget.height + e.pageY - app.session.resize);
				app.utils.updateLayout(app.editors);
			}
		},
		resizeFinalize: function () {
			app.session.resize = false;
			if(typeof app.session.resizeTarget !== 'undefined'){
				if(typeof app.session.resizeTarget.height !== 'undefined'){
					app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).height();
				}
			}
			app.utils.updateLayout(app.editors);
			$('#editors').css('padding-bottom', '0');
		},
		toggleFullscreen: function () {
			var target = document.querySelector('#result iframe');
			app.utils.toggleFullscreenMode(target);
		},
		editorFullscreen: function (e) {
			var target;
			if(e.container !== undefined){
				target = $(e.container).prop('id');
			}else{
				target = $(e.currentTarget).prop('id');
				target = target.replace('-editor-fullscreen-toggle', '') + '-editor';
			}
			target = document.getElementById(target);
			app.utils.toggleFullscreenMode(target);
		},
		updateResults: function () {
			$('#console-editor').html('');

			var content = '';
			var style= '';
			var script= '';

			if ($('#markupChoice').val() === 'Markdown') {
				content = marked(app.editors.html.getValue());
			} else if ($('#markupChoice').val() === 'HAML') {
				app.utils.consoleLog('HAML support is not ready yet');
			} else if ($('#markupChoice').val() === 'Jade') {
				app.utils.consoleLog('Jade support is not ready yet');
			} else {
				content = app.editors.html.getValue();
			}

			if ($('#styleChoice').val() === 'Less') {
				var parser = new(less.Parser)();

				parser.parse(app.editors.css.getValue(), function (e, tree) {
					if (e) {
						// TODO: error handling in console
						$('#console-editor').append('> ' + e.message + '
');
						console.log(e);
					}
					style = tree.toCSS();
				});
			} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
				app.utils.consoleLog('SASS/SCSS support is not ready yet');
			} else if ($('#styleChoice').val() === 'Stylus') {
				app.utils.consoleLog('Stylus support is not ready yet');
			} else {
				style = app.editors.css.getValue();
			}

			if ($('#styleChoice').val() === 'CoffeeScript') {
			} else {
				script = app.editors.js.getValue();
			}

			// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit
			var logger = '';

			var head = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">';
			var body = '' + content + '';

			var result = head + body;

			var iframeContainer = document.getElementById('result');

			$('#result iframe').remove();

			// TODO: write the lines below in JQuery (if performance and stability allow it)
			var iframe = document.createElement('iframe');

			iframeContainer.appendChild(iframe);

			var iDoc = iframe.contentDocument;
			iDoc.open();
			iDoc.write(result);
			iDoc.close();

			$('iframe').height(Math.max($('#editors').height(), $('iframe').height()));
		},
		initialize: function () {
			this.template = _.template($('#codemagic-template').html());
			this.render();

			// populate editors with example content
			app.editors.htmlSession.setValue('
Hello World
\n\n
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, nobis, inventore, cupiditate, itaque quae quas commodi reprehenderit expedita aliquid nulla vero voluptatem esse modi quasi similique atque sequi tempore dolore ut nesciunt aliquam quidem dolorum ipsa totam eaque accusamus odit maiores fugiat incidunt iste. Itaque necessitatibus cupiditate consequatur vitae maxime.
');
			app.editors.cssSession.setValue('body{ margin: 0; padding: 1rem; }\n\nh1{\n	margin-top: 0;\n	color: #666;\n}\n\np{\n	color: #999;\n}');
			app.editors.jsSession.setValue('var x = document.querySelector("p");\nx.style.textAlign = "justify";\nx.style.textIndent= "1rem";');
			this.updateResults();
		},
		render: function () {
			this.$el.append(this.template());

			/* *******************************************************
				Editors
			******************************************************* */

			app.session = {
				settings : {
					title : 'codeMagic',
					description : '',
					author : '',
					html : {
						state : true,
						mode : 'html',
						content : ''
					},
					css : {
						state : true,
						mode : 'css',
						content : ''
					},
					js : {
						state : true,
						content : ''
					},
					console : {
						state : false,
						content : ''
					},
					theme : app.utils.getSettings('editor.theme') || 'tomorrow',
					tabSize : parseInt(app.utils.getSettings('editor.tabSize'), 10) || 4,
					showPrintMargin : app.utils.getSettings('editor.showPrintMargin') || false,
					useWrapMode : app.utils.getSettings('editor.useWrapMode') || true,
					useWorker : true,
					fontSize : parseInt(app.utils.getSettings('editor.fontSize'), 10) || 12,
					showInvisibles : app.utils.getSettings('editor.showInvisibles') || false,
					behavioursEnabled : app.utils.getSettings('editor.behavioursEnabled') || true
				}
			};

			app.utils.setSettings('editor.theme', app.session.settings.theme);
			app.utils.setSettings('editor.tabSize', app.session.settings.tabSize);
			app.utils.setSettings('editor.showPrintMargin', app.session.settings.showPrintMargin);
			app.utils.setSettings('editor.useWrapMode', app.session.settings.useWrapMode);
			app.utils.setSettings('editor.useWorker', app.session.settings.useWorker);
			app.utils.setSettings('editor.fontSize', app.session.settings.fontSize);
			app.utils.setSettings('editor.showInvisibles', app.session.settings.showInvisibles);
			app.utils.setSettings('editor.behavioursEnabled', app.session.settings.behavioursEnabled);

			app.editors = {};
			app.editors.html = ace.edit('html-editor');
			app.editors.css = ace.edit('css-editor');
			app.editors.js = ace.edit('js-editor');
			app.editors.htmlSession = app.editors.html.getSession();
			app.editors.cssSession = app.editors.css.getSession();
			app.editors.jsSession = app.editors.js.getSession();

			ace.config.set("basePath", "assets/js/ace");
			app.emmet = ace.require('ace/ext/emmet');
			app.language_tools = ace.require('ace/ext/language_tools');

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.commands.removeCommand('showSettingsMenu');
				editor.commands.addCommand({
					name: 'fullscreen',
					bindKey: {
						win: 'Ctrl-Shift-F',
						mac: 'Command-Shift-F'
					},
					exec: function (e) {
						app.codemagicView.editorFullscreen(e);
					},
					readOnly: true
				});
				editor.commands.addCommand({
					name: 'updateResults',
					bindKey: {
						win: 'Ctrl-Enter',
						mac: 'Command-Enter'
					},
					exec: function (e) {
						app.codemagicView.updateResults();
					},
					readOnly: true
				});
				editor.commands.addCommand({
					name: 'toggleEditorOptions',
					bindKey: {
						win: 'Ctrl-Alt-O',
						mac: 'Command-Alt-O'
					},
					exec: function (e) {
						app.codemagicView.toggleTargetedEditorOptions(e);
					},
					readOnly: true
				});
				editor.setOptions({
					enableSnippets: true,
					enableLiveAutoComplete: true,
					enableBasicAutocompletion: true,
					showPrintMargin: app.session.settings.showPrintMargin,
					useSoftTabs: false,
					fontSize: app.session.settings.fontSize,
					showInvisibles: app.session.settings.showInvisibles,
					behavioursEnabled: app.session.settings.behavioursEnabled,
					tabSize: app.session.settings.tabSize,
					wrap: app.session.settings.useWrapMode,
					useWorker: app.session.settings.useWorker,
					highlightActiveLine: false,
					enableEmmet: true
				});
			});

			// editor syntax highlighting modes
			app.editors.htmlSession.setMode('ace/mode/' + app.session.settings.html.mode);
			app.editors.cssSession.setMode('ace/mode/' + app.session.settings.css.mode);
			app.editors.jsSession.setMode('ace/mode/javascript');

			// set the Default theme
			app.utils.setTheme(app.editors, app.session.settings.theme);

			this.toggleEditorState(['html', 'css', 'js']);

			return this;
		}
	});
});
<|endoftext|>


<commit_before>if (typeof define !== 'function') {var define = require('amdefine')(module)}
define(['./assert', './smpl.data', './smpl.Ecb', './smpl.string', './smpl.utils'], '');

<commit_msg>Get more accurate code coverage.<commit_after>if (typeof define !== 'function') {var define = require('amdefine')(module)}
define(['../src/smpl', './assert', './smpl.data', './smpl.Ecb', './smpl.string', './smpl.utils'], '');

<|endoftext|>


<commit_before>/*
 * Copyright (c) Sematext Group, Inc.
 * All Rights Reserved
 *
 * SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
var config = require('../lib/util/spmconfig.js')
config.logger.console = false
config.logger.level = 'debug'
if (!config.tokens.spm) {
  config.tokens.spm = process.env.SPM_TOKEN || 'TEST_TEST_TEST_SPM_AGENT_TRAVIS'
}
global.spmSenderUrlParameters = '&countainerCount=1'

describe('SPM for NodeJS tests', function () {
  it('SPM Agent Stats', function (done) {
    try {
      this.timeout(30000)
      config.collectionInterval = 1200
      config.retransmitInterval = 1000
      config.recoverInterval = 1000
      config.maxDataPoints = 1
      config.logger.console = true
      config.logger.level = 'debug'
      var SpmAgent = require('../lib/index.js')
      var client = new SpmAgent()
      var testAgent = client.createAgent(new SpmAgent.Agent({
        start: function (agent) {
          setTimeout(function () {
            agent.addMetrics({name: 'collectd5-disk-space-used\tdf-xvda1/df_complex-used', value: 3380457472.0, sct: 'OS'})
            agent.addMetrics({name: 'collectd-io-octets  disk-sda2/disk_octets', value: '0.000000,0.000000', sct: 'OS'})
            agent.addMetrics({name: 'test', sct: 'OS', value: [1, 2, 3]})
            agent.addMetrics({name: 'test', value: [1, 2, 3]})
          }, 900)
        },
        stop: console.log
      }))

      client.once('stats', function (stats) {
        done()
      })
    } catch (err) {
      console.log(err.stack)
      done(err)
    }
  })
  it('Logger should log', function (done) {
    try {
      var logger = require('../lib/util/logger.js')
      logger.log('Logger test %d', 1)
      done()
    } catch (err) {
      done(err)
    }
  })
  it('SPM Config has defaults', function (done) {
    try {
      var cfgValue = ['tokens.spm', 'recoverInterval', 'maxRetransmitBatchSize', 'spmSenderBulkInsertUrl', 'logger.dir', 'logger.filename', 'logger.level', 'maxDataPoints', 'collectionInterval']
      var checked = cfgValue.filter(function (key) {
        return (config.get(key) === null)
      })
      if (checked.length === 0) {
        done()
      } else {
        done('missing config values: ' + checked)
      }
    } catch (err) {
      done(err)
    }
  })
})
<commit_msg>changed timeouts<commit_after>/*
 * Copyright (c) Sematext Group, Inc.
 * All Rights Reserved
 *
 * SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
var config = require('../lib/util/spmconfig.js')
config.logger.console = false
config.logger.level = 'debug'
if (!config.tokens.spm) {
  config.tokens.spm = process.env.SPM_TOKEN || 'TEST_TEST_TEST_SPM_AGENT_TRAVIS'
}
global.spmSenderUrlParameters = '&countainerCount=1'

describe('SPM for NodeJS tests', function () {
  it('SPM Agent Stats', function (done) {
    try {
      this.timeout(50000)
      config.collectionInterval = 1000
      config.retransmitInterval = 1000
      // config.recoverInterval = 1000
      config.maxDataPoints = 1
      config.logger.console = true
      config.logger.level = 'debug'
      var SpmAgent = require('../lib/index.js')
      var client = new SpmAgent()
      var testAgent = client.createAgent(new SpmAgent.Agent({
        start: function (agent) {
          setTimeout(function () {
            agent.addMetrics({name: 'collectd5-disk-space-used\tdf-xvda1/df_complex-used', value: 3380457472.0, sct: 'OS'})
            agent.addMetrics({name: 'collectd-io-octets  disk-sda2/disk_octets', value: '0.000000,0.000000', sct: 'OS'})
            agent.addMetrics({name: 'test', sct: 'OS', value: [1, 2, 3]})
            agent.addMetrics({name: 'test', value: [1, 2, 3]})
          }, 500)
        },
        stop: console.log
      }))

      client.once('stats', function (stats) {
        done()
      })
    } catch (err) {
      console.log(err.stack)
      done(err)
    }
  })
  it('Logger should log', function (done) {
    try {
      var logger = require('../lib/util/logger.js')
      logger.log('Logger test %d', 1)
      done()
    } catch (err) {
      done(err)
    }
  })
  it('SPM Config has defaults', function (done) {
    try {
      var cfgValue = ['tokens.spm', 'recoverInterval', 'maxRetransmitBatchSize', 'spmSenderBulkInsertUrl', 'logger.dir', 'logger.filename', 'logger.level', 'maxDataPoints', 'collectionInterval']
      var checked = cfgValue.filter(function (key) {
        return (config.get(key) === null)
      })
      if (checked.length === 0) {
        done()
      } else {
        done('missing config values: ' + checked)
      }
    } catch (err) {
      done(err)
    }
  })
})
<|endoftext|>


<commit_before>/*!
 * export_data.js v1.0.0
 * Copyright 2016, Ahmad Firuze
 *
 * Freely distributable under the MIT license.
 * Portions of G.ENE.SYS Ultimate - Manufacturing Systems
 *
 * A script file to support export_data.tpl
 */
/* Get Params */
var id = getURLParameter("id"),
	$pageid = getURLParameter("pageid"),
	$filter = getURLParameter("filter"),
	$ob = getURLParameter("ob"),
	act = getURLParameter("action"),
	act_name = "(Exporting Data From Database)";
/*
/* ========================================= */
/* Default init for Header									 */
/* ========================================= */

// $( document ).ready(function() {
	/* Start :: Init for Title, Breadcrumb */
	// console.log($bread);
	// console.log($bread.length);
	$(document).prop('title', $HEAD_TITLE+' > '+$bread[$bread.length-1].title);
	$bread.unshift({ icon:"fa fa-dashboard", title:"Dashboard", link: "window.location.replace('"+$APPS_LNK+"')" });
	$(".content").before(BSHelper.PageHeader({
		bc_list: $bread
	}));

	$(".content-header small").html(act_name);
// });
/*
/* ==================================== */
/* Default action for Form Export Data */
/* ==================================== */
$( document ).ready(function() {

	/* Init form */
	$('form').each(function(e){
		var form = $(this);

		form.validator().on('submit', function(e) {
			if (e.isDefaultPrevented()) { return false;	}
			e.preventDefault();

			form.find("[type='submit']").prop( "disabled", true );

			var data = form.serializeOBJ();

			$.getJSON( $BASE_URL+$class+'/'+$method, { export:1, pageid:$pageid, filter:$filter, ob:$ob, filetype:data.filetype, is_compress:data.is_compress }, function(result){
				if (!result.status) {
					BootstrapDialog.alert(result.message);
					form.find("[type='submit']").prop( "disabled", false );
				} else {
					console.log(result);
					window.open(result.file_url);

					setTimeout(function(){ window.history.back(); }, 500);
				}
			});

			return false;
		});
	});

});
<commit_msg>Updates<commit_after>/*!
 * export_data.js v1.0.0
 * Copyright 2016, Ahmad Firuze
 *
 * Freely distributable under the MIT license.
 * Portions of G.ENE.SYS Ultimate - Manufacturing Systems
 *
 * A script file to support export_data.tpl
 */
/* Get Params */
var id = getURLParameter("id"),
	$pageid = getURLParameter("pageid"),
	$filter = getURLParameter("filter"),
	$ob = getURLParameter("ob"),
	act = getURLParameter("action"),
	act_name = "(Exporting Data From Database)";
/*
/* ========================================= */
/* Default init for Header									 */
/* ========================================= */

// $( document ).ready(function() {
	/* Start :: Init for Title, Breadcrumb */
	// console.log($bread);
	// console.log($bread.length);
	$(document).prop('title', $HEAD_TITLE+' > '+$bread[$bread.length-1].title);
	$bread.unshift({ icon:"fa fa-dashboard", title:"Dashboard", link: "window.location.replace('"+$APPS_LNK+"')" });
	$(".content").before(BSHelper.PageHeader({
		bc_list: $bread
	}));

	$(".content-header small").html(act_name);
// });
/*
/* ==================================== */
/* Default action for Form Export Data */
/* ==================================== */
$( document ).ready(function() {

	/* Init form */
	$('form').each(function(e){
		var form = $(this);

		form.validator().on('submit', function(e) {
			if (e.isDefaultPrevented()) { return false;	}
			e.preventDefault();

			form.find("[type='submit']").prop( "disabled", true );

			var data = form.serializeOBJ();

			$.getJSON( $BASE_URL+$class+'/'+$method, { export:1, pageid:$pageid, filter:$filter, ob:$ob, filetype:data.filetype, is_compress:data.is_compress }, function(result){
				if (!result.status) {
					BootstrapDialog.alert(result.message);
					form.find("[type='submit']").prop( "disabled", false );
				} else {
					console.log(result);
					window.open(result.file_url);

					// setTimeout(function(){ window.history.back(); }, 500);
				}
			});

			return false;
		});
	});

});
<|endoftext|>