<commit_before>var width = 500, height = 250;
var container = d3.select('#largest')
    .append('svg')
    .attr({'width': width, 'height': height});

// create a large amount of data
var dataGenerator = fc.data.random.financial()
    .startDate(new Date(2014, 1, 1));
var data = dataGenerator(1000);

// configure the sampler
var sampler = fc.data.sampler.modeMedian()
  .bucketSize(20)
  .value(function(d) { return d.low; });

// sample the data
var sampledData = sampler(data);

var xScale = fc.scale.dateTime()
    .domain(fc.util.extent().fields('date')(sampledData))
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain(fc.util.extent().fields('low')(sampledData))
    .range([height, 0]);

// render the sampled data
var sampledLine = fc.series.line()
    .xScale(xScale)
    .yScale(yScale)
    .yValue(function(d) { return d.low; });

container.append('g')
    .datum(sampledData)
    .call(sampledLine);

// render the original data
var originalLine = fc.series.line()
    .xScale(xScale)
    .yScale(yScale)
    .yValue(function(d) { return d.low; })
    .decorate(function(selection) {
        selection.enter().style('stroke-opacity', '0.5');
    });

container.append('g')
    .datum(data)
    .call(originalLine);
<commit_msg>Specify correct xValue accessor for site Mode Median sampler example<commit_after>var width = 500, height = 250;
var container = d3.select('#largest')
    .append('svg')
    .attr({'width': width, 'height': height});

// create a large amount of data
var dataGenerator = fc.data.random.financial()
    .startDate(new Date(2014, 1, 1));
var data = dataGenerator(1000);

// configure the sampler
var sampler = fc.data.sampler.modeMedian()
  .bucketSize(20)
  .value(function(d) { return d.low; });

// sample the data
var sampledData = sampler(data);

var xScale = fc.scale.dateTime()
    .domain(fc.util.extent().fields('date')(sampledData))
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain(fc.util.extent().fields('low')(sampledData))
    .range([height, 0]);

// render the sampled data
var sampledLine = fc.series.line()
    .xScale(xScale)
    .yScale(yScale)
    .xValue(function(d) { return d.date; })
    .yValue(function(d) { return d.low; });

container.append('g')
    .datum(sampledData)
    .call(sampledLine);

// render the original data
var originalLine = fc.series.line()
    .xScale(xScale)
    .yScale(yScale)
    .xValue(function(d) { return d.date; })
    .yValue(function(d) { return d.low; })
    .decorate(function(selection) {
        selection.enter().style('stroke-opacity', '0.5');
    });

container.append('g')
    .datum(data)
    .call(originalLine);
<|endoftext|>


<commit_before>define([
  'src/util/api',
  './yamlParser',
  'src/util/ui',
  './getViewInfo',
], function (API, yamlParser, UI, getViewInfo) {
  let tipsURL = 'https://docs.cheminfo.org/tips/';
  let pagesURL = 'https://docs.cheminfo.org/pages/';
  let minDelayBetweenTips = 4 * 3600 * 1000;

  async function showTips(info) {
    if (!info) info = await getViewInfo();
    if (!info._id) return;

    //  info._id='15c9a2dcd55c963fdedf2c18a1471b03';
    //  info.rev=90;
    // retrieve tips toc
    await fetch(`${tipsURL + info._id}/index.yml`)
      .then(async (response) => {
        let text = await response.text();
        processTipsToc(text, info);
      })
      .catch();
  }

  function processTipsToc(yaml, info) {
    let toc = yamlParser.parse(yaml);
    if (!toc.tips) return;
    let userPrefs = JSON.parse(
      window.localStorage.getItem('tipsPreferences') ||
        '{"lastTip":0, "views":{}}',
    );
    if ((Date.now() - userPrefs.lastTip || 0) < minDelayBetweenTips) return;
    if (!userPrefs.views[info._id]) {
      userPrefs.views[info._id] = { lastIndex: -1 };
    }
    let viewPrefs = userPrefs.views[info._id];
    let tips = toc.tips
      .map((a, index) => {
        a.index = a.index === undefined ? index + 1 : a.index;
        return a;
      })
      .sort((a, b) => a.index - b.index)
      .filter((a) => a.index > viewPrefs.lastIndex)
      .filter((a) => info.rev >= (a.minRev || 0))
      .filter((a) => info.rev <= (a.maxRev || Number.MAX_SAFE_INTEGER));
    if (tips.length > 0) {
      viewPrefs.lastIndex = tips[0].index;
      userPrefs.lastTip = Date.now();
      window.localStorage.setItem('tipsPreferences', JSON.stringify(userPrefs));
      UI.dialog(
        `

        `,
        { width: 800, height: 600, title: 'Did you know ?' },
      );
    }
  }

  async function addPageHelp(options = {}) {
    const { iconSize = 'fa-3x' } = options;
    let info =
      options._id === undefined ? await getViewInfo() : { _id: options._id };
    if (!info._id) return;

    await fetch(`${pagesURL + info._id}/index.html`, { method: 'HEAD' })
      .then(async () => {})
      .catch();

    let target = document.getElementById('modules-grid');
    let div = document.createElement('DIV');
    div.innerHTML = `

      `;
    div.style.zIndex = 99;
    div.style.position = 'fixed';

    div.addEventListener('click', () => {
      UI.dialog(
        `

        `,
        { width: 900, height: 700, title: 'Information about the page' },
      );
    });

    target.prepend(div);

    window.addEventListener(
      'keypress',
      (event) => {
        if (
          event.altKey &&
          event.shiftKey &&
          event.ctrlKey &&
          event.keyCode === 8
        ) {
          UI.dialog(
            `

            `,
            { width: 900, height: 700, title: 'Information about the page' },
          );
        }
      },
      false,
    );
  }

  return {
    showTips,
    addPageHelp,
  };
});
<commit_msg>feat: use relative link to docs<commit_after>define([
  'src/util/api',
  './yamlParser',
  'src/util/ui',
  './getViewInfo',
], function (API, yamlParser, UI, getViewInfo) {
  let baseUrl = require.s.contexts._.config.baseUrl;

  let tipsURL = baseUrl + '../../docs/tips/';
  let pagesURL = baseUrl + '../../docs/pages/';
  let minDelayBetweenTips = 4 * 3600 * 1000;

  async function showTips(info) {
    if (!info) info = await getViewInfo();
    if (!info._id) return;

    //  info._id='15c9a2dcd55c963fdedf2c18a1471b03';
    //  info.rev=90;
    // retrieve tips toc
    await fetch(`${tipsURL + info._id}/index.yml`)
      .then(async (response) => {
        let text = await response.text();
        processTipsToc(text, info);
      })
      .catch();
  }

  function processTipsToc(yaml, info) {
    let toc = yamlParser.parse(yaml);
    if (!toc.tips) return;
    let userPrefs = JSON.parse(
      window.localStorage.getItem('tipsPreferences') ||
        '{"lastTip":0, "views":{}}',
    );
    if ((Date.now() - userPrefs.lastTip || 0) < minDelayBetweenTips) return;
    if (!userPrefs.views[info._id]) {
      userPrefs.views[info._id] = { lastIndex: -1 };
    }
    let viewPrefs = userPrefs.views[info._id];
    let tips = toc.tips
      .map((a, index) => {
        a.index = a.index === undefined ? index + 1 : a.index;
        return a;
      })
      .sort((a, b) => a.index - b.index)
      .filter((a) => a.index > viewPrefs.lastIndex)
      .filter((a) => info.rev >= (a.minRev || 0))
      .filter((a) => info.rev <= (a.maxRev || Number.MAX_SAFE_INTEGER));
    if (tips.length > 0) {
      viewPrefs.lastIndex = tips[0].index;
      userPrefs.lastTip = Date.now();
      window.localStorage.setItem('tipsPreferences', JSON.stringify(userPrefs));
      UI.dialog(
        `

        `,
        { width: 800, height: 600, title: 'Did you know ?' },
      );
    }
  }

  async function addPageHelp(options = {}) {
    const { iconSize = 'fa-3x' } = options;
    let info =
      options._id === undefined ? await getViewInfo() : { _id: options._id };
    if (!info._id) return;

    await fetch(`${pagesURL + info._id}/index.html`, { method: 'HEAD' })
      .then(async () => {})
      .catch();

    let target = document.getElementById('modules-grid');
    let div = document.createElement('DIV');
    div.innerHTML = `

      `;
    div.style.zIndex = 99;
    div.style.position = 'fixed';

    div.addEventListener('click', () => {
      UI.dialog(
        `

        `,
        { width: 900, height: 700, title: 'Information about the page' },
      );
    });

    target.prepend(div);

    window.addEventListener(
      'keypress',
      (event) => {
        if (
          event.altKey &&
          event.shiftKey &&
          event.ctrlKey &&
          event.keyCode === 8
        ) {
          UI.dialog(
            `

            `,
            { width: 900, height: 700, title: 'Information about the page' },
          );
        }
      },
      false,
    );
  }

  return {
    showTips,
    addPageHelp,
  };
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const ModuleTransport = require('../lib/ModuleTransport');
const Promise = require('promise');
const declareOpts = require('../lib/declareOpts');
const fs = require('fs');
const temp = require('temp');
const util = require('util');
const workerFarm = require('worker-farm');
const debug = require('debug')('ReactNativePackager:JStransformer');

const readFile = Promise.denodeify(fs.readFile);

// Avoid memory leaks caused in workers. This number seems to be a good enough number
// to avoid any memory leak while not slowing down initial builds.
// TODO(amasad): Once we get bundle splitting, we can drive this down a bit more.
const MAX_CALLS_PER_WORKER = 600;

// Worker will timeout if one of the callers timeout.
const DEFAULT_MAX_CALL_TIME = 300000;

// How may times can we tolerate failures from the worker.
const MAX_RETRIES = 2;

const validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  transformModulePath: {
    type:'string',
    required: false,
  },
  cache: {
    type: 'object',
    required: true,
  },
  transformTimeoutInterval: {
    type: 'number',
    default: DEFAULT_MAX_CALL_TIME,
  },
  disableInternalTransforms: {
    type: 'boolean',
    default: false,
  },
});

class Transformer {
  constructor(options) {
    const opts = this._opts = validateOpts(options);

    this._cache = opts.cache;
    this._transformModulePath = opts.transformModulePath;

    if (opts.transformModulePath != null) {
      let transformer;

      if (opts.disableInternalTransforms) {
        transformer = opts.transformModulePath;
      } else {
        transformer = this._workerWrapperPath = temp.path();
        fs.writeFileSync(
          this._workerWrapperPath,
          `
          module.exports = require(${JSON.stringify(require.resolve('./worker'))});
          require(${JSON.stringify(String(opts.transformModulePath))});
          `
        );
      }

      this._workers = workerFarm({
        autoStart: true,
        maxConcurrentCallsPerWorker: 1,
        maxCallsPerWorker: MAX_CALLS_PER_WORKER,
        maxCallTime: opts.transformTimeoutInterval,
        maxRetries: MAX_RETRIES,
      }, transformer);

      this._transform = Promise.denodeify(this._workers);
    }
  }

  kill() {
    this._workers && workerFarm.end(this._workers);
    if (this._workerWrapperPath &&
        typeof this._workerWrapperPath === 'string') {
      fs.unlink(this._workerWrapperPath, () => {}); // we don't care about potential errors here
    }
  }

  invalidateFile(filePath) {
    this._cache.invalidate(filePath);
  }

  loadFileAndTransform(filePath, options) {
    if (this._transform == null) {
      return Promise.reject(new Error('No transfrom module'));
    }

    debug('transforming file', filePath);

    const optionsJSON = JSON.stringify(options);

    return this._cache.get(
      filePath,
      'transformedSource-' + optionsJSON,
      // TODO: use fastfs to avoid reading file from disk again
      () => readFile(filePath).then(
        buffer => {
          const sourceCode = buffer.toString('utf8');

          return this._transform({
            sourceCode,
            filename: filePath,
            options: {
              ...options,
              externalTransformModulePath: this._transformModulePath,
            },
          }).then(res => {
            if (res.error) {
              console.warn(
                'Error property on the result value from the transformer',
                'module is deprecated and will be removed in future versions.',
                'Please pass an error object as the first argument to the callback'
              );
              throw formatError(res.error, filePath);
            }

            debug('done transforming file', filePath);

            return new ModuleTransport({
              code: res.code,
              map: res.map,
              sourcePath: filePath,
              sourceCode: sourceCode,
            });
          }).catch(err => {
            if (err.type === 'TimeoutError') {
              const timeoutErr = new Error(
                `TimeoutError: transforming ${filePath} took longer than ` +
                `${this._opts.transformTimeoutInterval / 1000} seconds.\n` +
                `You can adjust timeout via the 'transformTimeoutInterval' option`
              );
              timeoutErr.type = 'TimeoutError';
              throw timeoutErr;
            } else if (err.type === 'ProcessTerminatedError') {
              const uncaughtError = new Error(
                'Uncaught error in the transformer worker: ' +
                this._opts.transformModulePath
              );
              uncaughtError.type = 'ProcessTerminatedError';
              throw uncaughtError;
            }

            throw formatError(err, filePath);
          });
        })
    );
  }
}

module.exports = Transformer;

Transformer.TransformError = TransformError;

function TransformError() {
  Error.captureStackTrace && Error.captureStackTrace(this, TransformError);
}
util.inherits(TransformError, SyntaxError);

function formatError(err, filename, source) {
  if (err.loc) {
    return formatBabelError(err, filename, source);
  } else {
    return formatGenericError(err, filename, source);
  }
}

function formatGenericError(err, filename) {
  var msg = 'TransformError: ' + filename + ': ' + err.message;
  var error = new TransformError();
  var stack = (err.stack || '').split('\n').slice(0, -1);
  stack.push(msg);
  error.stack = stack.join('\n');
  error.message = msg;
  error.type = 'TransformError';
  return error;
}

function formatBabelError(err, filename) {
  var error = new TransformError();
  error.type = 'TransformError';
  error.message = (err.type || error.type) + ' ' + err.message;
  error.stack = err.stack;
  error.snippet = err.codeFrame;
  error.lineNumber = err.loc.line;
  error.column = err.loc.column;
  error.filename = filename;
  error.description = err.message;
  return error;
}
<commit_msg>Bump timeout to track intermittent error<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const ModuleTransport = require('../lib/ModuleTransport');
const Promise = require('promise');
const declareOpts = require('../lib/declareOpts');
const fs = require('fs');
const temp = require('temp');
const util = require('util');
const workerFarm = require('worker-farm');
const debug = require('debug')('ReactNativePackager:JStransformer');

const readFile = Promise.denodeify(fs.readFile);

// Avoid memory leaks caused in workers. This number seems to be a good enough number
// to avoid any memory leak while not slowing down initial builds.
// TODO(amasad): Once we get bundle splitting, we can drive this down a bit more.
const MAX_CALLS_PER_WORKER = 600;

// Worker will timeout if one of the callers timeout.
const DEFAULT_MAX_CALL_TIME = 301000;

// How may times can we tolerate failures from the worker.
const MAX_RETRIES = 2;

const validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  transformModulePath: {
    type:'string',
    required: false,
  },
  cache: {
    type: 'object',
    required: true,
  },
  transformTimeoutInterval: {
    type: 'number',
    default: DEFAULT_MAX_CALL_TIME,
  },
  disableInternalTransforms: {
    type: 'boolean',
    default: false,
  },
});

class Transformer {
  constructor(options) {
    const opts = this._opts = validateOpts(options);

    this._cache = opts.cache;
    this._transformModulePath = opts.transformModulePath;

    if (opts.transformModulePath != null) {
      let transformer;

      if (opts.disableInternalTransforms) {
        transformer = opts.transformModulePath;
      } else {
        transformer = this._workerWrapperPath = temp.path();
        fs.writeFileSync(
          this._workerWrapperPath,
          `
          module.exports = require(${JSON.stringify(require.resolve('./worker'))});
          require(${JSON.stringify(String(opts.transformModulePath))});
          `
        );
      }

      this._workers = workerFarm({
        autoStart: true,
        maxConcurrentCallsPerWorker: 1,
        maxCallsPerWorker: MAX_CALLS_PER_WORKER,
        maxCallTime: opts.transformTimeoutInterval,
        maxRetries: MAX_RETRIES,
      }, transformer);

      this._transform = Promise.denodeify(this._workers);
    }
  }

  kill() {
    this._workers && workerFarm.end(this._workers);
    if (this._workerWrapperPath &&
        typeof this._workerWrapperPath === 'string') {
      fs.unlink(this._workerWrapperPath, () => {}); // we don't care about potential errors here
    }
  }

  invalidateFile(filePath) {
    this._cache.invalidate(filePath);
  }

  loadFileAndTransform(filePath, options) {
    if (this._transform == null) {
      return Promise.reject(new Error('No transfrom module'));
    }

    debug('transforming file', filePath);

    const optionsJSON = JSON.stringify(options);

    return this._cache.get(
      filePath,
      'transformedSource-' + optionsJSON,
      // TODO: use fastfs to avoid reading file from disk again
      () => readFile(filePath).then(
        buffer => {
          const sourceCode = buffer.toString('utf8');

          return this._transform({
            sourceCode,
            filename: filePath,
            options: {
              ...options,
              externalTransformModulePath: this._transformModulePath,
            },
          }).then(res => {
            if (res.error) {
              console.warn(
                'Error property on the result value from the transformer',
                'module is deprecated and will be removed in future versions.',
                'Please pass an error object as the first argument to the callback'
              );
              throw formatError(res.error, filePath);
            }

            debug('done transforming file', filePath);

            return new ModuleTransport({
              code: res.code,
              map: res.map,
              sourcePath: filePath,
              sourceCode: sourceCode,
            });
          }).catch(err => {
            if (err.type === 'TimeoutError') {
              const timeoutErr = new Error(
                `TimeoutError: transforming ${filePath} took longer than ` +
                `${this._opts.transformTimeoutInterval / 1000} seconds.\n` +
                `You can adjust timeout via the 'transformTimeoutInterval' option`
              );
              timeoutErr.type = 'TimeoutError';
              throw timeoutErr;
            } else if (err.type === 'ProcessTerminatedError') {
              const uncaughtError = new Error(
                'Uncaught error in the transformer worker: ' +
                this._opts.transformModulePath
              );
              uncaughtError.type = 'ProcessTerminatedError';
              throw uncaughtError;
            }

            throw formatError(err, filePath);
          });
        })
    );
  }
}

module.exports = Transformer;

Transformer.TransformError = TransformError;

function TransformError() {
  Error.captureStackTrace && Error.captureStackTrace(this, TransformError);
}
util.inherits(TransformError, SyntaxError);

function formatError(err, filename, source) {
  if (err.loc) {
    return formatBabelError(err, filename, source);
  } else {
    return formatGenericError(err, filename, source);
  }
}

function formatGenericError(err, filename) {
  var msg = 'TransformError: ' + filename + ': ' + err.message;
  var error = new TransformError();
  var stack = (err.stack || '').split('\n').slice(0, -1);
  stack.push(msg);
  error.stack = stack.join('\n');
  error.message = msg;
  error.type = 'TransformError';
  return error;
}

function formatBabelError(err, filename) {
  var error = new TransformError();
  error.type = 'TransformError';
  error.message = (err.type || error.type) + ' ' + err.message;
  error.stack = err.stack;
  error.snippet = err.codeFrame;
  error.lineNumber = err.loc.line;
  error.column = err.loc.column;
  error.filename = filename;
  error.description = err.message;
  return error;
}
<|endoftext|>


<commit_before>import { dialog, app, Menu } from 'electron';

import launch from './launch';

export const file = {
  label: '&File',
  submenu: [
    {
      label: '&Open',
      click: () => {
        const opts = {
          title: 'Open a notebook',
          filters: [
            { name: 'Notebooks', extensions: ['ipynb'] },
          ],
          properties: [
            'openFile',
          ],
          defaultPath: process.cwd(),
        };
        dialog.showOpenDialog(opts, (fname) => {
          launch(fname);
        });
      },
      accelerator: 'CmdOrCtrl+O',
    },
    {
      type: 'separator',
    },
    {
      label: '&Quit',
      action: ['killKernel', 'exit'],
      accelerator: 'CmdOrCtrl+Q',
    },
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
  ],
};

export const window = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { require('electron').shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = app.getName();
export const named = {
  label: name,
  submenu: [
    {
      label: 'About ' + name,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: 'Hide ' + name,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => { app.quit(); },
    },
  ],
};

const template = [];

if(process.platform === 'darwin') {
  template.push(named);
  window.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

template.push(file);
template.push(edit);
template.push(view);

export const defaultMenu = Menu.buildFromTemplate(template);
<commit_msg>Problem: quit is duplicated in menus<commit_after>import { dialog, app, Menu } from 'electron';

import launch from './launch';

export const file = {
  label: '&File',
  submenu: [
    {
      label: '&Open',
      click: () => {
        const opts = {
          title: 'Open a notebook',
          filters: [
            { name: 'Notebooks', extensions: ['ipynb'] },
          ],
          properties: [
            'openFile',
          ],
          defaultPath: process.cwd(),
        };
        dialog.showOpenDialog(opts, (fname) => {
          launch(fname);
        });
      },
      accelerator: 'CmdOrCtrl+O',
    },
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
  ],
};

export const window = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { require('electron').shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = app.getName();
export const named = {
  label: name,
  submenu: [
    {
      label: 'About ' + name,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: 'Hide ' + name,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => { app.quit(); },
    },
  ],
};

const template = [];

if(process.platform === 'darwin') {
  template.push(named);
  window.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

template.push(file);
template.push(edit);
template.push(view);

export const defaultMenu = Menu.buildFromTemplate(template);
<|endoftext|>


<commit_before>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},

	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	"addItem": function(item, countrydef, search, distance, quickentry, enabled) {
		var textLink = '';
		var classes = (enabled ? 'enabled' : 'disabled');
//		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon && this.parent.Utils.options.get('showIcon', true)) {
			textLink += '';
			clear = true;
		}

		if (quickentry) {
//			textLink += '↵';
			textLink += '↵';
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '— ' + search + '';
		} else if (item.descr) {
			textLink += '— ' +  item.descr + '';
		}

		if (
				(countrydef || (distance != undefined))
				&& this.parent.Utils.options.get('showLocationInfo', true)
			) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';

			if (item.subID) {
				textLink += '<input value="' + item.subID + '" />';
			}

			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		var relID = item.entityID;
		if (item.subID) {
			relID += '#' + item.subID;
		}

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"setScreen": function (content) {
		$("div.discojuice_listContent").hide();
		$("div#locatemediv").hide();
		$("div#search").hide();
		$("div.filters p.discojuice_filter_country").hide();

		$("div#discojuice_page div.discojuice_content").html(content);

		$("div#discojuice_page").show();
		$("div#discojuice_page_return").show();

		console.log($("div#discojuice_page"));

	},

	"returnToProviderList": function () {
		$("div.discojuice_listContent").show();
		$("div#discojuice_page").hide();
		$("div#discojuice_page_return").hide();
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				event.stopPropagation();
				//overthere.hide();

				// The "rel" attribute is containing: 'entityid#subid'
				// THe following code, decodes that.
				var relID = unescape($(this).attr('rel'));
				var entityID = relID;
				var subID = undefined;
				if (relID.match(/^.*#.+?$/)) {
					var matched = /^(.*)#(.+?)$/.exec(relID);
					entityID = matched[1];
					subID = matched[2];
				}
				overthere.control.selectProvider(entityID, subID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(event) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"error": function(message) {
		console.log("error" + message);
		this.popup.find("div#discojuice_error").show();
		this.popup.find("div.discojuice_errortext").append('
' + message + '
');
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var textSearch = this.parent.Utils.options.get('textSearch', 'or search for a provider, in example Univerity of Oslo');
		var textHelp = this.parent.Utils.options.get('textHelp', 'Help me, I cannot find my provider');
		var textHelpMore = this.parent.Utils.options.get('textHelpMore', 'If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).');

		var subtitleText = this.parent.Utils.options.get('subtitle', null);
		var subtitleHTML = (subtitleText !== null ? '
' + subtitleText + '
' : '');

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				subtitleHTML +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
' +
				'
' +
			'
' +

			'
' +
				'
' +
				'<input id="discojuice_returntoproviderlist" type="submit" value="« Return to list of providers" />' +
				'
' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="' + textSearch + '" value="" />
' +
				'
' +
					'' + textHelp + '' +
					'
' + textHelpMore + '
' +
				'
' +
			'
' +

			'
' +
				'' +
				'
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me and show nearby providers' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'<button id="discojuiceextesion_listener" />' +
			'
' +

			'
' +
//				'
Settings
' +
				'
DiscoJuice © UNINETT
' +

			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		this.popup.find("#discojuiceextesion_listener").click(function() {
			that.control.discojuiceextension();
		});

		this.popup.find("#discojuice_page_return input").click(function(e) {
			e.preventDefault();
			that.returnToProviderList();
		});

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("a#locateme").click(function(event) {
				that.parent.Utils.log('Locate me. Detected click event.');
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';
				event.preventDefault();
 				event.stopPropagation();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("dd#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<commit_msg>Hide location bar properly if turned off in configuration...<commit_after>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},

	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	"addItem": function(item, countrydef, search, distance, quickentry, enabled) {
		var textLink = '';
		var classes = (enabled ? 'enabled' : 'disabled');
//		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon && this.parent.Utils.options.get('showIcon', true)) {
			textLink += '';
			clear = true;
		}

		if (quickentry) {
//			textLink += '↵';
			textLink += '↵';
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '— ' + search + '';
		} else if (item.descr) {
			textLink += '— ' +  item.descr + '';
		}

		if (
				(countrydef || (distance != undefined))
				&& this.parent.Utils.options.get('showLocationInfo', true)
			) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';

			if (item.subID) {
				textLink += '<input value="' + item.subID + '" />';
			}

			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		var relID = item.entityID;
		if (item.subID) {
			relID += '#' + item.subID;
		}

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"setScreen": function (content) {
		$("div.discojuice_listContent").hide();
		$("div#locatemediv").hide();
		$("div#search").hide();
		$("div.filters p.discojuice_filter_country").hide();

		$("div#discojuice_page div.discojuice_content").html(content);

		$("div#discojuice_page").show();
		$("div#discojuice_page_return").show();

		console.log($("div#discojuice_page"));

	},

	"returnToProviderList": function () {
		$("div.discojuice_listContent").show();
		$("div#discojuice_page").hide();
		$("div#discojuice_page_return").hide();
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				event.stopPropagation();
				//overthere.hide();

				// The "rel" attribute is containing: 'entityid#subid'
				// THe following code, decodes that.
				var relID = unescape($(this).attr('rel'));
				var entityID = relID;
				var subID = undefined;
				if (relID.match(/^.*#.+?$/)) {
					var matched = /^(.*)#(.+?)$/.exec(relID);
					entityID = matched[1];
					subID = matched[2];
				}
				overthere.control.selectProvider(entityID, subID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(event) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"error": function(message) {
		console.log("error" + message);
		this.popup.find("div#discojuice_error").show();
		this.popup.find("div.discojuice_errortext").append('
' + message + '
');
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var textSearch = this.parent.Utils.options.get('textSearch', 'or search for a provider, in example Univerity of Oslo');
		var textHelp = this.parent.Utils.options.get('textHelp', 'Help me, I cannot find my provider');
		var textHelpMore = this.parent.Utils.options.get('textHelpMore', 'If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).');

		var subtitleText = this.parent.Utils.options.get('subtitle', null);
		var subtitleHTML = (subtitleText !== null ? '
' + subtitleText + '
' : '');

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				subtitleHTML +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
' +
				'
' +
			'
' +

			'
' +
				'
' +
				'<input id="discojuice_returntoproviderlist" type="submit" value="« Return to list of providers" />' +
				'
' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="' + textSearch + '" value="" />
' +
				'
' +
					'' + textHelp + '' +
					'
' + textHelpMore + '
' +
				'
' +
			'
' +

			'
' +
				'' +
				'
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me and show nearby providers' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'<button id="discojuiceextesion_listener" />' +
			'
' +

			'
' +
//				'
Settings
' +
				'
DiscoJuice © UNINETT
' +

			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		this.popup.find("#discojuiceextesion_listener").click(function() {
			that.control.discojuiceextension();
		});

		this.popup.find("#discojuice_page_return input").click(function(e) {
			e.preventDefault();
			that.returnToProviderList();
		});

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("a#locateme").click(function(event) {
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';

				that.parent.Utils.log('Locate me. Detected click event.');
				event.preventDefault();
 				event.stopPropagation();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("div#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<|endoftext|>


<commit_before>/**
 * @author Raoul Harel
 * @license The MIT license (LICENSE.txt)
 * @copyright 2015 Raoul Harel
 * @url https://github.com/rharel/webgl-dm-voronoi
 */

function Diagram(options) {

  options = _parseOptions(options);

  if (options.canvas === null) {
    this._canvas = _createCanvas(options.width, options.height);
  }
  else {
    this._canvas = options.canvas;
  }

  this._3D = new Context3D(this._canvas);

  this._precision = options.precision;
  this._distanceMeasure = options._distanceMeasure;

  this._sites = [];

  this._maxDistance = Math.max(this._canvas.width, this._canvas.height);

  this._pointDG = PointSite.distanceGeometry(
    this._maxDistance,
    this._precision,
    this._distanceMeasure
  );

  function _parseOptions(options) {
    var defaultOptions = {
      canvas: null,
      width: 500, height: 500,
      precision: 16,
      _distanceMeasure: Distance.euclidean
    };

    if (typeof options === 'undefined') {
      return defaultOptions;
    }
    else {
      options.canvas = options.canvas || null;
      options.width = +options.width || defaultOptions.width;
      options.height = +options.height || defaultOptions.height;
      options.precision = +options.precision || defaultOptions.precision;
      options._distanceMeasure =
        options._distanceMeasure || defaultOptions._distanceMeasure;

      return options;
    }
  }

  function _createCanvas(width, height) {
    var canvas = document.createElement('canvas');

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

    return canvas;
  }
}

Diagram.prototype = {

  constructor: Diagram,

  point: function(x, y, color) {

    if (typeof color === 'string') {
      color = new THREE.Color(color);
    }
    else {
      color = new THREE.Color(color.r, color.g, color.b);
    }

    var mesh = new THREE.Mesh(this._pointDG, this._3D.material(color));
    var site = new PointSite(x, y, mesh);

    this._sites.push(site);
    this._3D.add(mesh);
  },

  render: function() { this._3D.render(); },

  get canvas() { return this._canvas; },

  get precision() { return this._precision; },
  set precision(value) { this._precision = value; },

  get nSites() { return this._sites.length; }
};
<commit_msg>Removed precision setter<commit_after>/**
 * @author Raoul Harel
 * @license The MIT license (LICENSE.txt)
 * @copyright 2015 Raoul Harel
 * @url https://github.com/rharel/webgl-dm-voronoi
 */

function Diagram(options) {

  options = _parseOptions(options);

  if (options.canvas === null) {
    this._canvas = _createCanvas(options.width, options.height);
  }
  else {
    this._canvas = options.canvas;
  }

  this._3D = new Context3D(this._canvas);

  this._precision = options.precision;
  this._distanceMeasure = options._distanceMeasure;

  this._sites = [];

  this._maxDistance = Math.max(this._canvas.width, this._canvas.height);

  this._pointDistanceGeometry =
    PointSite.distanceGeometry(
      this._maxDistance,
      this._precision,
      this._distanceMeasure
  );

  function _parseOptions(options) {
    var defaultOptions = {
      canvas: null,
      width: 500, height: 500,
      precision: 16,
      _distanceMeasure: Distance.euclidean
    };

    if (typeof options === 'undefined') {
      return defaultOptions;
    }
    else {
      options.canvas = options.canvas || null;
      options.width = +options.width || defaultOptions.width;
      options.height = +options.height || defaultOptions.height;
      options.precision = +options.precision || defaultOptions.precision;
      options._distanceMeasure =
        options._distanceMeasure || defaultOptions._distanceMeasure;

      return options;
    }
  }

  function _createCanvas(width, height) {
    var canvas = document.createElement('canvas');

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

    return canvas;
  }
}

Diagram.prototype = {

  constructor: Diagram,

  point: function(x, y, color) {

    if (typeof color === 'string') {
      color = new THREE.Color(color);
    }
    else {
      color = new THREE.Color(color.r, color.g, color.b);
    }

    var mesh = new THREE.Mesh(
      this._pointDistanceGeometry,
      this._3D.material(color)
    );
    var site = new PointSite(x, y, mesh);

    this._sites.push(site);
    this._3D.add(mesh);
  },

  render: function() { this._3D.render(); },

  get canvas() { return this._canvas; },

  get precision() { return this._precision; },

  get nSites() { return this._sites.length; }
};
<|endoftext|>


<commit_before>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off", no-negated-condition: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    return function createAccessory_ContactSensor(settings) {
        const sensor = newAccessory(settings);

        sensor.addService(Service.ContactSensor, settings.name)
            .getCharacteristic(Characteristic.ContactSensorState)
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'ContactSensorState');
                const contact = mqttStatus[settings.topic.statusContactSensorState] === settings.payload.onContactDetected ?
                    Characteristic.ContactSensorState.CONTACT_DETECTED :
                    Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;

                log.debug('> hap re_get', settings.name, 'ContactSensorState', contact);
                callback(null, contact);
            });

        mqttSub(settings.topic.statusContactSensorState, val => {
            const contact = val === settings.payload.onContactDetected ?
                Characteristic.ContactSensorState.CONTACT_DETECTED :
                Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
            log.debug('> hap update', settings.name, 'ContactSensorState', contact);
            sensor.getService(Service.ContactSensor)
                .updateCharacteristic(Characteristic.ContactSensorState, contact);
        });

        if (settings.topic.statusLowBattery) {
            sensor.getService(Service.ContactSensor, settings.name)
                .getCharacteristic(Characteristic.StatusLowBattery)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusLowBattery');
                    const bat = mqttStatus[settings.topic.statusLowBattery] !== settings.payload.onLowBattery ?
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                    log.debug('> hap re_get', settings.name, 'StatusLowBattery', bat);
                    callback(null, bat);
                });

            mqttSub(settings.topic.statusLowBattery, val => {
                const bat = val !== settings.payload.onLowBattery ?
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                log.debug('> hap update', settings.name, 'StatusLowBattery', bat);
                sensor.getService(Service.ContactSensor)
                    .updateCharacteristic(Characteristic.StatusLowBattery, bat);
            });
        }

        return sensor;
    };
};
<commit_msg>istanbul ignore<commit_after>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off", no-negated-condition: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    return function createAccessory_ContactSensor(settings) {
        const sensor = newAccessory(settings);

        sensor.addService(Service.ContactSensor, settings.name)
            .getCharacteristic(Characteristic.ContactSensorState)
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'ContactSensorState');
                const contact = mqttStatus[settings.topic.statusContactSensorState] === settings.payload.onContactDetected ?
                    Characteristic.ContactSensorState.CONTACT_DETECTED :
                    Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;

                log.debug('> hap re_get', settings.name, 'ContactSensorState', contact);
                callback(null, contact);
            });

        mqttSub(settings.topic.statusContactSensorState, val => {
            const contact = val === settings.payload.onContactDetected ?
                Characteristic.ContactSensorState.CONTACT_DETECTED :
                Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
            log.debug('> hap update', settings.name, 'ContactSensorState', contact);
            sensor.getService(Service.ContactSensor)
                .updateCharacteristic(Characteristic.ContactSensorState, contact);
        });

        /* istanbul ignore else */
        if (settings.topic.statusLowBattery) {
            sensor.getService(Service.ContactSensor, settings.name)
                .getCharacteristic(Characteristic.StatusLowBattery)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusLowBattery');
                    const bat = mqttStatus[settings.topic.statusLowBattery] !== settings.payload.onLowBattery ?
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                    log.debug('> hap re_get', settings.name, 'StatusLowBattery', bat);
                    callback(null, bat);
                });

            mqttSub(settings.topic.statusLowBattery, val => {
                const bat = val !== settings.payload.onLowBattery ?
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                log.debug('> hap update', settings.name, 'StatusLowBattery', bat);
                sensor.getService(Service.ContactSensor)
                    .updateCharacteristic(Characteristic.StatusLowBattery, bat);
            });
        }

        return sensor;
    };
};
<|endoftext|>


<commit_before>import * as types from 'constants/action_types'
import lbry from 'lbry'
import lbryio from 'lbryio'
import lbryuri from 'lbryuri'
import lighthouse from 'lighthouse'
import {
  selectSearchQuery,
} from 'selectors/search'
import {
  doResolveUri,
} from 'actions/content'

export function doSearchContent(query) {
  return function(dispatch, getState) {
    const state = getState()

    if (!query) {
      return dispatch({
        type: types.SEARCH_CANCELLED,
      })
    }

    dispatch({
      type: types.SEARCH_STARTED,
      data: { query }
    })

    lighthouse.search(query).then(results => {
      results.forEach(result => {
        const uri = lbryuri.build({
          channelName: result.channel_name,
          contentName: result.name,
          claimId: result.channel_id || result.claim_id,
        })
        dispatch(doResolveUri(uri))
      })

      dispatch({
        type: types.SEARCH_COMPLETED,
        data: {
          query,
          results,
        }
      })
    })
  }
}

export function doActivateSearch() {
  return {
    type: types.ACTIVATE_SEARCH,
  }
}

export function doDeactivateSearch() {
  return {
    type: types.DEACTIVATE_SEARCH,
  }
}
<commit_msg>even smarter search<commit_after>import * as types from 'constants/action_types'
import lbry from 'lbry'
import lbryio from 'lbryio'
import lbryuri from 'lbryuri'
import lighthouse from 'lighthouse'
import {
  selectSearchQuery,
} from 'selectors/search'
import {
  doResolveUri,
} from 'actions/content'
import {
  doNavigate,
} from 'actions/app'
import {
  selectCurrentPage,
} from 'selectors/app'

export function doSearchContent(query) {
  return function(dispatch, getState) {
    const state = getState()
    const page = selectCurrentPage(state)

    if (!query) {
      return dispatch({
        type: types.SEARCH_CANCELLED,
      })
    }

    dispatch({
      type: types.SEARCH_STARTED,
      data: { query }
    })

    if(page != 'discover' && query != undefined) dispatch(doNavigate('discover'))

    lighthouse.search(query).then(results => {
      results.forEach(result => {
        const uri = lbryuri.build({
          channelName: result.channel_name,
          contentName: result.name,
          claimId: result.channel_id || result.claim_id,
        })
        dispatch(doResolveUri(uri))
      })

      dispatch({
        type: types.SEARCH_COMPLETED,
        data: {
          query,
          results,
        }
      })
    })
  }
}

export function doActivateSearch() {
  return function(dispatch, getState) {
    const state = getState()
    const page = selectCurrentPage(state)
    const query = selectSearchQuery(state)

    if(page != 'discover' && query != undefined) dispatch(doNavigate('discover'))

    dispatch({
      type: types.ACTIVATE_SEARCH,
    })
  }
}

export function doDeactivateSearch() {
  return {
    type: types.DEACTIVATE_SEARCH,
  }
}
<|endoftext|>


<commit_before>/*
 * Book Summary Text View
 */
(function(gv) {
    var View = gv.View,
        state = gv.state,
        settings = gv.settings,
        // map styles
        mapStyle = settings.mapStyle,
        colorThemes = settings.colorThemes;

    // View: BookSummaryTextView (text content for the book summary)
    gv.BookSummaryMapView = View.extend({
        el: '#book-summary-map-view',

        // render and update functions

        layout: function() {
            $(this.el).height(
                this.topViewHeight() * .8 - 10 - $('#book-summary-text-view').height()
            )
            .width(
                this.topViewWidth() - 450
            );
        },

        render: function() {
            this.bindingLayout();

            var book = this.model,
                gmaps = google.maps,
                colorScale = d3.scale.quantize()
                    .domain([1, book.places.first().get('frequency')])
                    .range(colorThemes),
                bounds = book.gmapBounds(),
                gmap = new gmaps.Map(this.el, {
                    center: bounds.getCenter(),
                    zoom: 4,
                    mapTypeId: gmaps.MapTypeId.TERRAIN,
                    streetViewControl: false,
                    styles: mapStyle
                });

            // set bounds
            gmap.fitBounds(bounds);

            book.places.each(function(place) {
                var theme = colorScale(place.get('frequency')),
                    w = 10,
                    c = w/2,
                    icon = TimeMapTheme.getCircleUrl(w, theme.color, '99');
                    size = new gmaps.Size(w, w),
                    anchor = new gmaps.Point(c, c),
                    marker = new gmaps.Marker({
                        icon: new gmaps.MarkerImage(
                            icon,
                            size,
                            new gmaps.Point(0,0),
                            anchor,
                            size
                        ),
                        position: place.gmapLatLng(),
                        map: gmap,
                        title: place.get('title')
                    });
                // UI listener
                gmaps.event.addListener(marker, 'click', function() {
                    state.set({ placeid: place.id });
                    state.set({ topview: gv.BookPlaceView });
                });
            });

        }
    });

}(gv));<commit_msg>storing markers to enable testing<commit_after>/*
 * Book Summary Text View
 */
(function(gv) {
    var View = gv.View,
        state = gv.state,
        settings = gv.settings,
        // map styles
        mapStyle = settings.mapStyle,
        colorThemes = settings.colorThemes;

    // View: BookSummaryTextView (text content for the book summary)
    gv.BookSummaryMapView = View.extend({
        el: '#book-summary-map-view',

        // render and update functions

        layout: function() {
            $(this.el).height(
                this.topViewHeight() * .8 - 10 - $('#book-summary-text-view').height()
            )
            .width(
                this.topViewWidth() - 450
            );
        },

        render: function() {
            this.bindingLayout();

            var book = this.model,
                markers = this.markers = [],
                gmaps = google.maps,
                colorScale = d3.scale.quantize()
                    .domain([1, book.places.first().get('frequency')])
                    .range(colorThemes),
                bounds = book.gmapBounds(),
                gmap = new gmaps.Map(this.el, {
                    center: bounds.getCenter(),
                    zoom: 4,
                    mapTypeId: gmaps.MapTypeId.TERRAIN,
                    streetViewControl: false,
                    styles: mapStyle
                });

            // set bounds
            gmap.fitBounds(bounds);

            book.places.each(function(place) {
                var theme = colorScale(place.get('frequency')),
                    w = 10,
                    c = w/2,
                    icon = TimeMapTheme.getCircleUrl(w, theme.color, '99');
                    size = new gmaps.Size(w, w),
                    anchor = new gmaps.Point(c, c),
                    marker = new gmaps.Marker({
                        icon: new gmaps.MarkerImage(
                            icon,
                            size,
                            new gmaps.Point(0,0),
                            anchor,
                            size
                        ),
                        position: place.gmapLatLng(),
                        map: gmap,
                        title: place.get('title')
                    });
                // UI listener
                gmaps.event.addListener(marker, 'click', function() {
                    state.set({ placeid: place.id });
                    state.set({ topview: gv.BookPlaceView });
                });
                markers.push(marker);
            });

        }
    });

}(gv));<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const path = require('path');
const tryCatch = require('try-catch');
const squad = require('squad');
const readjson = require('readjson');

const mapsome = require('mapsome');

const cliParse = require('../lib/cli-parse');
const cwd = process.cwd();
const argv = process.argv.slice(2);
const first = argv[0];

const Directory = storage();
const Info = storage();

const tryOrExit = squad(exitIfError, tryCatch);
const exitIfNotEntry = squad(exitIfError, notEntryError);

let arg;
let ErrorCode = 1;

if (!first|| /^(-v|--version|-h|--help)$/.test(first))
    arg = cliParse(argv, {});
else
    arg = cliParse(argv,  traverseForInfo(cwd).scripts || {});

if (arg.name !== 'run') {
    console.log(arg.output);
} else {
    if (!arg.quiet)
        console.log(`> ${arg.cmd}`);

    if (arg.calm)
        ErrorCode = 0;

    execute(arg.cmd);
}

function execute(cmd) {
    const execSync = require('child_process').execSync;

    tryOrExit(() => {
        execSync(cmd, {
            stdio: 'inherit',
            env: getEnv(),
            cwd: Directory()
        });
    });
}

function getEnv() {
    const env = require('../lib/env');
    const path = require('path');

    const dir = Directory();
    const config = Info().config;
    const assign = Object.assign;

    const PATH = env.path(process.env.PATH, path.delimiter, dir, path.sep);

    const envVars = assign(process.env, env.config(config), {
        PATH: PATH
    });

    return envVars;
}

function exitIfError(error) {
    if (error) {
        console.error(error.message);
        process.exit(ErrorCode);
    }

    return error;
}

function getInfo(dir) {
    let info;
    const infoPath = path.join(dir, 'package.json');

    const error = tryCatch(() => {
        info = readjson.sync(infoPath);

        Info(info);
        Directory(dir);
    });

    exitIfNotEntry(infoPath, error);

    return info;
}

function traverseForInfo(cwd) {
    const parentDirs = require('parent-dirs')(cwd);
    const result = mapsome((dir) => getInfo(dir), parentDirs);

    exitIfEntryError(result);

    return result;
}

function notEntryError(path, error) {
    if (error && error.code !== 'ENOENT') {
        const message = error.message;
        error.message = `${path}: ${message}`;

        return error;
    }
}

function exitIfEntryError(data) {
    if (!data) {
        const infoPath = path.join(cwd, 'package.json');
        const error = Error(`Cannot find module \'${infoPath}\'`);
        exitIfError(error);
    }
}

function storage() {
    let value;
    return (data) => {
        if (data)
            value = data;
        else
            return value;
    };
}

<commit_msg>chore(redrun) rm " "<commit_after>#!/usr/bin/env node

'use strict';

const path = require('path');
const tryCatch = require('try-catch');
const squad = require('squad');
const readjson = require('readjson');

const mapsome = require('mapsome');

const cliParse = require('../lib/cli-parse');
const cwd = process.cwd();
const argv = process.argv.slice(2);
const first = argv[0];

const Directory = storage();
const Info = storage();

const tryOrExit = squad(exitIfError, tryCatch);
const exitIfNotEntry = squad(exitIfError, notEntryError);

let arg;
let ErrorCode = 1;

if (!first|| /^(-v|--version|-h|--help)$/.test(first))
    arg = cliParse(argv, {});
else
    arg = cliParse(argv,  traverseForInfo(cwd).scripts || {});

if (arg.name !== 'run') {
    console.log(arg.output);
} else {
    if (!arg.quiet)
        console.log(`> ${arg.cmd}`);

    if (arg.calm)
        ErrorCode = 0;

    execute(arg.cmd);
}

function execute(cmd) {
    const execSync = require('child_process').execSync;

    tryOrExit(() => {
        execSync(cmd, {
            stdio: 'inherit',
            env: getEnv(),
            cwd: Directory()
        });
    });
}

function getEnv() {
    const env = require('../lib/env');
    const path = require('path');

    const dir = Directory();
    const config = Info().config;
    const assign = Object.assign;

    const PATH = env.path(process.env.PATH, path.delimiter, dir, path.sep);

    const envVars = assign(process.env, env.config(config), {
        PATH: PATH
    });

    return envVars;
}

function exitIfError(error) {
    if (error) {
        console.error(error.message);
        process.exit(ErrorCode);
    }

    return error;
}

function getInfo(dir) {
    let info;
    const infoPath = path.join(dir, 'package.json');

    const error = tryCatch(() => {
        info = readjson.sync(infoPath);

        Info(info);
        Directory(dir);
    });

    exitIfNotEntry(infoPath, error);

    return info;
}

function traverseForInfo(cwd) {
    const parentDirs = require('parent-dirs')(cwd);
    const result = mapsome((dir) => getInfo(dir), parentDirs);

    exitIfEntryError(result);

    return result;
}

function notEntryError(path, error) {
    if (error && error.code !== 'ENOENT') {
        const message = error.message;
        error.message = `${path}: ${message}`;

        return error;
    }
}

function exitIfEntryError(data) {
    if (!data) {
        const infoPath = path.join(cwd, 'package.json');
        const error = Error(`Cannot find module \'${infoPath}\'`);
        exitIfError(error);
    }
}

function storage() {
    let value;
    return (data) => {
        if (data)
            value = data;
        else
            return value;
    };
}

<|endoftext|>


<commit_before>var page = require('webpage').create(),
  system = require('system'),
  total = 0,
  requests = [],
  num_requests = 1,
  target = '1.1.1.1',
  t, address;

if (system.args.length < 3) {
  console.log('Usage: detect_url.js <URL> <TARGET> <NUM REQUESTS>');
  phantom.exit();
}

page.onResourceRequested = function(request) {
  total++;
  if (request.url.indexOf(target) > -1) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
    requests.append(request);
    if (requests.length > num_requests) {
      console.log('\nTarget requests: ' + requests.length + ', Total: ' + total);
      phantom.exit();
    }
  }
};

//page.onResourceReceived = function(response) {
//  console.log('Receive ' + JSON.stringify(response, undefined, 4));
//};

t = Date.now();
url = system.args[1];
target = system.args[2];
if (system.args.length > 3) {
  num_requests = system.args[3];
}

page.open(url, function(status) {
  if (status !== 'success') {
    console.log('FAIL to load the url');
  } else {
    t = (Date.now() - t)/1000.0;
    console.log('Loading ' + system.args[1] + ', time ' + t + ' s');
  }
  phantom.exit();
});

<commit_msg>added timeout<commit_after>var page = require('webpage').create(),
  system = require('system'),
  total = 0,
  requests = [],
  num_requests = 1,
  target = "",
  timeout_t = 10000,
  timeout_id,
  t = 0,
  url = "";

if (system.args.length < 3) {
  console.log('Usage: phantomjs detect_url.js <URL> <TARGET> <NUM REQUESTS> <TIMEOUT SEC>');
  phantom.exit();
}

page.onResourceRequested = function(request) {
  total++;
  if (request.url.indexOf(target) > -1) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
    requests.append(request);
    if (requests.length > num_requests) {
      console.log('\nTarget requests: ' + requests.length + ', Total: ' + total);
      phantom.exit();
    }
  }
};

//page.onResourceReceived = function(response) {
//  console.log('Receive ' + JSON.stringify(response, undefined, 4));
//};

t = Date.now();
url = system.args[1];
target = system.args[2];
if (system.args.length > 3) {
  num_requests = system.args[3];
}
if (system.args.length > 4) {
  timeout_t = parseInt(system.args[4]) * 1000;
}

page.open(url, function(status) {
  if (status !== 'success') {
    console.log('FAIL to load the url');
  } else {
    t = (Date.now() - t)/1000.0;
    console.log('Loading ' + system.args[1] + ', time ' + t + ' s');
  }

  timeout_id = setTimeout(function() {
    console.log('\nTarget requests: ' + requests.length + ', Total: ' + total);
    phantom.exit();
  }, timeout_t);
});

<|endoftext|>


<commit_before>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Clock control panel that shows "Normal Speed" and "Fast Forward" as radio buttons with a play/pause and step button.
 *
 * @author Sam Reid
 * @author John Blanco
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  // modules
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var PlayPauseButton = require( 'SCENERY_PHET/buttons/PlayPauseButton' );
  var RadioButtonGroup = require( 'SUN/buttons/RadioButtonGroup' );
  var SimSpeed = require( 'ENERGY_FORMS_AND_CHANGES/intro/model/SimSpeed' );
  var StepForwardButton = require( 'SCENERY_PHET/buttons/StepForwardButton' );
  var Text = require( 'SCENERY/nodes/Text' );

  // strings
  var fastForwardString = require( 'string!ENERGY_FORMS_AND_CHANGES/fastForward' );
  var normalString = require( 'string!ENERGY_FORMS_AND_CHANGES/normal' );

  // static data
  var RADIO_BUTTON_FONT = new PhetFont( 16 );

  /**
   * @param {EFACIntroModel} model
   * @constructor
   */
  function NormalAndFastForwardTimeControlPanel( model ) {

    // add play/pause button
    var playPauseButton = new PlayPauseButton( model.isPlayingProperty, { radius: 20 } );

    // add the step button, used to manually step the simulation
    var stepButton = new StepForwardButton( {
      isPlayingProperty: model.isPlayingProperty,
      listener: function() { model.manualStep(); },
      radius: 15,
      centerX: playPauseButton.centerX
    } );

    // group the play and pause buttons into their own panel for correct layout in the HBox
    var playPauseButtonGroup = new HBox( {
      children: [ playPauseButton, stepButton ],
      spacing: 10,
    } );

    var radioButtonContent = [
      { value: SimSpeed.NORMAL, node: new Text( normalString, { font: RADIO_BUTTON_FONT } ) },
      { value: SimSpeed.FAST_FORWARD, node: new Text( fastForwardString, { font: RADIO_BUTTON_FONT } ) }
    ];
    var radioButtonGroup = new RadioButtonGroup( model.normalSimSpeedProperty, radioButtonContent, {
      orientation: 'horizontal',
      selectedLineWidth: 4
    } );

    HBox.call( this, {
      children: [ radioButtonGroup, playPauseButtonGroup ],
      spacing: 35
    } );
  }

  energyFormsAndChanges.register( 'NormalAndFastForwardTimeControlPanel', NormalAndFastForwardTimeControlPanel );

  return inherit( HBox, NormalAndFastForwardTimeControlPanel );
} );

<commit_msg>Fix lint issues<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Clock control panel that shows "Normal Speed" and "Fast Forward" as radio buttons with a play/pause and step button.
 *
 * @author Sam Reid
 * @author John Blanco
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  // modules
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var PlayPauseButton = require( 'SCENERY_PHET/buttons/PlayPauseButton' );
  var RadioButtonGroup = require( 'SUN/buttons/RadioButtonGroup' );
  var SimSpeed = require( 'ENERGY_FORMS_AND_CHANGES/intro/model/SimSpeed' );
  var StepForwardButton = require( 'SCENERY_PHET/buttons/StepForwardButton' );
  var Text = require( 'SCENERY/nodes/Text' );

  // strings
  var fastForwardString = require( 'string!ENERGY_FORMS_AND_CHANGES/fastForward' );
  var normalString = require( 'string!ENERGY_FORMS_AND_CHANGES/normal' );

  // static data
  var RADIO_BUTTON_FONT = new PhetFont( 16 );

  /**
   * @param {EFACIntroModel} model
   * @constructor
   */
  function NormalAndFastForwardTimeControlPanel( model ) {

    // add play/pause button
    var playPauseButton = new PlayPauseButton( model.isPlayingProperty, { radius: 20 } );

    // add the step button, used to manually step the simulation
    var stepButton = new StepForwardButton( {
      isPlayingProperty: model.isPlayingProperty,
      listener: function() { model.manualStep(); },
      radius: 15,
      centerX: playPauseButton.centerX
    } );

    // group the play and pause buttons into their own panel for correct layout in the HBox
    var playPauseButtonGroup = new HBox( {
      children: [ playPauseButton, stepButton ],
      spacing: 10
    } );

    var radioButtonContent = [
      { value: SimSpeed.NORMAL, node: new Text( normalString, { font: RADIO_BUTTON_FONT } ) },
      { value: SimSpeed.FAST_FORWARD, node: new Text( fastForwardString, { font: RADIO_BUTTON_FONT } ) }
    ];
    var radioButtonGroup = new RadioButtonGroup( model.normalSimSpeedProperty, radioButtonContent, {
      orientation: 'horizontal',
      selectedLineWidth: 4
    } );

    HBox.call( this, {
      children: [ radioButtonGroup, playPauseButtonGroup ],
      spacing: 35
    } );
  }

  energyFormsAndChanges.register( 'NormalAndFastForwardTimeControlPanel', NormalAndFastForwardTimeControlPanel );

  return inherit( HBox, NormalAndFastForwardTimeControlPanel );
} );

<|endoftext|>


<commit_before>define(function() {

  'use strict';

  function NO_OP(){}

  function split(segment, entries) {

    var macPartitioned = segment.getBytes(512, 4).then(function(sig) {
      if (String.fromCharCode(sig[0], sig[1], sig[2], sig[3]) !== 'PM\0\0') {
        return;
      }
      return segment.getSegment('volume/mac-partitioned').split();
    }, NO_OP);

    var iso9660 = segment.getBytes(2048 * 16 + 1, 5).then(function(sig) {
      if (String.fromCharCode(sig[0], sig[1], sig[2], sig[3], sig[4]) !== 'CD001') {
        return;
      }
      return segment.getSegment('volume/iso-9660').split();
    }, NO_OP);

    return Promise.all([
      macPartitioned,
      iso9660,
    ]);

  }

  return {
    split: split,
  };

});
<commit_msg>Try to mount an arbitrary volume<commit_after>define(function() {

  'use strict';

  function NO_OP(){}

  function split(segment, entries) {

    var macPartitioned = segment.getBytes(512, 4).then(function(sig) {
      if (String.fromCharCode(sig[0], sig[1], sig[2], sig[3]) !== 'PM\0\0') {
        return;
      }
      return segment.getSegment('volume/mac-partitioned').split();
    }, NO_OP);

    var iso9660 = segment.getBytes(2048 * 16 + 1, 5).then(function(sig) {
      if (String.fromCharCode(sig[0], sig[1], sig[2], sig[3], sig[4]) !== 'CD001') {
        return;
      }
      return segment.getSegment('volume/iso-9660').split();
    }, NO_OP);

    return Promise.all([
      macPartitioned,
      iso9660,
    ]);

  }

  function mount(segment, volume) {
    return segment.split().then(function(parts) {
      if (parts.length === 0) return Promise.reject('No disk volume found');
      return parts[0].mount(volume);
    });
  }

  return {
    split: split,
    mount: mount,
  };

});
<|endoftext|>


<commit_before>/**
 * $.w.window.workspace represente un espace de travail.
 */
$.w.window.workspace = function WWindowWorkspace() {
	Webos.Observable.call(this);

	this._id = $.w.window.workspace.list.push(this) - 1;
	var id = this._id;

	var that = this;

	this.switchTo = function(workspaceId) {
		var windowsList = this.windows();
		var that = this;
		/*var desktopWidth = $('#desktop').width() * ($.w.window.workspace.current - workspaceId);*/

		if (this.id() == workspaceId) {
			var doWindowEffectFn = function(thisWindow) {
				/*thisWindow.addClass('animating').animate({
					left: '+='+desktopWidth+'px'
				}, 'normal', function() {
					$(this).removeClass('animating');
				});*/
				thisWindow.show();
			};

			this._button.addClass('selected','normal');
		} else {
			var doWindowEffectFn = function(thisWindow) {
				/*thisWindow.addClass('animating').animate({
					left: '+='+desktopWidth+'px'
				}, 'normal', function() {
					$(this).removeClass('animating');
					var leftX = $(this).offset().left;
					var rightX = leftX + $(this).width();
					if (rightX > 0 && leftX < $('#desktop').width()) {
						thisWindow.window('workspace', $.w.window.workspace.get(workspaceId));
						thisWindow.window('button').show();
					}
				});*/
				thisWindow.window('toBackground').hide();
			};

			this._button.removeClass('selected','normal');
		}

		for(var i=0; i < windowsList.length; i++) {
			if (!windowsList[i].window('is', 'hidden')) {
				doWindowEffectFn(windowsList[i]);
			}
		}
	};

	this.remove = function() { //Supprimer l'espace de travail
		var windowsList = this.windows();
		for(var i = 0; i < windowsList.length; i++) {
			windowsList[i].window('close');
		}

		this._button.remove();
	};
	this.id = function() { //Recuperer l'ID de l'espace de travail
		return this._id;
	};
	this.getId = function() {
		return this.id();
	};
	this.windows = function() { //Recuperer toutes les fenetres de l'espace de travail
		var list = [];
		var id = this._id;
		$.webos.window.getWindows().each(function() {
			if ($(this).window('workspace').getId() == id) {
				list.push($(this));
			}
		});
		return list;
	};
	this.getWindows = function() {
		return this.windows();
	};

	this._button = $('', { 'class': 'workspace-button', title: 'Espace de travail '+(id+1) })
		.click(function() {
			$.w.window.workspace.switchTo(that.getId());
		})
		.appendTo($.w.window.workspace.switcher);

	if (!$.w.window.workspace.getCurrent()) {
		$.w.window.workspace.switchTo(this.id());
	}
};
Webos.inherit($.w.window.workspace, Webos.Observable);
Webos.Observable.build($.w.window.workspace);

$.w.window.workspace.switcher = $('

');
$.w.window.workspace.list = []; //Liste de tous les espaces de travail
$.w.window.workspace.current = undefined; //Espace de travail courrant
$.w.window.workspace.get = function(id) {
	for (var i = 0; i < $.w.window.workspace.list.length; i++) {
		if ($.w.window.workspace.list[i].id() == id) {
			return $.w.window.workspace.list[i];
		}
	}
};
$.w.window.workspace.getList = function() {
	return $.w.window.workspace.list;
};
$.w.window.workspace.getCurrent = function() { //Recuperer l'espace de travail actuel
	return $.w.window.workspace.get($.w.window.workspace.current);
};
$.w.window.workspace.switchTo = function(id) { //Se deplacer vers un autre espace de travail
	if ($.w.window.workspace.current === id) {
		return;
	}

	var workspace = $.w.window.workspace.get(id);
	if (typeof workspace == 'undefined') {
		return;
	}

	var old = $.w.window.workspace.current;
	if (typeof $.w.window.workspace.current != 'undefined') {
		$.w.window.workspace.getCurrent().switchTo(id);
	}
	workspace.switchTo(id);
	$.w.window.workspace.current = id;

	$.w.window.workspace.notify('switch', { old: old, current: id });
};
$.w.window.workspace.remove = function(id) {
	if ($.w.window.workspace.current === id) {
		return;
	}

	var workspace = $.w.window.workspace.get(id);
	if (!workspace) {
		return;
	}

	workspace.remove();

	var newList = [], actualList = $.w.window.workspace.getList();
	for (var i = 0; i < actualList.length; i++) {
		if (actualList[i].id() != id) {
			newList.push(actualList[i]);
		}
	}
	$.w.window.workspace.list = newList;

	$.w.window.workspace.notify('remove', { removed: id });
};
<commit_msg>Resolution d'un bug du Shell lors du changement d'un espace de travail lorsqu'une fenetre est reduite.<commit_after>/**
 * $.w.window.workspace represente un espace de travail.
 */
$.w.window.workspace = function WWindowWorkspace() {
	Webos.Observable.call(this);

	this._id = $.w.window.workspace.list.push(this) - 1;
	var id = this._id;

	var that = this;

	this.switchTo = function(workspaceId) {
		var windowsList = this.windows();
		var that = this;
		/*var desktopWidth = $('#desktop').width() * ($.w.window.workspace.current - workspaceId);*/

		if (this.id() == workspaceId) {
			var doWindowEffectFn = function(thisWindow) {
				/*thisWindow.addClass('animating').animate({
					left: '+='+desktopWidth+'px'
				}, 'normal', function() {
					$(this).removeClass('animating');
				});*/
				thisWindow.show();
			};

			this._button.addClass('selected','normal');
		} else {
			var doWindowEffectFn = function(thisWindow) {
				/*thisWindow.addClass('animating').animate({
					left: '+='+desktopWidth+'px'
				}, 'normal', function() {
					$(this).removeClass('animating');
					var leftX = $(this).offset().left;
					var rightX = leftX + $(this).width();
					if (rightX > 0 && leftX < $('#desktop').width()) {
						thisWindow.window('workspace', $.w.window.workspace.get(workspaceId));
						thisWindow.window('button').show();
					}
				});*/
				thisWindow.window('toBackground').hide();
			};

			this._button.removeClass('selected','normal');
		}

		for(var i=0; i < windowsList.length; i++) {
			doWindowEffectFn(windowsList[i]);
		}
	};

	this.remove = function() { //Supprimer l'espace de travail
		var windowsList = this.windows();
		for(var i = 0; i < windowsList.length; i++) {
			windowsList[i].window('close');
		}

		this._button.remove();
	};
	this.id = function() { //Recuperer l'ID de l'espace de travail
		return this._id;
	};
	this.getId = function() {
		return this.id();
	};
	this.windows = function() { //Recuperer toutes les fenetres de l'espace de travail
		var list = [];
		var id = this._id;
		$.webos.window.getWindows().each(function() {
			if ($(this).window('workspace').getId() == id) {
				list.push($(this));
			}
		});
		return list;
	};
	this.getWindows = function() {
		return this.windows();
	};

	this._button = $('', { 'class': 'workspace-button', title: 'Espace de travail '+(id+1) })
		.click(function() {
			$.w.window.workspace.switchTo(that.getId());
		})
		.appendTo($.w.window.workspace.switcher);

	if (!$.w.window.workspace.getCurrent()) {
		$.w.window.workspace.switchTo(this.id());
	}
};
Webos.inherit($.w.window.workspace, Webos.Observable);
Webos.Observable.build($.w.window.workspace);

$.w.window.workspace.switcher = $('

');
$.w.window.workspace.list = []; //Liste de tous les espaces de travail
$.w.window.workspace.current = undefined; //Espace de travail courrant
$.w.window.workspace.get = function(id) {
	for (var i = 0; i < $.w.window.workspace.list.length; i++) {
		if ($.w.window.workspace.list[i].id() == id) {
			return $.w.window.workspace.list[i];
		}
	}
};
$.w.window.workspace.getList = function() {
	return $.w.window.workspace.list;
};
$.w.window.workspace.getCurrent = function() { //Recuperer l'espace de travail actuel
	return $.w.window.workspace.get($.w.window.workspace.current);
};
$.w.window.workspace.switchTo = function(id) { //Se deplacer vers un autre espace de travail
	if ($.w.window.workspace.current === id) {
		return;
	}

	var workspace = $.w.window.workspace.get(id);
	if (typeof workspace == 'undefined') {
		return;
	}

	var old = $.w.window.workspace.current;
	if (typeof $.w.window.workspace.current != 'undefined') {
		$.w.window.workspace.getCurrent().switchTo(id);
	}
	workspace.switchTo(id);
	$.w.window.workspace.current = id;

	$.w.window.workspace.notify('switch', { old: old, current: id });
};
$.w.window.workspace.remove = function(id) {
	if ($.w.window.workspace.current === id) {
		return;
	}

	var workspace = $.w.window.workspace.get(id);
	if (!workspace) {
		return;
	}

	workspace.remove();

	var newList = [], actualList = $.w.window.workspace.getList();
	for (var i = 0; i < actualList.length; i++) {
		if (actualList[i].id() != id) {
			newList.push(actualList[i]);
		}
	}
	$.w.window.workspace.list = newList;

	$.w.window.workspace.notify('remove', { removed: id });
};
<|endoftext|>


<commit_before>import jQuery from 'jquery';
import Mixin from 'ember-metal/mixin';
import computed from 'ember-computed';
import { bind, debounce } from 'ember-runloop';
import { isNone } from 'ember-utils';
import Ember from 'ember';
const { RSVP } = Ember;
const { trim } = jQuery;

export default Mixin.create({
  didInitAttrs() {
    this._super(...arguments);
    this.set('isSearchable', typeof this.getAttr('on-search') === 'function');
  },

  searchDelayTime: computed(function() {
    let ms = this.getAttr('search-delay-time');
    return isNone(ms) ? 100 : ms;
  }),

  searchSlowTime: computed(function() {
    let ms = this.getAttr('search-slow-time');
    return isNone(ms) ? 500 : ms;
  }),

  searchMinChars: computed(function() {
    let min = this.getAttr('search-min-chars');
    return isNone(min) ? 1 : min;
  }),

  queryOK(query) {
    return query.length >= this.get('searchMinChars');
  },

  _inputText(text) {
    if (this.get('isSearchable')) {
      this._runDebouncedSearch(text);
    }
  },

  _runDebouncedSearch(query) {
    let delay = this.get('searchDelayTime');
    let immediate = !delay;
    debounce(this, '_runSearch', query, delay, immediate);
  },

  _runSearch(query) {
    query = trim(query);
    if (this.queryOK(query) && !this.get('isDestroyed')) {
      this._search(query);
    }
  },

  _search(query = '') {
    this.set('isSearching', true);
    this.incrementProperty('searchID');
    debounce(this, '_checkSlowSearch', this.get('searchSlowTime'));

    let search = this.getAttr('on-search');
    return RSVP.resolve(search(query, this.get('api')))
      .then(bind(this, '_searchCompleted', this.get('searchID'), query))
      .catch(bind(this, '_searchFailed', query));
  },

  _searchCompleted(id, query, result) {
    if (this.get('isDestroyed')) { return; }

    let superseded = id < this.get('searchID');
    if (superseded) { return; }

    this.sendAction('on-searched', result, query, this.get('api'));
    this._searchFinished();
  },

  _searchFailed(query, error) {
    if (this.get('isDestroyed')) { return; }
    this.sendAction('on-search-error', error, query, this.get('api'));
    this._searchFinished();
  },

  _searchFinished() {
    this.set('isSearching', false);
    this.set('isSlowSearch', false);
  },

  _checkSlowSearch() {
    if (this.get('isDestroyed')) { return; }
    this.set('isSlowSearch', this.get('isSearching'));
  },

  actions: {
    search(query) {
      return this._search(query);
    },

    stopSearching() {
      this.incrementProperty('searchID');
      this._searchFinished();
    },

    setInputValue(value) {
      this.get('input').$().val(value);
    },

    focusInput() {
      this.get('input').$().focus();
    },

    inputText(text) {
      this._super(...arguments);
      this._inputText(text);
    }
  }
});
<commit_msg>phase out didInitAttrs<commit_after>import jQuery from 'jquery';
import Mixin from 'ember-metal/mixin';
import computed from 'ember-computed';
import { bind, debounce } from 'ember-runloop';
import { isNone } from 'ember-utils';
import Ember from 'ember';
const { RSVP } = Ember;
const { trim } = jQuery;

export default Mixin.create({
  isSearchable: computed(function() {
    return typeof this.getAttr('on-search') === 'function';
  }),

  searchDelayTime: computed(function() {
    let ms = this.getAttr('search-delay-time');
    return isNone(ms) ? 100 : ms;
  }),

  searchSlowTime: computed(function() {
    let ms = this.getAttr('search-slow-time');
    return isNone(ms) ? 500 : ms;
  }),

  searchMinChars: computed(function() {
    let min = this.getAttr('search-min-chars');
    return isNone(min) ? 1 : min;
  }),

  queryOK(query) {
    return query.length >= this.get('searchMinChars');
  },

  _inputText(text) {
    if (this.get('isSearchable')) {
      this._runDebouncedSearch(text);
    }
  },

  _runDebouncedSearch(query) {
    let delay = this.get('searchDelayTime');
    let immediate = !delay;
    debounce(this, '_runSearch', query, delay, immediate);
  },

  _runSearch(query) {
    query = trim(query);
    if (this.queryOK(query) && !this.get('isDestroyed')) {
      this._search(query);
    }
  },

  _search(query = '') {
    this.set('isSearching', true);
    this.incrementProperty('searchID');
    debounce(this, '_checkSlowSearch', this.get('searchSlowTime'));

    let search = this.getAttr('on-search');
    return RSVP.resolve(search(query, this.get('api')))
      .then(bind(this, '_searchCompleted', this.get('searchID'), query))
      .catch(bind(this, '_searchFailed', query));
  },

  _searchCompleted(id, query, result) {
    if (this.get('isDestroyed')) { return; }

    let superseded = id < this.get('searchID');
    if (superseded) { return; }

    this.sendAction('on-searched', result, query, this.get('api'));
    this._searchFinished();
  },

  _searchFailed(query, error) {
    if (this.get('isDestroyed')) { return; }
    this.sendAction('on-search-error', error, query, this.get('api'));
    this._searchFinished();
  },

  _searchFinished() {
    this.set('isSearching', false);
    this.set('isSlowSearch', false);
  },

  _checkSlowSearch() {
    if (this.get('isDestroyed')) { return; }
    this.set('isSlowSearch', this.get('isSearching'));
  },

  actions: {
    search(query) {
      return this._search(query);
    },

    stopSearching() {
      this.incrementProperty('searchID');
      this._searchFinished();
    },

    setInputValue(value) {
      this.get('input').$().val(value);
    },

    focusInput() {
      this.get('input').$().focus();
    },

    inputText(text) {
      this._super(...arguments);
      this._inputText(text);
    }
  }
});
<|endoftext|>


<commit_before>module("juice.scriptloading");

test("Get juice path", function(){

});

test("test multi script loading", function(){

	stop(600);
	expect(2);
	juice.loadExtensions('AspireList', 'copac');
	setTimeout(function(){

						equal(typeof AspireListJuice, 'function', 'There should be an aspire list extension');
						equal(typeof copacJuice, 'function', 'There should be a copac extension');
						start();
						}, 500);

});

test("test Google API loader", function(){
	stop();
	juice.loadGoogle_jsapi();
	setTimeout(function(){
							equal(typeof window.google, 'object', 'Google API should load');
							start();
							}, 500);

});

test("test script loading", function(){
	stop();
	juice.loadJs('../extensions/delicious.js','', function(){

													equal(typeof deliciousJuice, 'function', 'There should be a delicious extension');

													start();
													});
});

test("test loading of google apis", function(){
	stop();
	juice.loadGoogleApi("feeds", "1");
	setTimeout(function(){
							equal(typeof google.feeds, 'object', 'There should be a feeds api loaded');
							start();
							}, 500);
});

<commit_msg>Path detection tests.<commit_after>module("juice.scriptloading");

test("Get juice path", function(){
    equal(juice.getPath('../juice.min.js'),'../');
    equal(juice.getPath('../juice.js'),'../');
    equal(juice.getPath('http://localhost/js/somefolder/juice.js'), 'http://localhost/js/somefolder/');

});

test("test multi script loading", function(){

	stop(600);
	expect(2);
	juice.loadExtensions('AspireList', 'copac');
	setTimeout(function(){

						equal(typeof AspireListJuice, 'function', 'There should be an aspire list extension');
						equal(typeof copacJuice, 'function', 'There should be a copac extension');
						start();
						}, 500);

});

test("test Google API loader", function(){
	stop();
	juice.loadGoogle_jsapi();
	setTimeout(function(){
							equal(typeof window.google, 'object', 'Google API should load');
							start();
							}, 500);

});

test("test script loading", function(){
	stop();
	juice.loadJs('../extensions/delicious.js','', function(){

													equal(typeof deliciousJuice, 'function', 'There should be a delicious extension');

													start();
													});
});

test("test loading of google apis", function(){
	stop();
	juice.loadGoogleApi("feeds", "1");
	setTimeout(function(){
							equal(typeof google.feeds, 'object', 'There should be a feeds api loaded');
							start();
							}, 500);
});

<|endoftext|>