<commit_before>import React from 'react';
import _ from 'lodash';
import ReplEntries from './ReplEntries';
import ReplPrompt from './ReplPrompt';
import ReplStatusBar from './ReplStatusBar';
import ReplStore from '../stores/ReplStore';
import ReplDOMEvents from '../common/ReplDOMEvents';
import ReplDOM from '../common/ReplDOM';
import ReplActiveInputActions from '../actions/ReplActiveInputActions';
import ReplPreferencesActions from '../actions/ReplPreferencesActions';
import ReplConsoleActions from '../actions/ReplConsoleActions';
import ReplSuggestionActions from '../actions/ReplSuggestionActions';
import ReplStatusBarActions from '../actions/ReplStatusBarActions';
import Reflux from 'reflux';
import {ipcRenderer} from 'electron';
import {writeFile, readFile} from 'fs';
import {EOL} from 'os';
import remote from 'remote';
import ReplStreamHook from '../common/ReplStreamHook';
import ReplConsoleHook from '../common/ReplConsoleHook';
import ReplConsole from './ReplConsole';
import ReplOutput from '../common/ReplOutput';
import ContextMenu from '../menus/context-menu.json';
import ReplConstants from '../constants/ReplConstants';
import ReplContext from '../common/ReplContext';
import ReplCommon from '../common/ReplCommon';
import ReplLanguages from '../languages/ReplLanguages';
import {format} from 'util';

export default class Repl extends React.Component {
  constructor(props) {
    super(props);
    _.each([
      'onStateChange', 'onPaste', 'onContextMenu',
      'onKeydown', 'onBreakPrompt', 'onClearCommands',
      'onCollapseAll', 'onExpandAll', 'onDrag', 'onToggleConsole', 'onFormatPromptCode',
      'onStdout', 'onStderr', 'onStdMessage', 'onConsole', 'onConsoleChange', 'getPromptKey',
      'onImport', 'onExport', 'onAddPath', 'loadPreferences', 'onSaveCommands', 'onLoadScript',
      'checkNewRelease', 'onNewRelease', 'resizeWindow', 'onSetREPLMode', 'loadStartupScript', 'onInit'
    ], (field) => {
      this[field] = this[field].bind(this);
    });

    this.loadPreferences();
    ReplCommon.addUserDataToPath(ReplContext.getContext());

    this.state = _.cloneDeep(ReplStore.getStore());
  }

  componentDidMount() {
    // set REPL language
    ReplLanguages.setREPL(global.Mancy.preferences.lang);
    this.setupContextMenu();
    this.activePromptKey = Date.now();

    //register events
    this.unsubscribe = ReplStore.listen(this.onStateChange);

    window.addEventListener('paste', this.onPaste, false);
    window.addEventListener('contextmenu', this.onContextMenu, false);
    window.addEventListener('keydown', this.onKeydown, false);

    // hooks
    ReplStreamHook.on('stdout', this.onStdout);
    ReplStreamHook.on('stderr', this.onStderr);

    ReplConsoleHook.on('console', this.onConsole);

    ipcRenderer.on('application:import-file', this.onImport);
    ipcRenderer.on('application:export-file', this.onExport);
    ipcRenderer.on('application:add-path', this.onAddPath);
    ipcRenderer.on('application:save-as', this.onSaveCommands);
    ipcRenderer.on('application:load-file', this.onLoadScript);

    ipcRenderer.on('application:prompt-clear-all', this.onClearCommands);
    ipcRenderer.on('application:prompt-expand-all', this.onExpandAll);
    ipcRenderer.on('application:prompt-collapse-all', this.onCollapseAll);
    ipcRenderer.on('application:prompt-break', this.onBreakPrompt);
    ipcRenderer.on('application:prompt-format', this.onFormatPromptCode);

    ipcRenderer.on('application:prompt-mode', (sender, value) => this.onSetREPLMode(value));
    ipcRenderer.on('application:prompt-language', (sender, value) =>  {
      global.Mancy.session.lang = value;
      ReplLanguages.setREPL(value);
      ReplStatusBarActions.updateLanguage(value);
    });

    ipcRenderer.on('application:preferences', ReplPreferencesActions.openPreferences);

    ipcRenderer.on('application:preference-theme-dark', () => ReplPreferencesActions.setTheme('Dark Theme'));
    ipcRenderer.on('application:preference-theme-light', () => ReplPreferencesActions.setTheme('Light Theme'));

    ipcRenderer.on('application:view-theme-dark', () => document.body.className = 'dark-theme');
    ipcRenderer.on('application:view-theme-light', () => document.body.className = 'light-theme');

    ipcRenderer.on('application:new-release', this.onNewRelease);
    this.onInit();
  }

  onInit() {
    this.checkNewRelease();
    this.onSetREPLMode(global.Mancy.preferences.mode);
    ReplPreferencesActions.setTheme(global.Mancy.preferences.theme);

    this.resizeWindow();
    this.loadStartupScript();
    ipcRenderer.send('application:prompt-on-close', global.Mancy.preferences.promptOnClose);
  }

  onLoadScript(sender, script) {
    if(script) {
      let ext = script.replace(/(?:.*)\.(\w+)$/, '$1');
      let lang = ReplLanguages.getLangName(ext);
      if(lang) {
        ReplLanguages.setREPL(lang);
        ReplActiveInputActions.playCommands([`.load ${script}`]);
        if(lang !== global.Mancy.preferences.lang) {
          setTimeout(() => {
            ReplLanguages.setREPL(global.Mancy.preferences.lang);
            ReplStore.onReloadPrompt('');
          }, 200);
        }
      } else {
        let options = {
          buttons: ['Close'],
          title: 'Failed to load script',
          type: 'error',
          message: `Failed to load '${script}'. '${ext}' extension is not supported.`
        };
        ipcRenderer.send('application:message-box', options);
      }
    }
  }

  loadStartupScript() {
    this.onLoadScript(null, global.Mancy.preferences.loadScript);
  }

  resizeWindow() {
    let setSize = (w, h) => localStorage.setItem('window', JSON.stringify({ width: w, height: h }));
    let win = remote.getCurrentWindow();
    let lastWindow = JSON.parse(localStorage.getItem('window'));
    let [width, height] = win.getSize();
    if(!lastWindow) { setSize(width, height) }
    else {
      try {
        win.setSize(lastWindow.width, lastWindow.height);
      } catch(e) {}
    }
    win.on('resize', () => {
      let [width, height] = win.getSize();
      setSize(width, height);
    });
  }

  setupContextMenu() {
    let Menu = remote.require('menu');
    let contextMenu = _.cloneDeep(ContextMenu);
    let actionTemplates = [
      {
        label: 'Clear All',
        accelerator: 'Ctrl+L',
        click: this.onClearCommands
      },
      {
        label: 'Collapse All',
        accelerator: 'CmdOrCtrl+K',
        click: this.onCollapseAll
      },
      {
        label: 'Expand All',
        accelerator: 'CmdOrCtrl+E',
        click: this.onExpandAll
      },
      {
        label: 'Break Prompt',
        accelerator: 'Ctrl+D',
        click: this.onBreakPrompt
      },
      {
        label: 'Format',
        accelerator: 'Shift+Ctrl+F',
        click: this.onFormatPromptCode
      }
    ];

    _.each(actionTemplates, (template) => contextMenu.push(template));

    this.menu = Menu.buildFromTemplate(contextMenu);
  }

  componentWillUnmount() {
    this.unsubscribe();
    window.removeEventListener('paste', this.onPaste, false);
    window.removeEventListener('contextmenu', this.onContextMenu, false);
    window.removeEventListener('keydown', this.onKeydown, false);

    ReplStreamHook.removeListener('stdout', this.onStdout);
    ReplStreamHook.removeListener('stderr', this.onStderr);
    ReplStreamHook.disable();

    ReplConsoleHook.removeListener('console', this.onConsole);
    ReplConsoleHook.disable();
  }

  checkNewRelease() {
    setTimeout(() => ipcRenderer.send('application:check-new-release'), 2000);
  }

  loadPreferences() {
    let preferences = JSON.parse(localStorage.getItem('preferences'));
    ipcRenderer.send('application:sync-preference', preferences);
  }

  onNewRelease(release) {
    ReplStatusBarActions.newRelease(release);
  }

  onSaveCommands(sender, filename) {
    let {history} = ReplStore.getStore();
    let data = _.chain(history)
      .map((h) => h.plainCode)
      .filter((c) => !/^\s*\./.test(c))
      .value()
      .join(EOL);

    writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => {
      let options = { buttons: ['Close'] };
      if(err) {
        options = _.extend(options, {
          title: 'Save Error',
          type: 'error',
          message: err.name || ' Error',
          detail: err.toString()
        });
      } else {
        options = _.extend(options, {
          title: 'Commands saved',
          type: 'info',
          message: `Commands saved to ${filename}`
        });
      }
      ipcRenderer.send('application:message-box', options);
    });
  }

  onImport(sender, filename) {
    readFile(filename, (err, data) => {
      if(!err) {
        try {
          let history = JSON.parse(data);
          if(!Array.isArray(history) || !_.every(history, (h) => typeof h === 'string')) {
            throw Error(`Invalid session file ${filename}`);
          }
          ReplActiveInputActions.playCommands(history);
          return;
        } catch(e) {
          err = e;
        }
      }

      ipcRenderer.send('application:message-box', {
        title: 'Load session error',
        buttons: ['Close'],
        type: 'error',
        message: err.toString()
      });
    });
  }

  onExport(sender, filename) {
    let {history} = ReplStore.getStore();
    let data = JSON.stringify(_.map(history, (h) => h.plainCode));
    writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => {
      let options = { buttons: ['Close'] };
      if(err) {
        options = _.extend(options, {
          title: 'Export Error',
          type: 'error',
          message: err.name || ' Error',
          detail: err.toString()
        });
      } else {
        options = _.extend(options, {
          title: 'Session saved',
          type: 'info',
          message: `Session saved to ${filename}`
        });
      }
      ipcRenderer.send('application:message-box', options);
    });
  }

  onAddPath(sender, paths) {
    ReplCommon.addToPath(paths, ReplContext.getContext());
  }

  onContextMenu(e) {
    e.preventDefault();
    this.menu.popup(remote.getCurrentWindow());
  }

  onSetREPLMode(mode) {
    ReplStore.onSetREPLMode(mode);
    ReplStatusBarActions.updateMode(mode);
    global.Mancy.session.mode = mode;
  }

  onPaste(e) {
    e.preventDefault();
    var text = e.clipboardData.getData("text/plain");
    document.execCommand("insertHTML", false, text);
    ReplSuggestionActions.removeSuggestion();
  }

  onKeydown(e) {
    if(ReplDOMEvents.isEnter(e)) {
      ReplDOM.scrollToEnd();
      return;
    }
    if(e.ctrlKey && ReplDOMEvents.isSpace(e)) {
      ReplActiveInputActions.performAutoComplete();
    }
  }

  onFormatPromptCode() {
    ReplActiveInputActions.formatCode();
  }

  onCollapseAll() {
    ReplStore.collapseAll();
  }

  onExpandAll() {
    ReplStore.expandAll();
  }

  onBreakPrompt() {
    ReplActiveInputActions.breakPrompt();
  }

  onClearCommands() {
    ReplStore.clearStore();
    ReplConsoleActions.clear();
  }

  onStateChange() {
    this.setState(ReplStore.getStore());
  }

  onDrag(e) {
    let replConsole = document.getElementsByClassName('repl-console')[0];
    let replContainerRight = document.getElementsByClassName('repl-container-right')[0];

    let {clientX} = e;
    let {width} = document.defaultView.getComputedStyle(replConsole);
    let initWidth = parseInt(width, 10);

    let startDrag = (e) => {
      let adj = e.clientX - clientX;
      replContainerRight.style.flex = '0 0  ' + (initWidth - adj) + 'px';
    }

    let stopDrag = (e) => {
      document.documentElement.removeEventListener('mousemove', startDrag, false);
      document.documentElement.removeEventListener('mouseup', stopDrag, false);
    }

    document.documentElement.addEventListener('mousemove', startDrag, false);
    document.documentElement.addEventListener('mouseup', stopDrag, false);
  }

  onToggleConsole() {
    this.reloadPrompt = false;
    ReplStore.toggleConsole();
  }

  onStdMessage(data, type) {
    let {formattedOutput} = ReplOutput.some(data).highlight(data);
    ReplConsoleActions.addEntry({
      type: type,
      data: [formattedOutput]
    });
    this.onConsoleChange();
  }

  onStdout(msg) {
    this.onStdMessage(msg.data ? msg.data.toString() : msg, 'log');
  }

  onStderr(msg) {
    this.onStdMessage(msg.data ? msg.data.toString() : msg, 'error');
  }

  onConsole({type, data}) {
    if(data.length === 0) { return; }
    let results;
    if(data.length > 1 && typeof data[0] === 'string' && data[0].match(/%[%sdj]/)) {
      results = [format.apply(null, data)];
    }
    else {
      results = _.reduce(data, function(result, datum) {
        let {formattedOutput} = ReplOutput.some(datum).highlight(datum);
        result.push(formattedOutput);
        return result;
      }, []);
    }

    ReplConsoleActions.addEntry({
      type: type,
      data: results
    });
    this.onConsoleChange(type);
  }

  onConsoleChange(type) {
    let currentWindow = remote.getCurrentWindow();
    if(!currentWindow.isFocused() && process.platform === 'darwin') {
      ipcRenderer.send('application:dock-message-notification', currentWindow.id);
    }
    if(this.state.showConsole) { return; }
    ReplStore.showBell();
  }

  getPromptKey() {
    if(!this.state.reloadPrompt) {
      return this.activePromptKey;
    }
    this.activePromptKey = Date.now();
    return this.activePromptKey;
  }

  render() {
    // force to recreate ReplPrompt
    return (

          <ReplEntries entries={this.state.entries} />
          <ReplPrompt key={this.getPromptKey()}
            history={this.state.history}
            historyIndex={this.state.historyIndex}
            historyStaged={this.state.historyStaged}
            command={this.state.command}
            cursor= {this.state.cursor} />

        {
          this.state.showConsole
            ?

                  <ReplConsole />

            : null
        }

        <ReplStatusBar history={this.state.entries}
          showConsole={this.state.showConsole}
          showBell={this.state.showBell}
          onToggleConsole={this.onToggleConsole}/>

    );
  }
}
<commit_msg>:bug: consider session language<commit_after>import React from 'react';
import _ from 'lodash';
import ReplEntries from './ReplEntries';
import ReplPrompt from './ReplPrompt';
import ReplStatusBar from './ReplStatusBar';
import ReplStore from '../stores/ReplStore';
import ReplDOMEvents from '../common/ReplDOMEvents';
import ReplDOM from '../common/ReplDOM';
import ReplActiveInputActions from '../actions/ReplActiveInputActions';
import ReplPreferencesActions from '../actions/ReplPreferencesActions';
import ReplConsoleActions from '../actions/ReplConsoleActions';
import ReplSuggestionActions from '../actions/ReplSuggestionActions';
import ReplStatusBarActions from '../actions/ReplStatusBarActions';
import Reflux from 'reflux';
import {ipcRenderer} from 'electron';
import {writeFile, readFile} from 'fs';
import {EOL} from 'os';
import remote from 'remote';
import ReplStreamHook from '../common/ReplStreamHook';
import ReplConsoleHook from '../common/ReplConsoleHook';
import ReplConsole from './ReplConsole';
import ReplOutput from '../common/ReplOutput';
import ContextMenu from '../menus/context-menu.json';
import ReplConstants from '../constants/ReplConstants';
import ReplContext from '../common/ReplContext';
import ReplCommon from '../common/ReplCommon';
import ReplLanguages from '../languages/ReplLanguages';
import {format} from 'util';

export default class Repl extends React.Component {
  constructor(props) {
    super(props);
    _.each([
      'onStateChange', 'onPaste', 'onContextMenu',
      'onKeydown', 'onBreakPrompt', 'onClearCommands',
      'onCollapseAll', 'onExpandAll', 'onDrag', 'onToggleConsole', 'onFormatPromptCode',
      'onStdout', 'onStderr', 'onStdMessage', 'onConsole', 'onConsoleChange', 'getPromptKey',
      'onImport', 'onExport', 'onAddPath', 'loadPreferences', 'onSaveCommands', 'onLoadScript',
      'checkNewRelease', 'onNewRelease', 'resizeWindow', 'onSetREPLMode', 'loadStartupScript', 'onInit'
    ], (field) => {
      this[field] = this[field].bind(this);
    });

    this.loadPreferences();
    ReplCommon.addUserDataToPath(ReplContext.getContext());

    this.state = _.cloneDeep(ReplStore.getStore());
  }

  componentDidMount() {
    // set REPL language
    ReplLanguages.setREPL(global.Mancy.preferences.lang);
    this.setupContextMenu();
    this.activePromptKey = Date.now();

    //register events
    this.unsubscribe = ReplStore.listen(this.onStateChange);

    window.addEventListener('paste', this.onPaste, false);
    window.addEventListener('contextmenu', this.onContextMenu, false);
    window.addEventListener('keydown', this.onKeydown, false);

    // hooks
    ReplStreamHook.on('stdout', this.onStdout);
    ReplStreamHook.on('stderr', this.onStderr);

    ReplConsoleHook.on('console', this.onConsole);

    ipcRenderer.on('application:import-file', this.onImport);
    ipcRenderer.on('application:export-file', this.onExport);
    ipcRenderer.on('application:add-path', this.onAddPath);
    ipcRenderer.on('application:save-as', this.onSaveCommands);
    ipcRenderer.on('application:load-file', this.onLoadScript);

    ipcRenderer.on('application:prompt-clear-all', this.onClearCommands);
    ipcRenderer.on('application:prompt-expand-all', this.onExpandAll);
    ipcRenderer.on('application:prompt-collapse-all', this.onCollapseAll);
    ipcRenderer.on('application:prompt-break', this.onBreakPrompt);
    ipcRenderer.on('application:prompt-format', this.onFormatPromptCode);

    ipcRenderer.on('application:prompt-mode', (sender, value) => this.onSetREPLMode(value));
    ipcRenderer.on('application:prompt-language', (sender, value) =>  {
      global.Mancy.session.lang = value;
      ReplLanguages.setREPL(value);
      ReplStatusBarActions.updateLanguage(value);
    });

    ipcRenderer.on('application:preferences', ReplPreferencesActions.openPreferences);

    ipcRenderer.on('application:preference-theme-dark', () => ReplPreferencesActions.setTheme('Dark Theme'));
    ipcRenderer.on('application:preference-theme-light', () => ReplPreferencesActions.setTheme('Light Theme'));

    ipcRenderer.on('application:view-theme-dark', () => document.body.className = 'dark-theme');
    ipcRenderer.on('application:view-theme-light', () => document.body.className = 'light-theme');

    ipcRenderer.on('application:new-release', this.onNewRelease);
    this.onInit();
  }

  onInit() {
    this.checkNewRelease();
    this.onSetREPLMode(global.Mancy.preferences.mode);
    ReplPreferencesActions.setTheme(global.Mancy.preferences.theme);

    this.resizeWindow();
    this.loadStartupScript();
    ipcRenderer.send('application:prompt-on-close', global.Mancy.preferences.promptOnClose);
  }

  onLoadScript(sender, script) {
    if(script) {
      let ext = script.replace(/(?:.*)\.(\w+)$/, '$1');
      let lang = ReplLanguages.getLangName(ext);
      if(lang) {
        ReplLanguages.setREPL(lang);
        ReplActiveInputActions.playCommands([`.load ${script}`]);
        if(lang !== global.Mancy.session.lang) {
          setTimeout(() => {
            ReplLanguages.setREPL(global.Mancy.session.lang);
            ReplStore.onReloadPrompt('');
          }, 200);
        }
      } else {
        let options = {
          buttons: ['Close'],
          title: 'Failed to load script',
          type: 'error',
          message: `Failed to load '${script}'. '${ext}' extension is not supported.`
        };
        ipcRenderer.send('application:message-box', options);
      }
    }
  }

  loadStartupScript() {
    this.onLoadScript(null, global.Mancy.preferences.loadScript);
  }

  resizeWindow() {
    let setSize = (w, h) => localStorage.setItem('window', JSON.stringify({ width: w, height: h }));
    let win = remote.getCurrentWindow();
    let lastWindow = JSON.parse(localStorage.getItem('window'));
    let [width, height] = win.getSize();
    if(!lastWindow) { setSize(width, height) }
    else {
      try {
        win.setSize(lastWindow.width, lastWindow.height);
      } catch(e) {}
    }
    win.on('resize', () => {
      let [width, height] = win.getSize();
      setSize(width, height);
    });
  }

  setupContextMenu() {
    let Menu = remote.require('menu');
    let contextMenu = _.cloneDeep(ContextMenu);
    let actionTemplates = [
      {
        label: 'Clear All',
        accelerator: 'Ctrl+L',
        click: this.onClearCommands
      },
      {
        label: 'Collapse All',
        accelerator: 'CmdOrCtrl+K',
        click: this.onCollapseAll
      },
      {
        label: 'Expand All',
        accelerator: 'CmdOrCtrl+E',
        click: this.onExpandAll
      },
      {
        label: 'Break Prompt',
        accelerator: 'Ctrl+D',
        click: this.onBreakPrompt
      },
      {
        label: 'Format',
        accelerator: 'Shift+Ctrl+F',
        click: this.onFormatPromptCode
      }
    ];

    _.each(actionTemplates, (template) => contextMenu.push(template));

    this.menu = Menu.buildFromTemplate(contextMenu);
  }

  componentWillUnmount() {
    this.unsubscribe();
    window.removeEventListener('paste', this.onPaste, false);
    window.removeEventListener('contextmenu', this.onContextMenu, false);
    window.removeEventListener('keydown', this.onKeydown, false);

    ReplStreamHook.removeListener('stdout', this.onStdout);
    ReplStreamHook.removeListener('stderr', this.onStderr);
    ReplStreamHook.disable();

    ReplConsoleHook.removeListener('console', this.onConsole);
    ReplConsoleHook.disable();
  }

  checkNewRelease() {
    setTimeout(() => ipcRenderer.send('application:check-new-release'), 2000);
  }

  loadPreferences() {
    let preferences = JSON.parse(localStorage.getItem('preferences'));
    ipcRenderer.send('application:sync-preference', preferences);
  }

  onNewRelease(release) {
    ReplStatusBarActions.newRelease(release);
  }

  onSaveCommands(sender, filename) {
    let {history} = ReplStore.getStore();
    let data = _.chain(history)
      .map((h) => h.plainCode)
      .filter((c) => !/^\s*\./.test(c))
      .value()
      .join(EOL);

    writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => {
      let options = { buttons: ['Close'] };
      if(err) {
        options = _.extend(options, {
          title: 'Save Error',
          type: 'error',
          message: err.name || ' Error',
          detail: err.toString()
        });
      } else {
        options = _.extend(options, {
          title: 'Commands saved',
          type: 'info',
          message: `Commands saved to ${filename}`
        });
      }
      ipcRenderer.send('application:message-box', options);
    });
  }

  onImport(sender, filename) {
    readFile(filename, (err, data) => {
      if(!err) {
        try {
          let history = JSON.parse(data);
          if(!Array.isArray(history) || !_.every(history, (h) => typeof h === 'string')) {
            throw Error(`Invalid session file ${filename}`);
          }
          ReplActiveInputActions.playCommands(history);
          return;
        } catch(e) {
          err = e;
        }
      }

      ipcRenderer.send('application:message-box', {
        title: 'Load session error',
        buttons: ['Close'],
        type: 'error',
        message: err.toString()
      });
    });
  }

  onExport(sender, filename) {
    let {history} = ReplStore.getStore();
    let data = JSON.stringify(_.map(history, (h) => h.plainCode));
    writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => {
      let options = { buttons: ['Close'] };
      if(err) {
        options = _.extend(options, {
          title: 'Export Error',
          type: 'error',
          message: err.name || ' Error',
          detail: err.toString()
        });
      } else {
        options = _.extend(options, {
          title: 'Session saved',
          type: 'info',
          message: `Session saved to ${filename}`
        });
      }
      ipcRenderer.send('application:message-box', options);
    });
  }

  onAddPath(sender, paths) {
    ReplCommon.addToPath(paths, ReplContext.getContext());
  }

  onContextMenu(e) {
    e.preventDefault();
    this.menu.popup(remote.getCurrentWindow());
  }

  onSetREPLMode(mode) {
    ReplStore.onSetREPLMode(mode);
    ReplStatusBarActions.updateMode(mode);
    global.Mancy.session.mode = mode;
  }

  onPaste(e) {
    e.preventDefault();
    var text = e.clipboardData.getData("text/plain");
    document.execCommand("insertHTML", false, text);
    ReplSuggestionActions.removeSuggestion();
  }

  onKeydown(e) {
    if(ReplDOMEvents.isEnter(e)) {
      ReplDOM.scrollToEnd();
      return;
    }
    if(e.ctrlKey && ReplDOMEvents.isSpace(e)) {
      ReplActiveInputActions.performAutoComplete();
    }
  }

  onFormatPromptCode() {
    ReplActiveInputActions.formatCode();
  }

  onCollapseAll() {
    ReplStore.collapseAll();
  }

  onExpandAll() {
    ReplStore.expandAll();
  }

  onBreakPrompt() {
    ReplActiveInputActions.breakPrompt();
  }

  onClearCommands() {
    ReplStore.clearStore();
    ReplConsoleActions.clear();
  }

  onStateChange() {
    this.setState(ReplStore.getStore());
  }

  onDrag(e) {
    let replConsole = document.getElementsByClassName('repl-console')[0];
    let replContainerRight = document.getElementsByClassName('repl-container-right')[0];

    let {clientX} = e;
    let {width} = document.defaultView.getComputedStyle(replConsole);
    let initWidth = parseInt(width, 10);

    let startDrag = (e) => {
      let adj = e.clientX - clientX;
      replContainerRight.style.flex = '0 0  ' + (initWidth - adj) + 'px';
    }

    let stopDrag = (e) => {
      document.documentElement.removeEventListener('mousemove', startDrag, false);
      document.documentElement.removeEventListener('mouseup', stopDrag, false);
    }

    document.documentElement.addEventListener('mousemove', startDrag, false);
    document.documentElement.addEventListener('mouseup', stopDrag, false);
  }

  onToggleConsole() {
    this.reloadPrompt = false;
    ReplStore.toggleConsole();
  }

  onStdMessage(data, type) {
    let {formattedOutput} = ReplOutput.some(data).highlight(data);
    ReplConsoleActions.addEntry({
      type: type,
      data: [formattedOutput]
    });
    this.onConsoleChange();
  }

  onStdout(msg) {
    this.onStdMessage(msg.data ? msg.data.toString() : msg, 'log');
  }

  onStderr(msg) {
    this.onStdMessage(msg.data ? msg.data.toString() : msg, 'error');
  }

  onConsole({type, data}) {
    if(data.length === 0) { return; }
    let results;
    if(data.length > 1 && typeof data[0] === 'string' && data[0].match(/%[%sdj]/)) {
      results = [format.apply(null, data)];
    }
    else {
      results = _.reduce(data, function(result, datum) {
        let {formattedOutput} = ReplOutput.some(datum).highlight(datum);
        result.push(formattedOutput);
        return result;
      }, []);
    }

    ReplConsoleActions.addEntry({
      type: type,
      data: results
    });
    this.onConsoleChange(type);
  }

  onConsoleChange(type) {
    let currentWindow = remote.getCurrentWindow();
    if(!currentWindow.isFocused() && process.platform === 'darwin') {
      ipcRenderer.send('application:dock-message-notification', currentWindow.id);
    }
    if(this.state.showConsole) { return; }
    ReplStore.showBell();
  }

  getPromptKey() {
    if(!this.state.reloadPrompt) {
      return this.activePromptKey;
    }
    this.activePromptKey = Date.now();
    return this.activePromptKey;
  }

  render() {
    // force to recreate ReplPrompt
    return (

          <ReplEntries entries={this.state.entries} />
          <ReplPrompt key={this.getPromptKey()}
            history={this.state.history}
            historyIndex={this.state.historyIndex}
            historyStaged={this.state.historyStaged}
            command={this.state.command}
            cursor= {this.state.cursor} />

        {
          this.state.showConsole
            ?

                  <ReplConsole />

            : null
        }

        <ReplStatusBar history={this.state.entries}
          showConsole={this.state.showConsole}
          showBell={this.state.showBell}
          onToggleConsole={this.onToggleConsole}/>

    );
  }
}
<|endoftext|>


<commit_before><commit_msg>format<commit_after><|endoftext|>


<commit_before>import React from 'react'

const Tldr = ({size}) => {
  let className=`brand ${size}`
  return ()
}

export default Tldr
<commit_msg>Logo links to home<commit_after>import React from 'react'

const Tldr = ({size}) => {
  let className=`brand ${size}`
  return ()
}

export default Tldr
<|endoftext|>


<commit_before>import React from 'react';
import {
  Row,
  Col
} from 'react-bootstrap'

const CommentItem = ({user, content, create_at}) => {
  create_at = create_at.slice(0, 10);
  return (
    <Row>

        <Col md={2}>{ user.username }: </Col>
        <Col md={8}>{ content }</Col>
        <Col md={2}>{ create_at }</Col>

    </Row>

  )
}

export default CommentItem;
<commit_msg>Comment marked<commit_after>import React from 'react';
import {
  Row,
  Col
} from 'react-bootstrap'

const marked = require('marked');

const CommentItem = ({user, content, create_at}) => {
  create_at = create_at.slice(0, 10);
  return (
    <Row>

        <Col md={2}>{ user.username }: </Col>
        <Col md={8}>
          {
           content ?
                   : null
          }
        </Col>
        <Col md={2}>{ create_at }</Col>

    </Row>

  )
}

export default CommentItem;

<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import { Text, View } from 'react-native';

import type { ChatThreadItem } from 'lib/selectors/chat-selectors';
import type { ThreadInfo } from 'lib/types/thread-types';
import type { UserInfo } from 'lib/types/user-types';
import { shortAbsoluteDate } from 'lib/utils/date-utils';

import Button from '../components/button.react';
import ColorSplotch from '../components/color-splotch.react';
import { SingleLine } from '../components/single-line.react';
import ThreadAncestorsLabel from '../components/thread-ancestors-label.react';
import UnreadDot from '../components/unread-dot.react';
import { useColors, useStyles } from '../themes/colors';
import ChatThreadListSeeMoreSidebars from './chat-thread-list-see-more-sidebars.react';
import ChatThreadListSidebar from './chat-thread-list-sidebar.react';
import MessagePreview from './message-preview.react';
import SwipeableThread from './swipeable-thread.react';

type Props = {|
  +data: ChatThreadItem,
  +onPressItem: (
    threadInfo: ThreadInfo,
    pendingPersonalThreadUserInfo?: UserInfo,
  ) => void,
  +onPressSeeMoreSidebars: (threadInfo: ThreadInfo) => void,
  +onSwipeableWillOpen: (threadInfo: ThreadInfo) => void,
  +currentlyOpenedSwipeableId: string,
|};
function ChatThreadListItem({
  data,
  onPressItem,
  onPressSeeMoreSidebars,
  onSwipeableWillOpen,
  currentlyOpenedSwipeableId,
}: Props) {
  const styles = useStyles(unboundStyles);
  const colors = useColors();

  const lastMessage = React.useMemo(() => {
    const mostRecentMessageInfo = data.mostRecentMessageInfo;
    if (!mostRecentMessageInfo) {
      return (
        <Text style={styles.noMessages} numberOfLines={1}>
          No messages
        </Text>
      );
    }
    return (
      <MessagePreview
        messageInfo={mostRecentMessageInfo}
        threadInfo={data.threadInfo}
      />
    );
  }, [data.mostRecentMessageInfo, data.threadInfo, styles]);

  const sidebars = data.sidebars.map((sidebarItem) => {
    if (sidebarItem.type === 'sidebar') {
      const { type, ...sidebarInfo } = sidebarItem;
      return (
        <ChatThreadListSidebar
          sidebarInfo={sidebarInfo}
          onPressItem={onPressItem}
          onSwipeableWillOpen={onSwipeableWillOpen}
          currentlyOpenedSwipeableId={currentlyOpenedSwipeableId}
          key={sidebarItem.threadInfo.id}
        />
      );
    } else if (sidebarItem.type === 'seeMore') {
      return (
        <ChatThreadListSeeMoreSidebars
          threadInfo={data.threadInfo}
          unread={sidebarItem.unread}
          showingSidebarsInline={sidebarItem.showingSidebarsInline}
          onPress={onPressSeeMoreSidebars}
          key="seeMore"
        />
      );
    } else {
      return <View style={styles.spacer} key="spacer" />;
    }
  });

  const onPress = React.useCallback(() => {
    onPressItem(data.threadInfo, data.pendingPersonalThreadUserInfo);
  }, [onPressItem, data.threadInfo, data.pendingPersonalThreadUserInfo]);

  const threadNameStyle = React.useMemo(() => {
    if (!data.threadInfo.currentUser.unread) {
      return styles.threadName;
    }
    return [styles.threadName, styles.unreadThreadName];
  }, [
    data.threadInfo.currentUser.unread,
    styles.threadName,
    styles.unreadThreadName,
  ]);

  const lastActivity = shortAbsoluteDate(data.lastUpdatedTime);
  const lastActivityStyle = React.useMemo(() => {
    if (!data.threadInfo.currentUser.unread) {
      return styles.lastActivity;
    }
    return [styles.lastActivity, styles.unreadLastActivity];
  }, [
    data.threadInfo.currentUser.unread,
    styles.lastActivity,
    styles.unreadLastActivity,
  ]);

  return (
    <>
      <SwipeableThread
        threadInfo={data.threadInfo}
        mostRecentNonLocalMessage={data.mostRecentNonLocalMessage}
        onSwipeableWillOpen={onSwipeableWillOpen}
        currentlyOpenedSwipeableId={currentlyOpenedSwipeableId}
        iconSize={24}
      >
        <Button
          onPress={onPress}
          iosFormat="highlight"
          iosHighlightUnderlayColor={colors.listIosHighlightUnderlay}
          iosActiveOpacity={0.85}
          style={styles.container}
        >
          <View style={styles.content}>
            <View style={styles.colorSplotch}>
              <UnreadDot unread={data.threadInfo.currentUser.unread} />
            </View>
            <View style={styles.colorSplotch}>
              <ColorSplotch color={data.threadInfo.color} size="profile" />
            </View>
            <View style={styles.threadDetails}>
              <ThreadAncestorsLabel
                threadInfo={data.threadInfo}
                unread={data.threadInfo.currentUser.unread}
              />
              <View style={styles.row}>
                <SingleLine style={threadNameStyle}>
                  {data.threadInfo.uiName}
                </SingleLine>
              </View>
              <View style={styles.row}>
                {lastMessage}
                <Text style={lastActivityStyle}>{lastActivity}</Text>
              </View>
            </View>
          </View>
        </Button>
      </SwipeableThread>
      {sidebars}
    </>
  );
}

const chatThreadListItemHeight = 70;
const spacerHeight = 6;
const unboundStyles = {
  container: {
    height: chatThreadListItemHeight,
    justifyContent: 'center',
    backgroundColor: 'listBackground',
  },
  content: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  colorSplotch: {
    marginLeft: 6,
    marginBottom: 12,
  },
  threadDetails: {
    paddingLeft: 12,
    paddingRight: 18,
    justifyContent: 'center',
    flex: 1,
    marginTop: 5,
  },
  lastActivity: {
    color: 'listForegroundTertiaryLabel',
    fontSize: 14,
    marginLeft: 10,
  },
  unreadLastActivity: {
    color: 'listForegroundLabel',
    fontWeight: 'bold',
  },
  noMessages: {
    color: 'listForegroundTertiaryLabel',
    flex: 1,
    fontSize: 14,
    fontStyle: 'italic',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  threadName: {
    color: 'listForegroundSecondaryLabel',
    flex: 1,
    fontSize: 18,
  },
  unreadThreadName: {
    color: 'listForegroundLabel',
    fontWeight: '500',
  },
  spacer: {
    height: spacerHeight,
  },
};

export { ChatThreadListItem, chatThreadListItemHeight, spacerHeight };
<commit_msg>[native] Increase thread name size in ChatThreadListItem<commit_after>// @flow

import * as React from 'react';
import { Text, View } from 'react-native';

import type { ChatThreadItem } from 'lib/selectors/chat-selectors';
import type { ThreadInfo } from 'lib/types/thread-types';
import type { UserInfo } from 'lib/types/user-types';
import { shortAbsoluteDate } from 'lib/utils/date-utils';

import Button from '../components/button.react';
import ColorSplotch from '../components/color-splotch.react';
import { SingleLine } from '../components/single-line.react';
import ThreadAncestorsLabel from '../components/thread-ancestors-label.react';
import UnreadDot from '../components/unread-dot.react';
import { useColors, useStyles } from '../themes/colors';
import ChatThreadListSeeMoreSidebars from './chat-thread-list-see-more-sidebars.react';
import ChatThreadListSidebar from './chat-thread-list-sidebar.react';
import MessagePreview from './message-preview.react';
import SwipeableThread from './swipeable-thread.react';

type Props = {|
  +data: ChatThreadItem,
  +onPressItem: (
    threadInfo: ThreadInfo,
    pendingPersonalThreadUserInfo?: UserInfo,
  ) => void,
  +onPressSeeMoreSidebars: (threadInfo: ThreadInfo) => void,
  +onSwipeableWillOpen: (threadInfo: ThreadInfo) => void,
  +currentlyOpenedSwipeableId: string,
|};
function ChatThreadListItem({
  data,
  onPressItem,
  onPressSeeMoreSidebars,
  onSwipeableWillOpen,
  currentlyOpenedSwipeableId,
}: Props) {
  const styles = useStyles(unboundStyles);
  const colors = useColors();

  const lastMessage = React.useMemo(() => {
    const mostRecentMessageInfo = data.mostRecentMessageInfo;
    if (!mostRecentMessageInfo) {
      return (
        <Text style={styles.noMessages} numberOfLines={1}>
          No messages
        </Text>
      );
    }
    return (
      <MessagePreview
        messageInfo={mostRecentMessageInfo}
        threadInfo={data.threadInfo}
      />
    );
  }, [data.mostRecentMessageInfo, data.threadInfo, styles]);

  const sidebars = data.sidebars.map((sidebarItem) => {
    if (sidebarItem.type === 'sidebar') {
      const { type, ...sidebarInfo } = sidebarItem;
      return (
        <ChatThreadListSidebar
          sidebarInfo={sidebarInfo}
          onPressItem={onPressItem}
          onSwipeableWillOpen={onSwipeableWillOpen}
          currentlyOpenedSwipeableId={currentlyOpenedSwipeableId}
          key={sidebarItem.threadInfo.id}
        />
      );
    } else if (sidebarItem.type === 'seeMore') {
      return (
        <ChatThreadListSeeMoreSidebars
          threadInfo={data.threadInfo}
          unread={sidebarItem.unread}
          showingSidebarsInline={sidebarItem.showingSidebarsInline}
          onPress={onPressSeeMoreSidebars}
          key="seeMore"
        />
      );
    } else {
      return <View style={styles.spacer} key="spacer" />;
    }
  });

  const onPress = React.useCallback(() => {
    onPressItem(data.threadInfo, data.pendingPersonalThreadUserInfo);
  }, [onPressItem, data.threadInfo, data.pendingPersonalThreadUserInfo]);

  const threadNameStyle = React.useMemo(() => {
    if (!data.threadInfo.currentUser.unread) {
      return styles.threadName;
    }
    return [styles.threadName, styles.unreadThreadName];
  }, [
    data.threadInfo.currentUser.unread,
    styles.threadName,
    styles.unreadThreadName,
  ]);

  const lastActivity = shortAbsoluteDate(data.lastUpdatedTime);
  const lastActivityStyle = React.useMemo(() => {
    if (!data.threadInfo.currentUser.unread) {
      return styles.lastActivity;
    }
    return [styles.lastActivity, styles.unreadLastActivity];
  }, [
    data.threadInfo.currentUser.unread,
    styles.lastActivity,
    styles.unreadLastActivity,
  ]);

  return (
    <>
      <SwipeableThread
        threadInfo={data.threadInfo}
        mostRecentNonLocalMessage={data.mostRecentNonLocalMessage}
        onSwipeableWillOpen={onSwipeableWillOpen}
        currentlyOpenedSwipeableId={currentlyOpenedSwipeableId}
        iconSize={24}
      >
        <Button
          onPress={onPress}
          iosFormat="highlight"
          iosHighlightUnderlayColor={colors.listIosHighlightUnderlay}
          iosActiveOpacity={0.85}
          style={styles.container}
        >
          <View style={styles.content}>
            <View style={styles.colorSplotch}>
              <UnreadDot unread={data.threadInfo.currentUser.unread} />
            </View>
            <View style={styles.colorSplotch}>
              <ColorSplotch color={data.threadInfo.color} size="profile" />
            </View>
            <View style={styles.threadDetails}>
              <ThreadAncestorsLabel
                threadInfo={data.threadInfo}
                unread={data.threadInfo.currentUser.unread}
              />
              <View style={styles.row}>
                <SingleLine style={threadNameStyle}>
                  {data.threadInfo.uiName}
                </SingleLine>
              </View>
              <View style={styles.row}>
                {lastMessage}
                <Text style={lastActivityStyle}>{lastActivity}</Text>
              </View>
            </View>
          </View>
        </Button>
      </SwipeableThread>
      {sidebars}
    </>
  );
}

const chatThreadListItemHeight = 70;
const spacerHeight = 6;
const unboundStyles = {
  container: {
    height: chatThreadListItemHeight,
    justifyContent: 'center',
    backgroundColor: 'listBackground',
  },
  content: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  colorSplotch: {
    marginLeft: 6,
    marginBottom: 12,
  },
  threadDetails: {
    paddingLeft: 12,
    paddingRight: 18,
    justifyContent: 'center',
    flex: 1,
    marginTop: 5,
  },
  lastActivity: {
    color: 'listForegroundTertiaryLabel',
    fontSize: 14,
    marginLeft: 10,
  },
  unreadLastActivity: {
    color: 'listForegroundLabel',
    fontWeight: 'bold',
  },
  noMessages: {
    color: 'listForegroundTertiaryLabel',
    flex: 1,
    fontSize: 14,
    fontStyle: 'italic',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  threadName: {
    color: 'listForegroundSecondaryLabel',
    flex: 1,
    fontSize: 21,
  },
  unreadThreadName: {
    color: 'listForegroundLabel',
    fontWeight: '500',
  },
  spacer: {
    height: spacerHeight,
  },
};

export { ChatThreadListItem, chatThreadListItemHeight, spacerHeight };
<|endoftext|>


<commit_before><commit_msg>remove CODE variable<commit_after><|endoftext|>


<commit_before>"use strict";

const EventEmitter = require("events").EventEmitter;
const net = require("net");
const fs = require("fs");
const os = require("os");

const streamChunks = require("./stream-util").streamChunks;

const endianness = os.endianness();
const uint32Size = 4;

const bufferFrom = (object) => {
  const serialized = JSON.stringify(object);
  const length = Buffer.byteLength(serialized, "utf8")
  const buffer = new Buffer(uint32Size + length);

  buffer[`writeUInt32${endianness}`](length, 0);
  buffer.write(serialized, uint32Size);

  return buffer;
};

const streamObjects = (readable, emit) => {
  let objectSize;
  streamChunks(readable, () => {
    return objectSize === undefined ?
      uint32Size : // read the size of the object
      objectSize;  // read the object
  }, (chunk) => {
    if (objectSize === undefined) {
      objectSize = chunk[`readUInt32${endianness}`](0);
    }
    else {
      objectSize = undefined;
      emit(chunk);
    }
  });
};

class Port extends EventEmitter {

  constructor(client) {
    super();
    this._client = client;

    streamObjects(client, (message) => {
      let parsed;
      try {
        parsed = JSON.parse(message);
      }
      catch (e) {
        this.emit("error", new Error(`While parsing "${message}": ${e}`));
        return;
      }

      this.emit("message", parsed);
    });

    client.on("close", () => this.emit("disconnect"));
  }

  post(message) {
    this._client.write(bufferFrom(message));
  }

}

class MessagingChannel extends EventEmitter {

  constructor(sockPath) {
    super();
    this._server = net.Server();

    this._server.on("connection", (client) => {
      this.emit("connection", new Port(client));
    });

    this._server.listen(sockPath);
  }

  close() {
    // Needs to be synchronous as it could be called when exiting the process.
    if (fs.existsSync(this._sockPath)) fs.unlinkSync(this._sockPath);
  }

}

module.exports = MessagingChannel;
<commit_msg>Fix messagingChannel.close()<commit_after>"use strict";

const EventEmitter = require("events").EventEmitter;
const net = require("net");
const fs = require("fs");
const os = require("os");

const streamChunks = require("./stream-util").streamChunks;

const endianness = os.endianness();
const uint32Size = 4;

const bufferFrom = (object) => {
  const serialized = JSON.stringify(object);
  const length = Buffer.byteLength(serialized, "utf8")
  const buffer = new Buffer(uint32Size + length);

  buffer[`writeUInt32${endianness}`](length, 0);
  buffer.write(serialized, uint32Size);

  return buffer;
};

const streamObjects = (readable, emit) => {
  let objectSize;
  streamChunks(readable, () => {
    return objectSize === undefined ?
      uint32Size : // read the size of the object
      objectSize;  // read the object
  }, (chunk) => {
    if (objectSize === undefined) {
      objectSize = chunk[`readUInt32${endianness}`](0);
    }
    else {
      objectSize = undefined;
      emit(chunk);
    }
  });
};

class Port extends EventEmitter {

  constructor(client) {
    super();
    this._client = client;

    streamObjects(client, (message) => {
      let parsed;
      try {
        parsed = JSON.parse(message);
      }
      catch (e) {
        this.emit("error", new Error(`While parsing "${message}": ${e}`));
        return;
      }

      this.emit("message", parsed);
    });

    client.on("close", () => this.emit("disconnect"));
  }

  post(message) {
    this._client.write(bufferFrom(message));
  }

}

class MessagingChannel extends EventEmitter {

  constructor(sockPath) {
    super();
    this._sockPath = sockPath;
    this._server = net.Server();

    this._server.on("connection", (client) => {
      this.emit("connection", new Port(client));
    });

    this._server.listen(sockPath);
  }

  close() {
    // Needs to be synchronous as it could be called when exiting the process.
    this._server.close();
    if (fs.existsSync(this._sockPath)) fs.unlinkSync(this._sockPath);
  }

}

module.exports = MessagingChannel;
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by __gulp_init__author_name @ __gulp_init__author_company

module.exports = {
    init(gulp, plugins, on_error) {
        let project_data = {};

        // gather project data
        const get_project_data = (callback) => {
            return gulp.src("./gulpfile.js")
                // prevent breaking on error
                .pipe(plugins.plumber({errorHandler: on_error}))
                // prompt for project data
                .pipe(plugins.prompt.prompt([
                    {
                        name:     "full_name",
                        message:  "Project Name:",
                        type:     "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a full name.";
                            }
                        },
                    },
                    {
                        name:     "short_name",
                        message:  "Project Short Name:",
                        type:     "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a short name.";
                            }
                        },
                    },
                    {
                        name:     "version",
                        message:  "Project Version:",
                        type:     "input",
                        default:  "0.1.0",
                        validate: (response) => {
                            if (response.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/)) {
                                return true;
                            } else {
                                return "Please enter a valid version number (semver).";
                            }
                        },
                    },
                    {
                        name:    "description",
                        message: "Project Description:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a description.";
                            }
                        },
                    },
                    {
                        name:     "homepage",
                        message:  "Project URL:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:     "repository",
                        message:  "Project Repository:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:    "author_name",
                        message: "Author Name:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a name.";
                            }
                        },
                    },
                    {
                        name:     "author_email",
                        message:  "Author Email:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
                                return true;
                            } else {
                                return "Please enter a valid email address.";
                            }
                        }
                    },
                    {
                        name:    "author_company",
                        message: "Author Company:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a company.";
                            }
                        },
                    },
                    {
                        name:     "author_url",
                        message:  "Author URL:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:    "remove_modules",
                        message: "Modules to Remove:",
                        type:    "checkbox",
                        choices: ["Resources", "Tribe Events"],
                    },
                    {
                        name:     "theme_color",
                        message:  "Theme Color:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/)) {
                                return true;
                            } else {
                                return "Please enter a valid hex color.";
                            }
                        },
                    },
                    {
                        name:    "heading_font",
                        message: "Heading Font:",
                        type:    "input",
                        default: "\"Open Sans\", \"Arial\", \"Helvetica\", sans-serif",
                    },
                    {
                        name:    "body_font",
                        message: "Body Font:",
                        type:    "input",
                        default: "\"Open Sans\", \"Arial\", \"Helvetica\", sans-serif",
                    },
                    {
                        name:     "site_width",
                        message:  "Site Width:",
                        type:     "input",
                        default:  "1500",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                    {
                        name:     "column_gap",
                        message:  "Column Gap:",
                        type:     "input",
                        default:  "30",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                    {
                        name:     "content_padding",
                        message:  "Content Padding:",
                        type:     "input",
                        default:  "25",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                ], (res) => {
                    // store the project data
                    project_data = res;
                })).on("end", () => {
                    // return the callback
                    if (typeof callback === "function") {
                        return callback();
                    }
                });
        };

        // write project data
        const write_project_data = (callback) => {
            return gulp.src(["./*", "./gulp-tasks/*", "./src/**/*"], {base: "./"})
                // prevent breaking on error
                .pipe(plugins.plumber({errorHandler: on_error}))
                // check if a file is a binary
                .pipe(plugins.is_binary())
                // skip file if it's a binary
                .pipe(plugins.through.obj((file, enc, next) => {
                    if (file.isBinary()) {
                        next();
                        return;
                    }

                    // go to next file
                    next(null, file);
                }))
                // replace variables with project data
                .pipe(plugins.file_include({
                    prefix:   "__gulp_init__",
                    basepath: "@file",
                    context: {
                        full_name:       project_data.full_name,
                        short_name:      project_data.short_name,
                        npm_name:        project_data.full_name.toLowerCase().replace(/[^A-Za-z ]/, "").replace(/ /g, "-"),
                        namespace:       project_data.short_name.toLowerCase().replace(/[^A-Za-z ]/, "").replace(/ /g, "_"),
                        version:         project_data.version,
                        description:     project_data.description,
                        homepage_url:    project_data.homepage,
                        repository:      project_data.repository.replace(/(\.git$)|(\/$)/, ""),
                        author_name:     project_data.author_name,
                        author_email:    project_data.author_email,
                        author_company:  project_data.author_company,
                        author_url:      project_data.author_url,
                        theme_color:     project_data.theme_color,
                        heading_font:    project_data.heading_font,
                        body_font:       project_data.body_font,
                        site_width:      project_data.site_width,
                        column_gap:      project_data.column_gap,
                        content_padding: project_data.content_padding,
                    }
                }))
                // write the file
                .pipe(gulp.dest("./")).on("end", () => {
                    // return the callback
                    if (typeof callback === "function") {
                        return callback();
                    }
                });
        };

        // remove modules selected during init
        const remove_selected_modules = (callback) => {
            return new Promise ((resolve) => {
                gulp.src(global.settings.paths.src + "/**/*")
                    // check if a file is a binary
                    .pipe(plugins.is_binary())
                    // skip file if it's a binary
                    .pipe(plugins.through.obj((file, enc, next) => {
                        if (file.isBinary()) {
                            next();
                            return;
                        }

                        // go to next file
                        next(null, file);
                    }))

                    // remove resource code if selected
                    .pipe(plugins.remove_code({resources_html: project_data.remove_modules.indexOf("Resources") > -1 ? true : false, commentStart: "<!--", commentEnd: "-->"}))
                    .pipe(plugins.remove_code({resources_css_js_php: project_data.remove_modules.indexOf("Resources") > -1 ? true : false, commentStart: "/*", commentEnd: "*/"}))

                    // remove tribe code if selected
                    .pipe(plugins.remove_code({tribe_html: project_data.remove_modules.indexOf("Tribe Events") > -1 ? true : false, commentStart: "<!--", commentEnd: "-->"}))
                    .pipe(plugins.remove_code({tribe_css_js_php: project_data.remove_modules.indexOf("Tribe Events") > -1 ? true : false, commentStart: "/*", commentEnd: "*/"}))

                    // output to source directory
                    .pipe(gulp.dest(global.settings.paths.src)).on("end", () => {
                        // resolve the promise
                        resolve();
                    });
            }).then(() => {
                return new Promise ((resolve) => {
                    // remove any empty files
                    plugins.glob(global.settings.paths.src + "/**/*", (err, files) => {
                        files.forEach((file) => {
                            if (plugins.fs.statSync(file).size <= 1) {
                                plugins.fs.unlinkSync(file);
                                console.log("\x1b[32m✔\x1b[0m deleted: " + plugins.path.relative(process.cwd(), file));
                            }
                        });

                        // resolve the promise
                        resolve();
                    });
                }).then(() => {
                    // remove any empty folders
                    return new Promise ((resolve) => {
                        plugins.delete_empty(global.settings.paths.src, () => {
                            // resolve the promise
                            resolve();
                        });
                    }).then(() => {
                        // remove any remaining comments
                        gulp.src(global.settings.paths.src + "/**/*")
                            // check if a file is a binary
                            .pipe(plugins.is_binary())
                            // skip file if it's a binary
                            .pipe(plugins.through.obj((file, enc, next) => {
                                if (file.isBinary()) {
                                    next();
                                    return;
                                }

                                // go to next file
                                next(null, file);
                            }))
                            // for comments that are on their own line, remove the entire line, otherwise just delete the comment
                            .pipe(plugins.replace(/(^((?:\/\*|<!--)(?:end)?[rR]emoveIf\([^)]+\)(?:\*\/|-->))\n$)|(((?:\/\*|<!--)(?:end)?[rR]emoveIf\([^)]+\)(?:\*\/|-->)))/gm, ""))
                            .pipe(gulp.dest(global.settings.paths.src))
                            .on("end", () => {
                                // return the callback
                                if (typeof callback === "function") {
                                    return callback();
                                }
                            });
                    });
                });
            });
        };

        return new Promise ((resolve) => {
            get_project_data(() => {
                write_project_data(() => {
                    remove_selected_modules(() => {
                        return resolve();
                    });
                });
            });
        });
    }
};
<commit_msg>Add a default color value<commit_after>// JavaScript Document

// Scripts written by __gulp_init__author_name @ __gulp_init__author_company

module.exports = {
    init(gulp, plugins, on_error) {
        let project_data = {};

        // gather project data
        const get_project_data = (callback) => {
            return gulp.src("./gulpfile.js")
                // prevent breaking on error
                .pipe(plugins.plumber({errorHandler: on_error}))
                // prompt for project data
                .pipe(plugins.prompt.prompt([
                    {
                        name:     "full_name",
                        message:  "Project Name:",
                        type:     "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a full name.";
                            }
                        },
                    },
                    {
                        name:     "short_name",
                        message:  "Project Short Name:",
                        type:     "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a short name.";
                            }
                        },
                    },
                    {
                        name:     "version",
                        message:  "Project Version:",
                        type:     "input",
                        default:  "0.1.0",
                        validate: (response) => {
                            if (response.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/)) {
                                return true;
                            } else {
                                return "Please enter a valid version number (semver).";
                            }
                        },
                    },
                    {
                        name:    "description",
                        message: "Project Description:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a description.";
                            }
                        },
                    },
                    {
                        name:     "homepage",
                        message:  "Project URL:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:     "repository",
                        message:  "Project Repository:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:    "author_name",
                        message: "Author Name:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a name.";
                            }
                        },
                    },
                    {
                        name:     "author_email",
                        message:  "Author Email:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
                                return true;
                            } else {
                                return "Please enter a valid email address.";
                            }
                        }
                    },
                    {
                        name:    "author_company",
                        message: "Author Company:",
                        type:    "input",
                        validate: (response) => {
                            if (response.trim().length > 0 && response.match(/\w/)) {
                                return true;
                            } else {
                                return "Please enter a company.";
                            }
                        },
                    },
                    {
                        name:     "author_url",
                        message:  "Author URL:",
                        type:     "input",
                        validate: (response) => {
                            if (response.match(/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/)) {
                                return true;
                            } else {
                                return "Please enter a valid URL.";
                            }
                        },
                    },
                    {
                        name:    "remove_modules",
                        message: "Modules to Remove:",
                        type:    "checkbox",
                        choices: ["Resources", "Tribe Events"],
                    },
                    {
                        name:     "theme_color",
                        message:  "Theme Color:",
                        type:     "input",
                        default:  "#17AAEC",
                        validate: (response) => {
                            if (response.match(/^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/)) {
                                return true;
                            } else {
                                return "Please enter a valid hex color.";
                            }
                        },
                    },
                    {
                        name:    "heading_font",
                        message: "Heading Font:",
                        type:    "input",
                        default: "\"Open Sans\", \"Arial\", \"Helvetica\", sans-serif",
                    },
                    {
                        name:    "body_font",
                        message: "Body Font:",
                        type:    "input",
                        default: "\"Open Sans\", \"Arial\", \"Helvetica\", sans-serif",
                    },
                    {
                        name:     "site_width",
                        message:  "Site Width:",
                        type:     "input",
                        default:  "1500",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                    {
                        name:     "column_gap",
                        message:  "Column Gap:",
                        type:     "input",
                        default:  "30",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                    {
                        name:     "content_padding",
                        message:  "Content Padding:",
                        type:     "input",
                        default:  "25",
                        validate: (response) => {
                            if (response.match(/[0-9]+/)) {
                                return true;
                            } else {
                                return "Please enter a valid positive integer.";
                            }
                        },
                    },
                ], (res) => {
                    // store the project data
                    project_data = res;
                })).on("end", () => {
                    // return the callback
                    if (typeof callback === "function") {
                        return callback();
                    }
                });
        };

        // write project data
        const write_project_data = (callback) => {
            return gulp.src(["./*", "./gulp-tasks/*", "./src/**/*"], {base: "./"})
                // prevent breaking on error
                .pipe(plugins.plumber({errorHandler: on_error}))
                // check if a file is a binary
                .pipe(plugins.is_binary())
                // skip file if it's a binary
                .pipe(plugins.through.obj((file, enc, next) => {
                    if (file.isBinary()) {
                        next();
                        return;
                    }

                    // go to next file
                    next(null, file);
                }))
                // replace variables with project data
                .pipe(plugins.file_include({
                    prefix:   "__gulp_init__",
                    basepath: "@file",
                    context: {
                        full_name:       project_data.full_name,
                        short_name:      project_data.short_name,
                        npm_name:        project_data.full_name.toLowerCase().replace(/[^A-Za-z ]/, "").replace(/ /g, "-"),
                        namespace:       project_data.short_name.toLowerCase().replace(/[^A-Za-z ]/, "").replace(/ /g, "_"),
                        version:         project_data.version,
                        description:     project_data.description,
                        homepage_url:    project_data.homepage,
                        repository:      project_data.repository.replace(/(\.git$)|(\/$)/, ""),
                        author_name:     project_data.author_name,
                        author_email:    project_data.author_email,
                        author_company:  project_data.author_company,
                        author_url:      project_data.author_url,
                        theme_color:     project_data.theme_color,
                        heading_font:    project_data.heading_font,
                        body_font:       project_data.body_font,
                        site_width:      project_data.site_width,
                        column_gap:      project_data.column_gap,
                        content_padding: project_data.content_padding,
                    }
                }))
                // write the file
                .pipe(gulp.dest("./")).on("end", () => {
                    // return the callback
                    if (typeof callback === "function") {
                        return callback();
                    }
                });
        };

        // remove modules selected during init
        const remove_selected_modules = (callback) => {
            return new Promise ((resolve) => {
                gulp.src(global.settings.paths.src + "/**/*")
                    // check if a file is a binary
                    .pipe(plugins.is_binary())
                    // skip file if it's a binary
                    .pipe(plugins.through.obj((file, enc, next) => {
                        if (file.isBinary()) {
                            next();
                            return;
                        }

                        // go to next file
                        next(null, file);
                    }))

                    // remove resource code if selected
                    .pipe(plugins.remove_code({resources_html: project_data.remove_modules.indexOf("Resources") > -1 ? true : false, commentStart: "<!--", commentEnd: "-->"}))
                    .pipe(plugins.remove_code({resources_css_js_php: project_data.remove_modules.indexOf("Resources") > -1 ? true : false, commentStart: "/*", commentEnd: "*/"}))

                    // remove tribe code if selected
                    .pipe(plugins.remove_code({tribe_html: project_data.remove_modules.indexOf("Tribe Events") > -1 ? true : false, commentStart: "<!--", commentEnd: "-->"}))
                    .pipe(plugins.remove_code({tribe_css_js_php: project_data.remove_modules.indexOf("Tribe Events") > -1 ? true : false, commentStart: "/*", commentEnd: "*/"}))

                    // output to source directory
                    .pipe(gulp.dest(global.settings.paths.src)).on("end", () => {
                        // resolve the promise
                        resolve();
                    });
            }).then(() => {
                return new Promise ((resolve) => {
                    // remove any empty files
                    plugins.glob(global.settings.paths.src + "/**/*", (err, files) => {
                        files.forEach((file) => {
                            if (plugins.fs.statSync(file).size <= 1) {
                                plugins.fs.unlinkSync(file);
                                console.log("\x1b[32m✔\x1b[0m deleted: " + plugins.path.relative(process.cwd(), file));
                            }
                        });

                        // resolve the promise
                        resolve();
                    });
                }).then(() => {
                    // remove any empty folders
                    return new Promise ((resolve) => {
                        plugins.delete_empty(global.settings.paths.src, () => {
                            // resolve the promise
                            resolve();
                        });
                    }).then(() => {
                        // remove any remaining comments
                        gulp.src(global.settings.paths.src + "/**/*")
                            // check if a file is a binary
                            .pipe(plugins.is_binary())
                            // skip file if it's a binary
                            .pipe(plugins.through.obj((file, enc, next) => {
                                if (file.isBinary()) {
                                    next();
                                    return;
                                }

                                // go to next file
                                next(null, file);
                            }))
                            // for comments that are on their own line, remove the entire line, otherwise just delete the comment
                            .pipe(plugins.replace(/(^((?:\/\*|<!--)(?:end)?[rR]emoveIf\([^)]+\)(?:\*\/|-->))\n$)|(((?:\/\*|<!--)(?:end)?[rR]emoveIf\([^)]+\)(?:\*\/|-->)))/gm, ""))
                            .pipe(gulp.dest(global.settings.paths.src))
                            .on("end", () => {
                                // return the callback
                                if (typeof callback === "function") {
                                    return callback();
                                }
                            });
                    });
                });
            });
        };

        return new Promise ((resolve) => {
            get_project_data(() => {
                write_project_data(() => {
                    remove_selected_modules(() => {
                        return resolve();
                    });
                });
            });
        });
    }
};
<|endoftext|>


<commit_before>//zmiana w fork

console.log('1');
<commit_msg># Conflicts: #	static.js<commit_after><<<<<<< .mine
//zmiana w fork

console.log('1');

=======
// zmiana w fork

/* zmiany w v2  */
>>>>>>> .theirs
<|endoftext|>


<commit_before>google.load('visualization', '1', {'packages':['corechart']});

google.setOnLoadCallback(drawChart);
function drawChart() {
    var data = new google.visualization.DataTable(chartData);

    var options = {
        legend: 'none',
        colors: ['#ea0649'],
        enableInteractivity: true,
        width: '100%',
        pointSize: 10,
        pointShape: {
            type: 'circle'
        },
        vAxis: {
            format: '#,### '+measure
        }
    };

    var formatter = new google.visualization.NumberFormat(
         {negativeColor: 'red', negativeParens: true, pattern: '###,### '+measure});
        formatter.format(data, 1);

    var chart = new google.visualization.LineChart(document.getElementById('chart-measurement'));
    chart.draw(data, options);
}

jQuery(window).resize(function(){
    drawChart();
});<commit_msg>Re-design: Data visualized<commit_after>google.load('visualization', '1', {'packages':['corechart']});

google.setOnLoadCallback(drawChart);
function drawChart() {
    var data = new google.visualization.DataTable(chartData);

    var options = {
        legend: 'none',
        colors: ['#2cbc24'],
        enableInteractivity: true,
        width: '100%',
        pointSize: 10,
        pointShape: {
            type: 'circle'
        },
        vAxis: {
            format: '#,### '+measure
        }
    };

    var formatter = new google.visualization.NumberFormat(
         {negativeColor: 'red', negativeParens: true, pattern: '###,### '+measure});
        formatter.format(data, 1);

    var chart = new google.visualization.LineChart(document.getElementById('chart-measurement'));
    chart.draw(data, options);
}

jQuery(window).resize(function(){
    drawChart();
});<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

module.exports = function(config) {
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			// '../test/helper/Test.js',
			'test/karmaTest.js',
			{pattern: 'test/*/*.js', included: false},
			{pattern: 'examples/*.html', included: false},
			{pattern: 'examples/scripts/*.js', included: false},
			{pattern: 'examples/style/*.css', included: false},
			{pattern: 'examples/audio/*/*.mp3', included: false},
			{pattern: 'examples/audio/*.mp3', included: false},
			{pattern: 'examples/audio/*/*.png', included: false},
			{pattern: 'build/*.js', included: false},
			{pattern: 'test/audio/*', included: false},
			{pattern: 'Tone/*/*.js', included: false},
			],

		// list of files to exclude
		exclude: [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'Tone/!(shim)/*.js': ['coverage']
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['dots', 'coverage'],

		coverageReporter: {
			type : 'lcov',
			dir : 'test/coverage/'
		},

		//plugins
		plugins : [
		'karma-coverage',
		'karma-mocha',
		'karma-requirejs',
		'karma-chrome-launcher',
		'karma-firefox-launcher'
		],

		client: {
			mocha: {
				reporter: 'html', // change Karma's debug.html to the mocha web reporter
				ui: 'bdd'
			}
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 20000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: ['HeadlessFirefox', 'HeadlessChrome'],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: Infinity,

		//custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: 'ChromeHeadless',
				flags: [/*'--disable-translate', '--disable-extensions', '--remote-debugging-port=9223', */'--no-sandbox', '--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream']
			},
			HeadlessFirefox: {
		        base: 'Firefox',
				flags: [ '-headless' ],
		        prefs: {
		            'media.navigator.permission.disabled': true
		        }
		    }
		}
	};

	config.set(configuration);
};
<commit_msg>limiting concurrency to avoid timeouts<commit_after>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

module.exports = function(config) {
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			// '../test/helper/Test.js',
			'test/karmaTest.js',
			{pattern: 'test/*/*.js', included: false},
			{pattern: 'examples/*.html', included: false},
			{pattern: 'examples/scripts/*.js', included: false},
			{pattern: 'examples/style/*.css', included: false},
			{pattern: 'examples/audio/*/*.mp3', included: false},
			{pattern: 'examples/audio/*.mp3', included: false},
			{pattern: 'examples/audio/*/*.png', included: false},
			{pattern: 'build/*.js', included: false},
			{pattern: 'test/audio/*', included: false},
			{pattern: 'Tone/*/*.js', included: false},
			],

		// list of files to exclude
		exclude: [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'Tone/!(shim)/*.js': ['coverage']
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['dots', 'coverage'],

		coverageReporter: {
			type : 'lcov',
			dir : 'test/coverage/'
		},

		//plugins
		plugins : [
		'karma-coverage',
		'karma-mocha',
		'karma-requirejs',
		'karma-chrome-launcher',
		'karma-firefox-launcher'
		],

		client: {
			mocha: {
				reporter: 'html', // change Karma's debug.html to the mocha web reporter
				ui: 'bdd'
			}
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 20000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: ['HeadlessFirefox', 'HeadlessChrome'],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 1,

		//custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: 'ChromeHeadless',
				flags: [/*'--disable-translate', '--disable-extensions', '--remote-debugging-port=9223', */'--no-sandbox', '--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream']
			},
			HeadlessFirefox: {
		        base: 'Firefox',
				flags: [ '-headless' ],
		        prefs: {
		            'media.navigator.permission.disabled': true
		        }
		    }
		}
	};

	config.set(configuration);
};
<|endoftext|>


<commit_before><commit_msg>replace quibble.browser.js with ES5 version<commit_after><|endoftext|>


<commit_before>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * 14/07/2015.
 */

var pullRequestsURL = '/rest/inbox/latest/pull-requests?role=reviewer&start=0&limit=10&avatarSize=64&state=OPEN&order=oldest';
var myPullRequestsURL = '/rest/inbox/latest/pull-requests?role=author&start=0&limit=10&avatarSize=64&state=OPEN&order=oldest';
var whoAmI = '/plugins/servlet/applinks/whoami';

function host(uri) {
    var splitRegExp = /\/(\b|$)/g;
    if (!uri) return localStorage["_server"];
    return (_.compact(host().split(splitRegExp).concat(uri.split(splitRegExp)))).join('/');
}

var _listeners = {};

function me() {
    if (localStorage["_username"].length) {
        return localStorage["_username"];
    } else {
        return najax(host(whoAmI))
            .then(function (data) {
                localStorage["_username"] = data;
                return data;
            });
    }
}

function filterResult(data) {
    data = JSON.parse(data);

    // Open tasks:
    if (localStorage["_hide_pr_with_tasks"] == "true") {
        data.values = _.filter(data.values, function (pr) {
            return !(
                pr['attributes']['openTaskCount']
                && (pr['attributes']['openTaskCount'] != "0")
            );
        });
    }

    // Scrum master:
    if (localStorage["_scrum_master"] == "true"
        && me()
    ) {
        data.values = _.filter(data.values, function (pr) {
            // If I'm the only reviewer, display:
            if (pr["reviewers"].length == 1) return true;
            // Else, if at least one other had reviewed:
            return _.some(pr["reviewers"], function (rev) {
                return (
                    rev['approved'] == true
                    && rev['user']['name'] != me()
                );
            });
        });
    }
    data.size = data.values.length;
    //return data;
    return data;
}

function getPullRequestData() {

    // TODO: Improve
    var uri = host(pullRequestsURL);

    return najax(uri)
        .then(filterResult)
        .then(function (res) {
            if (res.size == 0) clearBadge();
            else setBadge(res.size, null, "#ff0000");
            localStorage.prData = JSON.stringify(res);
            return res;
        })
        .catch(errHandle);
}

function getMyRequestsData() {

    var uri = host(myPullRequestsURL);

    return najax(uri)
        .then(filterResult)
        .then(function (res) {
            localStorage.prDataMine = JSON.stringify(res);
            return res;
        })
        .catch(errHandle);
}

var notifyPullRequests = _.throttle(function (PRData) {
    if (localStorage["_notifyPRs"] == "true" && !(localStorage['snooze_all'] > Date.now())) {
        PRData.values.forEach(notifyPullRequest);
    }
    return Promise.resolve();
}, localStorage["_notifyInterval"], {});

function notifyPullRequest(pr) {

    var prID = pr.links.self[0].href;

    // Quit if snoozed:
    if (localStorage['snooze.' + prID] > Date.now()) return;

    // Don't show if no repeat:
    if (localStorage["_repeatUntilNoticed"] == "once"
        && localStorage["notif." + prID])
        return;

    // Don't show if clicked:
    if (localStorage["_repeatUntilNoticed"] == "click"
        && localStorage["click." + prID])
        return;

    // Prepare buttons:
    var buttons = [];
    if (!(localStorage["_snooze_this_btn"] == 'true')) {
        buttons.push({title: "Snooze this Pull Request", iconUrl: "/assets/snooze.svg"});
    }
    if (!(localStorage["_snooze_all_btn"] == 'true')) {
        buttons.push({title: "Snooze all", iconUrl: "/assets/zzz.svg"});
    }

    chrome.notifications.clear(prID, null);
    chrome.notifications.create(prID, {
        type: "basic",
        message: pr.title,
        title: pr['author']['user']['displayName'],
        iconUrl: host(pr['author']['user']['avatarUrl'].split("?")[0]),
        buttons: buttons
    }, function () {
        // Mark as shown:
        localStorage["notif." + prID] = 1;
        if (!(_listeners[prID] == 'true')) {
            _listeners[prID] = true;
            chrome.notifications.onClicked.addListener(function (prID) {
                window.open(prID);
                localStorage["click." + prID] = 1;
            });

            chrome.notifications.onButtonClicked.addListener(function (prID, buttonIndex) {
                    switch (buttonIndex) {
                        case 0: // Snooze THIS!
                            localStorage['snooze.' + prID] = Date.now() + Number(localStorage["_snooze_duration"].replace(/"/g, ''));
                            break;
                        case 1: // Snooze ALL!
                            localStorage['snooze_all'] = Date.now() + Number(localStorage["_snooze_duration"].replace(/"/g, ''));
                            break;
                    }
                }
            );
        }
    });
}<commit_msg>Added function to get tasks of a pull request<commit_after>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * 14/07/2015.
 */

var pullRequestsURL = '/rest/inbox/latest/pull-requests?role=reviewer&start=0&limit=10&avatarSize=64&state=OPEN&order=oldest';
var myPullRequestsURL = '/rest/inbox/latest/pull-requests?role=author&start=0&limit=10&avatarSize=64&state=OPEN&order=oldest';
var whoAmI = '/plugins/servlet/applinks/whoami';

function host(uri) {
    var splitRegExp = /\/(\b|$)/g;
    if (!uri) return localStorage["_server"];
    return (_.compact(host().split(splitRegExp).concat(uri.split(splitRegExp)))).join('/');
}

var _listeners = {};

function me() {
    if (localStorage["_username"].length) {
        return localStorage["_username"];
    } else {
        return najax(host(whoAmI))
            .then(function (data) {
                localStorage["_username"] = data;
                return data;
            });
    }
}

function getTasks(pr) {
    var uri = host("/rest/api/latest" + pr["link"]["url"] + "/tasks?start=0&limit=5");
    var idx = 0;
    return najax(uri)
        .then(function (data) {
            return JSON.parse(data).values.map(function (task) {
                return ++idx + ". " + task.anchor.text.split(/\n/)[0];
            }).join('\n');
        });
}

function filterResult(data) {
    data = JSON.parse(data);

    // Open tasks:
    if (localStorage["_hide_pr_with_tasks"] == "true") {
        data.values = _.filter(data.values, function (pr) {
            return !(
                pr['attributes']['openTaskCount']
                && (pr['attributes']['openTaskCount'] != "0")
            );
        });
    }

    // Scrum master:
    if (localStorage["_scrum_master"] == "true"
        && me()
    ) {
        data.values = _.filter(data.values, function (pr) {
            // If I'm the only reviewer, display:
            if (pr["reviewers"].length == 1) return true;
            // Else, if at least one other had reviewed:
            return _.some(pr["reviewers"], function (rev) {
                return (
                    rev['approved'] == true
                    && rev['user']['name'] != me()
                );
            });
        });
    }
    data.size = data.values.length;
    //return data;
    return data;
}

function getPullRequestData() {

    // TODO: Improve
    var uri = host(pullRequestsURL);

    return najax(uri)
        .then(filterResult)
        .then(function (res) {
            if (res.size == 0) clearBadge();
            else setBadge(res.size, null, "#ff0000");
            localStorage.prData = JSON.stringify(res);
            return res;
        })
        .catch(errHandle);
}

function getMyRequestsData() {

    var uri = host(myPullRequestsURL);

    return najax(uri)
        .then(filterResult)
        .then(function (res) {
            localStorage.prDataMine = JSON.stringify(res);
            return res;
        })
        .catch(errHandle);
}

var notifyPullRequests = _.throttle(function (PRData) {
    if (localStorage["_notifyPRs"] == "true" && !(localStorage['snooze_all'] > Date.now())) {
        PRData.values.forEach(notifyPullRequest);
    }
    return Promise.resolve();
}, localStorage["_notifyInterval"], {});

function notifyPullRequest(pr) {

    var prID = pr.links.self[0].href;

    // Quit if snoozed:
    if (localStorage['snooze.' + prID] > Date.now()) return;

    // Don't show if no repeat:
    if (localStorage["_repeatUntilNoticed"] == "once"
        && localStorage["notif." + prID])
        return;

    // Don't show if clicked:
    if (localStorage["_repeatUntilNoticed"] == "click"
        && localStorage["click." + prID])
        return;

    // Prepare buttons:
    var buttons = [];
    if (!(localStorage["_snooze_this_btn"] == 'true')) {
        buttons.push({title: "Snooze this Pull Request", iconUrl: "/assets/snooze.svg"});
    }
    if (!(localStorage["_snooze_all_btn"] == 'true')) {
        buttons.push({title: "Snooze all", iconUrl: "/assets/zzz.svg"});
    }

    chrome.notifications.clear(prID, null);
    chrome.notifications.create(prID, {
        type: "basic",
        message: pr.title,
        title: pr['author']['user']['displayName'],
        iconUrl: host(pr['author']['user']['avatarUrl'].split("?")[0]),
        buttons: buttons
    }, function () {
        // Mark as shown:
        localStorage["notif." + prID] = 1;
        if (!(_listeners[prID] == 'true')) {
            _listeners[prID] = true;
            chrome.notifications.onClicked.addListener(function (prID) {
                window.open(prID);
                localStorage["click." + prID] = 1;
            });

            chrome.notifications.onButtonClicked.addListener(function (prID, buttonIndex) {
                    switch (buttonIndex) {
                        case 0: // Snooze THIS!
                            localStorage['snooze.' + prID] = Date.now() + Number(localStorage["_snooze_duration"].replace(/"/g, ''));
                            break;
                        case 1: // Snooze ALL!
                            localStorage['snooze_all'] = Date.now() + Number(localStorage["_snooze_duration"].replace(/"/g, ''));
                            break;
                    }
                }
            );
        }
    });
}<|endoftext|>