<commit_before>import classNames from 'classnames';
import {Link} from 'react-router';
import mixin from 'reactjs-mixin';
/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import {StoreMixin} from 'mesosphere-shared-reactjs';
import {Table} from 'reactjs-components';

import FilterBar from '../../../components/FilterBar';
import FilterHeadline from '../../../components/FilterHeadline';
import FilterInputText from '../../../components/FilterInputText';
import Icon from '../../../components/Icon';
import MesosStateStore from '../../../stores/MesosStateStore';
import Overlay from '../../../structs/Overlay';
import RequestErrorMsg from '../../../components/RequestErrorMsg';
import TaskUtil from '../../../utils/TaskUtil';
import VirtualNetworkUtil from '../../../utils/VirtualNetworkUtil';
import Util from '../../../utils/Util';

const headerMapping = {
  id: 'TASK',
  ip_address: 'AGENT IP',
  port_mappings: 'PORT MAPPINGS'
};
const METHODS_TO_BIND = [
  'handleSearchStringChange',
  'renderID',
  'renderPorts',
  'resetFilter'
];

const agentIPPath = 'statuses.0.container_status.network_infos.0.ip_addresses.0.ip_address';

class VirtualNetworkTaskTab extends mixin(StoreMixin) {
  constructor() {
    super(...arguments);

    this.state = {
      errorMessage: null,
      tasksDataReceived: false
    };

    this.store_listeners = [{
      name: 'state',
      events: ['success', 'error']
    }];

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  onStateStoreError(errorMessage) {
    this.setState({tasksDataReceived: true, errorMessage});
  }

  onStateStoreSuccess() {
    this.setState({tasksDataReceived: true, errorMessage: null});
  }

  handleSearchStringChange(searchString) {
    this.setState({searchString});
  }

  resetFilter() {
    this.setState({searchString: ''});
  }

  isLoading() {
    return !this.state.tasksDataReceived;
  }

  getFilteredTasks(tasks, searchString = '') {
    if (searchString === '') {
      return tasks;
    }

    return tasks.filter(function (task) {
      return task.name.includes(searchString) ||
        task.id.includes(searchString);
    });
  }

  getClassName(prop, sortBy) {
    return classNames({
      'highlight': prop === sortBy.prop
    });
  }

  getColumns() {
    let getClassName = this.getClassName;
    let heading = this.renderHeading;

    return [
      {
        className: getClassName,
        headerClassName: getClassName,
        heading,
        prop: 'id',
        render: this.renderID,
        sortable: false
      },
      {
        className: getClassName,
        getValue: function (task) {
          return Util.findNestedPropertyInObject(task, agentIPPath);
        },
        headerClassName: getClassName,
        heading,
        prop: 'ip_address',
        render: this.renderAgentIP,
        sortable: false
      },
      {
        className: getClassName,
        getValue: TaskUtil.getPortMappings,
        headerClassName: getClassName,
        heading,
        prop: 'port_mappings',
        render: this.renderPorts,
        sortable: false
      }
    ];
  }

  getColGroup() {
    return (
      <colgroup>
        <col style={{width: '50%'}} />
        <col />
        <col />
      </colgroup>
    );
  }

  getErrorScreen() {
    return <RequestErrorMsg />;
  }

  getLoadingScreen() {
    return (

    );
  }

  getTaskLink(taskID, value, title) {
    if (!value) {
      value = taskID;
    }

    if (!title) {
      title = taskID;
    }

    return (
      <Link
        className="clickable"
        params={{overlayName: this.props.overlay.getName(), taskID}}
        title={title}
        to="virtual-networks-tab-detail-tasks-detail">
        {value}
      </Link>
    );
  }

  getTitle(portMappings) {
    return portMappings.map(function (mapping) {
      return `${mapping.container_port} > ${mapping.host_port} (${mapping.protocol})`
    }).join(', ')
  }

  renderAgentIP(prop, task) {
    let ipAddress = Util.findNestedPropertyInObject(task, agentIPPath);

    if (!ipAddress) {
      return 'N/A';
    }

    return ipAddress;
  }

  renderHeading(prop) {
    return (
      {headerMapping[prop]}
    );
  }

  renderID(prop, task) {
    return this.getTaskLink(task.id);
  }

  renderPorts(prop, task) {
    let portMappings = TaskUtil.getPortMappings(task);
    if (!portMappings) {
      return 'N/A';
    }

    let title = this.getTitle(portMappings);
    if (portMappings.length > 3) {
      portMappings = portMappings.slice(0, 2);
      portMappings.push({container_port: '...'});
    }

    let {id} = task;
    return portMappings.map((mapping, index) => {
      let mapTo = [];

      if (mapping.host_port) {
        mapTo.push(
          <Icon
            className="list-inline-separator"
            family="tiny"
            id="caret-right"
            size="tiny" />
        );
        mapTo.push(this.getTaskLink(
          id,
          `${mapping.host_port} (${mapping.protocol})`,
          title
        ));
      }

      return (

              {this.getTaskLink(id, mapping.container_port, title)}
              {mapTo}

      );
    });
  }

  render() {
    let {errorMessage, searchString} = this.state;
    if (this.isLoading()) {
      return this.getLoadingScreen();
    }

    if (errorMessage) {
      return this.getErrorScreen();
    }

    let {overlay} = this.props;
    if (!overlay) {
      return VirtualNetworkUtil.getEmptyNetworkScreen();
    }

    let tasks = MesosStateStore.getTasksFromVirtualNetworkName(
      overlay.getName()
    );
    let filteredTasks = this.getFilteredTasks(tasks, searchString);

    return (

        <FilterHeadline
          inverseStyle={true}
          onReset={this.resetFilter}
          name="Task"
          currentLength={filteredTasks.length}
          totalLength={tasks.length} />
        <FilterBar>
          <FilterInputText
            searchString={searchString}
            handleFilterChange={this.handleSearchStringChange}
            inverseStyle={true} />
        </FilterBar>

    );
  }
}

VirtualNetworkTaskTab.contextTypes = {
  router: React.PropTypes.func
};

VirtualNetworkTaskTab.propTypes = {
  overlay: React.PropTypes.instanceOf(Overlay)
}

module.exports = VirtualNetworkTaskTab;
<commit_msg>Join ip addresses if there are multiple<commit_after>import classNames from 'classnames';
import {Link} from 'react-router';
import mixin from 'reactjs-mixin';
/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import {StoreMixin} from 'mesosphere-shared-reactjs';
import {Table} from 'reactjs-components';

import FilterBar from '../../../components/FilterBar';
import FilterHeadline from '../../../components/FilterHeadline';
import FilterInputText from '../../../components/FilterInputText';
import Icon from '../../../components/Icon';
import MesosStateStore from '../../../stores/MesosStateStore';
import Overlay from '../../../structs/Overlay';
import RequestErrorMsg from '../../../components/RequestErrorMsg';
import TaskUtil from '../../../utils/TaskUtil';
import VirtualNetworkUtil from '../../../utils/VirtualNetworkUtil';
import Util from '../../../utils/Util';

const headerMapping = {
  id: 'TASK',
  ip_address: 'AGENT IP',
  port_mappings: 'PORT MAPPINGS'
};
const METHODS_TO_BIND = [
  'handleSearchStringChange',
  'renderAgentIP',
  'renderID',
  'renderPorts',
  'resetFilter'
];

const agentIPPath = 'statuses.0.container_status.network_infos.0.ip_addresses';

class VirtualNetworkTaskTab extends mixin(StoreMixin) {
  constructor() {
    super(...arguments);

    this.state = {
      errorMessage: null,
      tasksDataReceived: false
    };

    this.store_listeners = [{
      name: 'state',
      events: ['success', 'error']
    }];

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  onStateStoreError(errorMessage) {
    this.setState({tasksDataReceived: true, errorMessage});
  }

  onStateStoreSuccess() {
    this.setState({tasksDataReceived: true, errorMessage: null});
  }

  handleSearchStringChange(searchString) {
    this.setState({searchString});
  }

  resetFilter() {
    this.setState({searchString: ''});
  }

  isLoading() {
    return !this.state.tasksDataReceived;
  }

  getFilteredTasks(tasks, searchString = '') {
    if (searchString === '') {
      return tasks;
    }

    return tasks.filter(function (task) {
      return task.name.includes(searchString) ||
        task.id.includes(searchString);
    });
  }

  getClassName(prop, sortBy) {
    return classNames({
      'highlight': prop === sortBy.prop
    });
  }

  getColumns() {
    let getClassName = this.getClassName;
    let heading = this.renderHeading;

    return [
      {
        className: getClassName,
        headerClassName: getClassName,
        heading,
        prop: 'id',
        render: this.renderID,
        sortable: false
      },
      {
        className: getClassName,
        getValue: this.getAgentIP,
        headerClassName: getClassName,
        heading,
        prop: 'ip_address',
        render: this.renderAgentIP,
        sortable: false
      },
      {
        className: getClassName,
        getValue: TaskUtil.getPortMappings,
        headerClassName: getClassName,
        heading,
        prop: 'port_mappings',
        render: this.renderPorts,
        sortable: false
      }
    ];
  }

  getColGroup() {
    return (
      <colgroup>
        <col style={{width: '50%'}} />
        <col />
        <col />
      </colgroup>
    );
  }

  getErrorScreen() {
    return <RequestErrorMsg />;
  }

  getLoadingScreen() {
    return (

    );
  }

  getTaskLink(taskID, value, title) {
    if (!value) {
      value = taskID;
    }

    if (!title) {
      title = taskID;
    }

    return (
      <Link
        className="clickable"
        params={{overlayName: this.props.overlay.getName(), taskID}}
        title={title}
        to="virtual-networks-tab-detail-tasks-detail">
        {value}
      </Link>
    );
  }

  getTitle(portMappings) {
    return portMappings.map(function (mapping) {
      return `${mapping.container_port} > ${mapping.host_port} (${mapping.protocol})`
    }).join(', ')
  }

  getAgentIP(task) {
    let ipAddresses = Util.findNestedPropertyInObject(task, agentIPPath);

    if (!ipAddresses || !Array.isArray(ipAddresses)) {
      return ipAddresses;
    }

    return ipAddresses.map(function (ipAddress) {
      return ipAddress.ip_address;
    }).join(', ');
  }

  renderAgentIP(prop, task) {
    let ipAddress = this.getAgentIP(task);

    if (!ipAddress) {
      return 'N/A';
    }

    return ipAddress;
  }

  renderHeading(prop) {
    return (
      {headerMapping[prop]}
    );
  }

  renderID(prop, task) {
    return this.getTaskLink(task.id);
  }

  renderPorts(prop, task) {
    let portMappings = TaskUtil.getPortMappings(task);
    if (!portMappings) {
      return 'N/A';
    }

    let title = this.getTitle(portMappings);
    if (portMappings.length > 3) {
      portMappings = portMappings.slice(0, 2);
      portMappings.push({container_port: '...'});
    }

    let {id} = task;
    return portMappings.map((mapping, index) => {
      let mapTo = [];

      if (mapping.host_port) {
        mapTo.push(
          <Icon
            className="list-inline-separator"
            family="tiny"
            id="caret-right"
            size="tiny" />
        );
        mapTo.push(this.getTaskLink(
          id,
          `${mapping.host_port} (${mapping.protocol})`,
          title
        ));
      }

      return (

              {this.getTaskLink(id, mapping.container_port, title)}
              {mapTo}

      );
    });
  }

  render() {
    let {errorMessage, searchString} = this.state;
    if (this.isLoading()) {
      return this.getLoadingScreen();
    }

    if (errorMessage) {
      return this.getErrorScreen();
    }

    let {overlay} = this.props;
    if (!overlay) {
      return VirtualNetworkUtil.getEmptyNetworkScreen();
    }

    let tasks = MesosStateStore.getTasksFromVirtualNetworkName(
      overlay.getName()
    );
    let filteredTasks = this.getFilteredTasks(tasks, searchString);

    return (

        <FilterHeadline
          inverseStyle={true}
          onReset={this.resetFilter}
          name="Task"
          currentLength={filteredTasks.length}
          totalLength={tasks.length} />
        <FilterBar>
          <FilterInputText
            searchString={searchString}
            handleFilterChange={this.handleSearchStringChange}
            inverseStyle={true} />
        </FilterBar>

    );
  }
}

VirtualNetworkTaskTab.contextTypes = {
  router: React.PropTypes.func
};

VirtualNetworkTaskTab.propTypes = {
  overlay: React.PropTypes.instanceOf(Overlay)
}

module.exports = VirtualNetworkTaskTab;
<|endoftext|>


<commit_before>/*jshint node:true */

"use strict";

var path = require('path');

module.exports = {
    // Whether or not to automatically throttle and blacklist abusive requests.
    // This works best if `upstreamRequestLog` is also set.
    autoThrottle: true,

    // Whitelist of file extensions that will be proxied through rawgit.com. All
    // others will be redirected to raw.githubusercontent.com.
    //
    // Requests to cdn.rawgit.com bypass this whitelist and proxy all file
    // types.
    extensionWhitelist: {
        '.coffee': true,
        '.css'   : true,
        '.eot'   : true,
        '.htm'   : true,
        '.html'  : true,
        '.js'    : true,
        '.json'  : true,
        '.kml'   : true,
        '.otf'   : true,
        '.rss'   : true,
        '.svg'   : true,
        '.swf'   : true,
        '.ttc'   : true,
        '.ttf'   : true,
        '.woff'  : true,
        '.xml'   : true
    },

    // This multiplier is used to determine the naughtiness of a given request
    // based on internal stats about the requested file and the referrer.
    //
    // Naughtiness for files is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier
    //
    // Naughtiness for referrers is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier *
    //         referrerNaughtinessMultiplier
    //
    // Referrers get a little more leeway since they're often legitimately
    // requesting multiple files per page.
    //
    // The end result is that large files requested rarely are fine. Small files
    // requested frequently but not too often are fine. But large files
    // requested often and small files requested abusively often are not fine.
    //
    // This multiplier is calibrated such that a naughtiness score of >= 0.5
    // probably indicates requests should be throttled, and a score of >= 1.0
    // probably indicates requests should be blacklisted.
    naughtinessMultiplier: 0.0000002,

    // Public directory containing static files.
    publicDir: path.join(__dirname, '/../public'),

    // Additional multiplier to use when determining the naughtiness of a
    // referrer. This is used to give referrers more leeway than individual
    // files, since they're often legitimately requesting multiple files per
    // page.
    referrerNaughtinessMultiplier: 0.3,

    // Array of request header names that should be relayed from the user to
    // GitHub.
    relayRequestHeaders: [
        'If-Modified-Since',
        'If-None-Match',
        'User-Agent'
    ],

    // Array of request header names that should be relayed from GitHub to the
    // user.
    relayResponseHeaders: [
        'Content-Length',
        'Date',
        'ETag'
    ],

    // If rawgit is fronted by Nginx, Apache, or something else that generates
    // logs in Common/Combined Log Format, set the path to that file here to
    // have rawgit tail the log and use it for accurate request statistics.
    //
    // If this is not set or if the file doesn't exist or isn't readable, rawgit
    // will track requests internally (but this may result in inaccurate stats
    // if you're fronting rawgit with a caching proxy).
    upstreamRequestLog: '/data/logs/rawgit.com-access.log',

    // Number of historical log entries to parse from the upstream request log
    // on startup. This is useful in order to retain recent stats after the
    // rawgit process is restarted.
    upstreamRequestLogScrollback: 100000
};
<commit_msg>Turns out relaying Content-Length wasn't such a great idea.<commit_after>/*jshint node:true */

"use strict";

var path = require('path');

module.exports = {
    // Whether or not to automatically throttle and blacklist abusive requests.
    // This works best if `upstreamRequestLog` is also set.
    autoThrottle: true,

    // Whitelist of file extensions that will be proxied through rawgit.com. All
    // others will be redirected to raw.githubusercontent.com.
    //
    // Requests to cdn.rawgit.com bypass this whitelist and proxy all file
    // types.
    extensionWhitelist: {
        '.coffee': true,
        '.css'   : true,
        '.eot'   : true,
        '.htm'   : true,
        '.html'  : true,
        '.js'    : true,
        '.json'  : true,
        '.kml'   : true,
        '.otf'   : true,
        '.rss'   : true,
        '.svg'   : true,
        '.swf'   : true,
        '.ttc'   : true,
        '.ttf'   : true,
        '.woff'  : true,
        '.xml'   : true
    },

    // This multiplier is used to determine the naughtiness of a given request
    // based on internal stats about the requested file and the referrer.
    //
    // Naughtiness for files is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier
    //
    // Naughtiness for referrers is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier *
    //         referrerNaughtinessMultiplier
    //
    // Referrers get a little more leeway since they're often legitimately
    // requesting multiple files per page.
    //
    // The end result is that large files requested rarely are fine. Small files
    // requested frequently but not too often are fine. But large files
    // requested often and small files requested abusively often are not fine.
    //
    // This multiplier is calibrated such that a naughtiness score of >= 0.5
    // probably indicates requests should be throttled, and a score of >= 1.0
    // probably indicates requests should be blacklisted.
    naughtinessMultiplier: 0.0000002,

    // Public directory containing static files.
    publicDir: path.join(__dirname, '/../public'),

    // Additional multiplier to use when determining the naughtiness of a
    // referrer. This is used to give referrers more leeway than individual
    // files, since they're often legitimately requesting multiple files per
    // page.
    referrerNaughtinessMultiplier: 0.3,

    // Array of request header names that should be relayed from the user to
    // GitHub.
    relayRequestHeaders: [
        'If-Modified-Since',
        'If-None-Match',
        'User-Agent'
    ],

    // Array of request header names that should be relayed from GitHub to the
    // user.
    relayResponseHeaders: [
        'Date',
        'ETag'
    ],

    // If rawgit is fronted by Nginx, Apache, or something else that generates
    // logs in Common/Combined Log Format, set the path to that file here to
    // have rawgit tail the log and use it for accurate request statistics.
    //
    // If this is not set or if the file doesn't exist or isn't readable, rawgit
    // will track requests internally (but this may result in inaccurate stats
    // if you're fronting rawgit with a caching proxy).
    upstreamRequestLog: '/data/logs/rawgit.com-access.log',

    // Number of historical log entries to parse from the upstream request log
    // on startup. This is useful in order to retain recent stats after the
    // rawgit process is restarted.
    upstreamRequestLogScrollback: 100000
};
<|endoftext|>


<commit_before>/**
* This validation program specifically checks that the generated HTML is identical in content
* to the original USX file.  To do this it reads the HTML data from the generated database,
* parses it, and generates USX files
*/
var fs = require("fs");
//var os = require("os");
var HTML_BIBLE_PATH = "../../DBL/3prepared/";
var OUT_BIBLE_PATH = "output/html/";
var USX_BIBLE_PATH = "../../DBL/2current/";
var EOL = '\r\n';

function HTMLValidator(version) {
	this.version = version;
	this.versionPath = HTML_BIBLE_PATH + version + '.db';
	this.parser = new HTMLParser();
	this.db = null;
}
HTMLValidator.prototype.open = function(callback) {
	var that = this;
	var sqlite3 = require('sqlite3');
	this.db = new sqlite3.Database(this.versionPath, sqlite3.OPEN_READWRITE, function(err) {
		if (err) that.fatalError(err, 'openDatabase');
		that.db.on('trace', function(sql) { console.log('DO ', sql); });
		that.db.on('profile', function(sql, ms) { console.log(ms, 'DONE', sql); });
		callback();
	});
};
HTMLValidator.prototype.validateBook = function(index, books, callback) {
	var that = this;
	if (index >= books.length) {
		callback();
	} else {
		var chapters = [];
		console.log('doing ', books[index]);
		var book = books[index].code;
		this.db.all("SELECT html FROM chapters WHERE reference LIKE ?", book + '%', function(err, results) {
			if (err) that.fatalError(err, 'select html');
			for (var i=0; i<results.length; i++) {
				var node = that.parser.readBook(results[i].html);
				chapters.push(node);
			}
			var usx = convertHTML2USX(chapters);
			compareUSXFile(book, usx, function() {
				that.validateBook(index + 1, books, callback);
			});
		});
	}

	function convertHTML2USX(chapters) {
		var usx = [];
		usx.push(String.fromCharCode('0xFEFF'));
		usx.push('<?xml version="1.0" encoding="utf-8"?>', EOL);
		usx.push('<usx version="2.*">', EOL);
		for (var i=0; i<chapters.length; i++) {
			recurseOverHTML(usx, chapters[i]);
		}
		usx.push(EOL, '</usx>');
		return(usx.join(''));
	}

	function recurseOverHTML(usx, node) {
		convertOpenElement(usx, node);
		if (node.children) {
			for (var i=0; i<node.children.length; i++) {
				recurseOverHTML(usx, node.children[i]);
			}
		}
		convertCloseElement(usx, node);
	}

	function convertOpenElement(usx, node) {
		//console.log(node.tagName);
		switch(node.tagName) {
			case 'ROOT':
				// do nothing
				break;
			case 'article':
				usx.push(node.whiteSpace, '<book code="', node.id, '" style="', node['class'], '">');
				break;
			case 'section':
				var parts = node.id.split(':');
				node.whiteSpace = '\r\n  '; // Necessary hack. I think XMLTokenizer discards leading whitespace
				if (parts[1] !== '0') {
					usx.push(node.whiteSpace, '<chapter number="', parts[1], '" style="c" />');
				}
				//node.children = [];
				break;
			case 'p':
				if (node['class'] === 'c') {
					node.children = [];
				} else if (node.emptyElement) {
					usx.push(node.whiteSpace, '<para style="', node['class'], '" />');
				} else {
					usx.push(node.whiteSpace, '<para style="', node['class'], '">');
				}
				if (node.hidden) {
					usx.push(node.hidden);
				}
				break;
			case 'span':
				if (node['class'] === 'v') {
					var parts = node.id.split(':');
					usx.push(node.whiteSpace, '<verse number="', parts[2], '" style="', node['class'], '" />');
					node.children = [];
				} else if (node['class'] === 'topf') {
					usx.push(node.whiteSpace, '<note caller="+" style="f">');
					clearTextChildren(node); // clear note button
				} else if (node['class'] === 'topx') {
					usx.push(node.whiteSpace, '<note caller="+" style="x">');
					clearTextChildren(node); // clear note button
				} else if (node.hidden) {
					if (node.closed) {
						usx.push(node.whiteSpace, '<char style="', node['class'], '" closed="', node.closed, '">');
					} else {
						usx.push(node.whiteSpace, '<char style="', node['class'], '">');
					}
				} else if (node.note) {
					if (node['class'] !== 'f' && node['class'] !== 'x') {
						if (node.closed) {
							usx.push(node.whiteSpace, '<char style="', node['class'], '" closed="', node.closed, '">');
						} else {
							usx.push(node.whiteSpace, '<char style="', node['class'], '">');
						}
					}
					usx.push(node.note);
				} else {
					usx.push(node.whiteSpace, '<char style="', node['class'], '">');
				}
				break;
			case 'TEXT':
				usx.push(node.text);
				break;
			default:
				throw new Error('unexpected HTML element ' + node.tagName + '.');
		}
	}

	function clearTextChildren(node) {
		for (var i=0; i<node.children.length; i++) {
			var child = node.children[i];
			if (child.tagName === 'TEXT') {
				child.text = '';
			}
		}
	}

	function convertCloseElement(usx, node) {
		switch(node.tagName) {
			case 'ROOT':
			case 'section':
				break;
			case 'article':
				usx.push('</book>');
				break;
			case 'TEXT':
				// do nothing
				break;
			case 'p':
				if (node['class'] !== 'c' && ! node.emptyElement) {
					usx.push('</para>');
				}
				break;
			case 'span':
				if (node['class'] === 'v') {
					// do nothing
				} else if (node['class'] === 'topf' || node['class'] === 'topx') {
					usx.push('</note>');
				} else if (node.hidden) {
					usx.push(node.hidden, '</char>');
				} else if (node.note) {
					if (node['class'] !== 'f' && node['class'] !== 'x') {
						usx.push('</char>');
					}
				} else {
					usx.push('</char>');
				}
				break;
			default:
				throw new Error('unexpected HTML element ' + node.tagName + '.');

		}
	}

	function compareUSXFile(book, data, callback) {
		var inFile = USX_BIBLE_PATH + that.version + '/USX_1/' + book + '.usx';
		console.log('INFILE', inFile);
		var outFile = OUT_BIBLE_PATH + book + '.usx';
		console.log('OUTFILE', outFile);
		fs.writeFile(outFile, data, { encoding: 'utf8'}, function(err) {
			if (err) {
				//console.log('WRITE ERROR', JSON.stringify(err));
				//process.exit(1);
				that.fatalError(err, 'Write USX File');
			}
			console.log('COMPARE ', book);
			var proc = require('child_process');
			proc.exec('diff ' + inFile + ' ' + outFile, { encoding: 'utf8' }, function(err, stdout, stderr) {
				if (err) {
					console.log('Diff Error', JSON.stringify(err));
				}
				console.log('STDOUT', stdout);
				console.log('STDERR', stderr);
				callback();
			});
		});
	}
};
HTMLValidator.prototype.fatalError = function(err, source) {
	console.log('FATAL ERROR ', err, ' AT ', source);
	process.exit(1);
};
HTMLValidator.prototype.completed = function() {
	console.log('HTMLValidator COMPLETED');
	this.db.close();
	process.exit(0);
};

function HTMLParser() {
}
HTMLParser.prototype.readBook = function(data) {
	var reader = new XMLTokenizer(data);
	var rootNode = new HTMLRoot();
	var nodeStack = [rootNode];
	var node = null;
	var count = 0;
	while (tokenType !== XMLNodeType.END && count < 300000) {

		var tokenType = reader.nextToken();

		var tokenValue = reader.tokenValue();
		//console.log('type=|' + tokenType + '|  value=|' + tokenValue + '|');
		count++;

		switch(tokenType) {
			case XMLNodeType.ELE_OPEN:
				node = new HTMLElement(tokenValue);
				node.whiteSpace = (priorType === XMLNodeType.WHITESP) ? priorValue : '';
				break;
			case XMLNodeType.ATTR_NAME:
				// do nothing
				break;
			case XMLNodeType.ATTR_VALUE:
				if (priorValue !== 'onclick') {
					node[priorValue] = tokenValue;
				}
				break;
			case XMLNodeType.ELE_END:
				node.emptyElement = false;
				nodeStack[nodeStack.length -1].addChild(node);
				nodeStack.push(node);
				break;
			case XMLNodeType.TEXT:
				node = new HTMLTextNode(tokenValue);
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_EMPTY:
				node.emptyElement = true;
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_CLOSE:
				node = nodeStack.pop();
				if (node.tagName !== tokenValue) {
					throw new Error('closing element mismatch ' + node.openElement() + ' and ' + tokenValue);
				}
				break;
			case XMLNodeType.WHITESP:
				// do nothing
				break;
			case XMLNodeType.PROG_INST:
				// do nothing
				break;
			case XMLNodeType.END:
				// do nothing
				break;
			default:
				throw new Error('The XMLNodeType ' + tokenType + ' is unknown in HTMLParser.');
		}
		var priorType = tokenType;
		var priorValue = tokenValue;
	}
	return(rootNode);
};

function HTMLElement(tagName) {
	this.tagName = tagName;
	this.id = null;
	this['class'] = null;
	this.note = null;
	this.hidden = null;
	this.closed = null;
	this.emptyElement = false;
	this.whiteSpace = '';
	this.children = [];
	Object.seal(this);
}
HTMLElement.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLElement.prototype.toString = function() {
	var array = [];
	this.buildHTML(array, false);
	return(array.join(''));
};
HTMLElement.prototype.toHTML = function() {
	var array = [];
	this.buildHTML(array, true);
	return(array.join(''));
};
HTMLElement.prototype.buildHTML = function(array, includeChildren) {
	array.push(EOL, '<', this.tagName);
	if (this.id) array.push(' id="', this.id, '"');
	if (this['class']) array.push(' class="', this['class'], '"');
	if (this.note) array.push(' note="', this.note, '"');
	if (this.hidden) array.push(' hidden="', this.hidden, '"');
	if (this.closed) array.push(' closed"', this.closed, '"');
	if (this.emptyElement) {
		array.push(' />');
	} else {
		array.push('>');
		if (includeChildren) {
			for (var i=0; i<this.children.length; i++) {
				this.children[i].buildHTML(array, includeChildren);
			}
		}
		array.push('</', this.tagName, '>');
	}
};

function HTMLTextNode(text) {
	this.tagName = 'TEXT';
	this.text = text;
	Object.seal(this);
}
HTMLTextNode.prototype.toString = function() {
	return(this.text);
};
HTMLTextNode.prototype.buildHTML = function(array) {
	array.push(this.text);
};

function HTMLRoot() {
	this.tagName = 'ROOT';
	this.children = [];
	Object.seal(this);
}
HTMLRoot.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLRoot.prototype.toHTML = function() {
	var array = [];
	for (var i=0; i<this.children.length; i++) {
		this.children[i].buildHTML(array, true);
	}
	return(array.join(''));
};

if (process.argv.length < 3) {
	console.log('Usage: HTMLValidator.sh  version');
	process.exit(1);
}
fs.lstat(OUT_BIBLE_PATH, function(err, stat) {
	if (err) {
		fs.mkdirSync(OUT_BIBLE_PATH);
	}
	var version = process.argv[2];
	var htmlValidator = new HTMLValidator(version);
	htmlValidator.open(function() {
		var canon = new Canon();
		htmlValidator.validateBook(0, canon.books, function() {
			htmlValidator.completed();
			console.log('HTMLValidator DONE');
		});
	});
});

<commit_msg>Remove all preWhiteSpace from HTMLTokenizer.<commit_after>/**
* This validation program specifically checks that the generated HTML is identical in content
* to the original USX file.  To do this it reads the HTML data from the generated database,
* parses it, and generates USX files
*/
var fs = require("fs");
//var os = require("os");
var HTML_BIBLE_PATH = "../../DBL/3prepared/";
var OUT_BIBLE_PATH = "output/html/";
var USX_BIBLE_PATH = "../../DBL/2current/";
var EOL = '\r\n';

function HTMLValidator(version) {
	this.version = version;
	this.versionPath = HTML_BIBLE_PATH + version + '.db';
	this.parser = new HTMLParser();
	this.db = null;
}
HTMLValidator.prototype.open = function(callback) {
	var that = this;
	var sqlite3 = require('sqlite3');
	this.db = new sqlite3.Database(this.versionPath, sqlite3.OPEN_READWRITE, function(err) {
		if (err) that.fatalError(err, 'openDatabase');
		that.db.on('trace', function(sql) { console.log('DO ', sql); });
		that.db.on('profile', function(sql, ms) { console.log(ms, 'DONE', sql); });
		callback();
	});
};
HTMLValidator.prototype.validateBook = function(index, books, callback) {
	var that = this;
	if (index >= books.length) {
		callback();
	} else {
		var chapters = [];
		console.log('doing ', books[index]);
		var book = books[index].code;
		this.db.all("SELECT html FROM chapters WHERE reference LIKE ?", book + '%', function(err, results) {
			if (err) that.fatalError(err, 'select html');
			for (var i=0; i<results.length; i++) {
				var node = that.parser.readBook(results[i].html);
				chapters.push(node);
			}
			var usx = convertHTML2USX(chapters);
			compareUSXFile(book, usx, function() {
				that.validateBook(index + 1, books, callback);
			});
		});
	}

	function convertHTML2USX(chapters) {
		var usx = [];
		usx.push(String.fromCharCode('0xFEFF'));
		usx.push('<?xml version="1.0" encoding="utf-8"?>', EOL);
		usx.push('<usx version="2.*">', EOL);
		for (var i=0; i<chapters.length; i++) {
			recurseOverHTML(usx, chapters[i]);
		}
		usx.push(EOL, '</usx>');
		return(usx.join(''));
	}

	function recurseOverHTML(usx, node) {
		convertOpenElement(usx, node);
		if (node.children) {
			for (var i=0; i<node.children.length; i++) {
				recurseOverHTML(usx, node.children[i]);
			}
		}
		convertCloseElement(usx, node);
	}

	function convertOpenElement(usx, node) {
		//console.log(node.tagName);
		switch(node.tagName) {
			case 'ROOT':
				// do nothing
				break;
			case 'article':
				usx.push('<book code="', node.id, '" style="', node['class'], '">');
				break;
			case 'section':
				var parts = node.id.split(':');
				//\r\n  Necessary hack. I think XMLTokenizer discards leading whitespace
				if (parts[1] !== '0') {
					usx.push('\r\n  ', '<chapter number="', parts[1], '" style="c" />');
				}
				//node.children = [];
				break;
			case 'p':
				if (node['class'] === 'c') {
					node.children = [];
				} else if (node.emptyElement) {
					usx.push('<para style="', node['class'], '" />');
				} else {
					usx.push('<para style="', node['class'], '">');
				}
				if (node.hidden) {
					usx.push(node.hidden);
				}
				break;
			case 'span':
				if (node['class'] === 'v') {
					var parts = node.id.split(':');
					usx.push('<verse number="', parts[2], '" style="', node['class'], '" />');
					node.children = [];
				} else if (node['class'] === 'topf') {
					usx.push('<note caller="+" style="f">');
					clearTextChildren(node); // clear note button
				} else if (node['class'] === 'topx') {
					usx.push('<note caller="+" style="x">');
					clearTextChildren(node); // clear note button
				} else if (node.hidden) {
					if (node.closed) {
						usx.push('<char style="', node['class'], '" closed="', node.closed, '">');
					} else {
						usx.push('<char style="', node['class'], '">');
					}
				} else if (node.note) {
					if (node['class'] !== 'f' && node['class'] !== 'x') {
						if (node.closed) {
							usx.push('<char style="', node['class'], '" closed="', node.closed, '">');
						} else {
							usx.push('<char style="', node['class'], '">');
						}
					}
					usx.push(node.note);
				} else {
					usx.push('<char style="', node['class'], '">');
				}
				break;
			case 'TEXT':
				usx.push(node.text);
				break;
			default:
				throw new Error('unexpected HTML element ' + node.tagName + '.');
		}
	}

	function clearTextChildren(node) {
		for (var i=0; i<node.children.length; i++) {
			var child = node.children[i];
			if (child.tagName === 'TEXT') {
				child.text = '';
			}
		}
	}

	function convertCloseElement(usx, node) {
		switch(node.tagName) {
			case 'ROOT':
			case 'section':
				break;
			case 'article':
				usx.push('</book>');
				break;
			case 'TEXT':
				// do nothing
				break;
			case 'p':
				if (node['class'] !== 'c' && ! node.emptyElement) {
					usx.push('</para>');
				}
				break;
			case 'span':
				if (node['class'] === 'v') {
					// do nothing
				} else if (node['class'] === 'topf' || node['class'] === 'topx') {
					usx.push('</note>');
				} else if (node.hidden) {
					usx.push(node.hidden, '</char>');
				} else if (node.note) {
					if (node['class'] !== 'f' && node['class'] !== 'x') {
						usx.push('</char>');
					}
				} else {
					usx.push('</char>');
				}
				break;
			default:
				throw new Error('unexpected HTML element ' + node.tagName + '.');

		}
	}

	function compareUSXFile(book, data, callback) {
		var inFile = USX_BIBLE_PATH + that.version + '/USX_1/' + book + '.usx';
		console.log('INFILE', inFile);
		var outFile = OUT_BIBLE_PATH + book + '.usx';
		console.log('OUTFILE', outFile);
		fs.writeFile(outFile, data, { encoding: 'utf8'}, function(err) {
			if (err) {
				//console.log('WRITE ERROR', JSON.stringify(err));
				//process.exit(1);
				that.fatalError(err, 'Write USX File');
			}
			console.log('COMPARE ', book);
			var proc = require('child_process');
			proc.exec('diff ' + inFile + ' ' + outFile, { encoding: 'utf8' }, function(err, stdout, stderr) {
				if (err) {
					console.log('Diff Error', JSON.stringify(err));
				}
				console.log('STDOUT', stdout);
				console.log('STDERR', stderr);
				callback();
			});
		});
	}
};
HTMLValidator.prototype.fatalError = function(err, source) {
	console.log('FATAL ERROR ', err, ' AT ', source);
	process.exit(1);
};
HTMLValidator.prototype.completed = function() {
	console.log('HTMLValidator COMPLETED');
	this.db.close();
	process.exit(0);
};

function HTMLParser() {
}
HTMLParser.prototype.readBook = function(data) {
	var reader = new XMLTokenizer(data);
	var rootNode = new HTMLRoot();
	var nodeStack = [rootNode];
	var node = null;
	var count = 0;
	while (tokenType !== XMLNodeType.END && count < 300000) {

		var tokenType = reader.nextToken();

		var tokenValue = reader.tokenValue();
		//console.log('type=|' + tokenType + '|  value=|' + tokenValue + '|');
		count++;

		switch(tokenType) {
			case XMLNodeType.ELE_OPEN:
				node = new HTMLElement(tokenValue);
				break;
			case XMLNodeType.ATTR_NAME:
				// do nothing
				break;
			case XMLNodeType.ATTR_VALUE:
				if (priorValue !== 'onclick') {
					node[priorValue] = tokenValue;
				}
				break;
			case XMLNodeType.ELE_END:
				node.emptyElement = false;
				nodeStack[nodeStack.length -1].addChild(node);
				nodeStack.push(node);
				break;
			case XMLNodeType.WHITESP:
			case XMLNodeType.TEXT:
				node = new HTMLTextNode(tokenValue);
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_EMPTY:
				node.emptyElement = true;
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_CLOSE:
				node = nodeStack.pop();
				if (node.tagName !== tokenValue) {
					throw new Error('closing element mismatch ' + node.openElement() + ' and ' + tokenValue);
				}
				break;
			case XMLNodeType.PROG_INST:
				// do nothing
				break;
			case XMLNodeType.END:
				// do nothing
				break;
			default:
				throw new Error('The XMLNodeType ' + tokenType + ' is unknown in HTMLParser.');
		}
		var priorValue = tokenValue;
	}
	return(rootNode);
};

function HTMLElement(tagName) {
	this.tagName = tagName;
	this.id = null;
	this['class'] = null;
	this.note = null;
	this.hidden = null;
	this.closed = null;
	this.emptyElement = false;
	this.children = [];
	Object.seal(this);
}
HTMLElement.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLElement.prototype.toString = function() {
	var array = [];
	this.buildHTML(array, false);
	return(array.join(''));
};
HTMLElement.prototype.toHTML = function() {
	var array = [];
	this.buildHTML(array, true);
	return(array.join(''));
};
HTMLElement.prototype.buildHTML = function(array, includeChildren) {
	array.push(EOL, '<', this.tagName);
	if (this.id) array.push(' id="', this.id, '"');
	if (this['class']) array.push(' class="', this['class'], '"');
	if (this.note) array.push(' note="', this.note, '"');
	if (this.hidden) array.push(' hidden="', this.hidden, '"');
	if (this.closed) array.push(' closed"', this.closed, '"');
	if (this.emptyElement) {
		array.push(' />');
	} else {
		array.push('>');
		if (includeChildren) {
			for (var i=0; i<this.children.length; i++) {
				this.children[i].buildHTML(array, includeChildren);
			}
		}
		array.push('</', this.tagName, '>');
	}
};

function HTMLTextNode(text) {
	this.tagName = 'TEXT';
	this.text = text;
	Object.seal(this);
}
HTMLTextNode.prototype.toString = function() {
	return(this.text);
};
HTMLTextNode.prototype.buildHTML = function(array) {
	array.push(this.text);
};

function HTMLRoot() {
	this.tagName = 'ROOT';
	this.children = [];
	Object.seal(this);
}
HTMLRoot.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLRoot.prototype.toHTML = function() {
	var array = [];
	for (var i=0; i<this.children.length; i++) {
		this.children[i].buildHTML(array, true);
	}
	return(array.join(''));
};

if (process.argv.length < 3) {
	console.log('Usage: HTMLValidator.sh  version');
	process.exit(1);
}
fs.lstat(OUT_BIBLE_PATH, function(err, stat) {
	if (err) {
		fs.mkdirSync(OUT_BIBLE_PATH);
	}
	var version = process.argv[2];
	var htmlValidator = new HTMLValidator(version);
	htmlValidator.open(function() {
		var canon = new Canon();
		htmlValidator.validateBook(0, canon.books, function() {
			htmlValidator.completed();
			console.log('HTMLValidator DONE');
		});
	});
});

<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global _*/
/* global eventLibrary */

////////////////////////////////////////////////////////////////////////////////
/// @brief Graph functionality
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// Example onclick = new eventLibrary.Expand(
// edges, nodes, start,
// adapter.loadNode, nodeShaper.reshapeNode)
function EventLibrary() {
  this.Expand = function (edges, nodes, startCallback, loadNode, reshapeNode) {
    if (edges === undefined) {
      throw "Edges have to be defined";
    }

    if (nodes === undefined) {
      throw "Nodes have to be defined";
    }

    if (startCallback === undefined) {
      throw "A callback to the Start-method has to be defined";
    }

    if (loadNode === undefined) {
      throw "A callback to load a node has to be defined";
    }

    if (reshapeNode === undefined) {
      throw "A callback to reshape a node has to be defined";
    }

    var removeNode = function (node) {
      var i;
      for ( i = 0; i < nodes.length; i++ ) {
        if ( nodes[i] === node ) {
          nodes.splice( i, 1 );
          return;
        }
      }
    },

    // Helper function to easily remove all outbound edges for one node
    removeOutboundEdgesFromNode = function ( node ) {
      if (node._outboundCounter > 0) {
        var subNodes = [],
        i;
        for ( i = 0; i < edges.length; i++ ) {
          if ( edges[i].source === node ) {
            subNodes.push(edges[i].target);
            node._outboundCounter--;
            edges[i].target._inboundCounter--;
            edges.splice( i, 1 );
            if (node._outboundCounter === 0) {
              break;
            }
            i--;
          }
        }
        return subNodes;
      }
    },

    collapseNode = function(node) {
      node._expanded = false;
      var subNodes = removeOutboundEdgesFromNode(node);
      _.each(subNodes, function (n) {
        if (n._inboundCounter === 0) {
          collapseNode(n);
          removeNode(n);
        }
      });
    },

    expandNode = function(n) {
      n._expanded = true;
      loadNode(n._id, startCallback);
    };

    // @ before layouter.stop()
    // nodeClicked = function(n)
    return function(n) {
      if (!n._expanded) {
        expandNode(n);
      } else {
        collapseNode(n);
      }
      reshapeNode(n);
      startCallback();
    };
  };

  this.InsertNode = function (nodes, adapter, nodeShaper) {
    return function(callback) {
      adapter.createNode({}, function(newNode) {
        newNode._outboundCounter = 0;
        newNode._inboundCounter = 0;
        nodeShaper.drawNodes(nodes);
        callback(newNode);
      });
    };
  };

  this.PatchNode = function (nodes, adapter, nodeShaper) {
    return function(nodeToPatch, patchData, callback) {
      adapter.patchNode(nodeToPatch, patchData, function(patchedNode) {
        nodeShaper.drawNodes(nodes);
        callback(patchedNode);
      });
    };

  };

  this.DeleteNode = function (nodes, adapter, nodeShaper) {
    return function(nodeToDelete, callback) {
      adapter.deleteNode(nodeToDelete, callback);
    };
  };

  this.InsertEdge = function (edges, adapter, edgeShaper) {
    return function(source, target, callback) {
      adapter.createEdge({source: source, target: target}, function(newEdge) {
        edgeShaper.drawEdges(edges);
        callback(newEdge);
      });
    };
  };

  this.PatchEdge = function (edges, adapter, edgeShaper) {
    return function(edgeToPatch, patchData, callback) {
      adapter.patchEdge(edgeToPatch, patchData, function(patchedEdge) {
        edgeShaper.drawEdges(edges);
        callback(patchedEdge);
      });
    };

  };

  this.DeleteEdge = function (edges, adapter, edgeShaper) {
    return function(edgeToDelete, callback) {
      adapter.deleteEdge(edgeToDelete, callback);
    };
  };

}<commit_msg>Improved style of EventLib code<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global _*/
/* global eventLibrary */

////////////////////////////////////////////////////////////////////////////////
/// @brief Graph functionality
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// Example onclick = new eventLibrary.Expand(
// edges, nodes, start,
// adapter.loadNode, nodeShaper.reshapeNode)
function EventLibrary() {
  this.Expand = function (edges, nodes, startCallback, loadNode, reshapeNode) {
    if (edges === undefined) {
      throw "Edges have to be defined";
    }

    if (nodes === undefined) {
      throw "Nodes have to be defined";
    }

    if (startCallback === undefined) {
      throw "A callback to the Start-method has to be defined";
    }

    if (loadNode === undefined) {
      throw "A callback to load a node has to be defined";
    }

    if (reshapeNode === undefined) {
      throw "A callback to reshape a node has to be defined";
    }

    var removeNode = function (node) {
      var i;
      for ( i = 0; i < nodes.length; i++ ) {
        if ( nodes[i] === node ) {
          nodes.splice( i, 1 );
          return;
        }
      }
    },

    // Helper function to easily remove all outbound edges for one node
    removeOutboundEdgesFromNode = function ( node ) {
      if (node._outboundCounter > 0) {
        var subNodes = [],
        i;
        for ( i = 0; i < edges.length; i++ ) {
          if ( edges[i].source === node ) {
            subNodes.push(edges[i].target);
            node._outboundCounter--;
            edges[i].target._inboundCounter--;
            edges.splice( i, 1 );
            if (node._outboundCounter === 0) {
              break;
            }
            i--;
          }
        }
        return subNodes;
      }
    },

    collapseNode = function(node) {
      node._expanded = false;
      var subNodes = removeOutboundEdgesFromNode(node);
      _.each(subNodes, function (n) {
        if (n._inboundCounter === 0) {
          collapseNode(n);
          removeNode(n);
        }
      });
    },

    expandNode = function(n) {
      n._expanded = true;
      loadNode(n._id, startCallback);
    };

    return function(n) {
      if (!n._expanded) {
        expandNode(n);
      } else {
        collapseNode(n);
      }
      reshapeNode(n);
      startCallback();
    };
  };

  this.InsertNode = function (nodes, adapter, nodeShaper) {
    return function(callback) {
      adapter.createNode({}, function(newNode) {
        newNode._outboundCounter = 0;
        newNode._inboundCounter = 0;
        nodeShaper.drawNodes(nodes);
        callback(newNode);
      });
    };
  };

  this.PatchNode = function (nodes, adapter, nodeShaper) {
    return function(nodeToPatch, patchData, callback) {
      adapter.patchNode(nodeToPatch, patchData, function(patchedNode) {
        nodeShaper.drawNodes(nodes);
        callback(patchedNode);
      });
    };
  };

  this.DeleteNode = function (nodes, adapter, nodeShaper) {
    return function(nodeToDelete, callback) {
      adapter.deleteNode(nodeToDelete, callback);
    };
  };

  this.InsertEdge = function (edges, adapter, edgeShaper) {
    return function(source, target, callback) {
      adapter.createEdge({source: source, target: target}, function(newEdge) {
        edgeShaper.drawEdges(edges);
        callback(newEdge);
      });
    };
  };

  this.PatchEdge = function (edges, adapter, edgeShaper) {
    return function(edgeToPatch, patchData, callback) {
      adapter.patchEdge(edgeToPatch, patchData, function(patchedEdge) {
        edgeShaper.drawEdges(edges);
        callback(patchedEdge);
      });
    };
  };

  this.DeleteEdge = function (edges, adapter, edgeShaper) {
    return function(edgeToDelete, callback) {
      adapter.deleteEdge(edgeToDelete, callback);
    };
  };

}<|endoftext|>


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

const EdgeInsetsPropType = require('EdgeInsetsPropType');
const React = require('React');
const TimerMixin = require('react-timer-mixin');
const Touchable = require('Touchable');
const View = require('View');

const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
const warning = require('fbjs/lib/warning');

type Event = Object;

const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};

/**
 * Do not use unless you have a very good reason. All the elements that
 * respond to press should have a visual feedback when touched. This is
 * one of the primary reasons a "web" app doesn't feel "native".
 *
 * > **NOTE**: TouchableWithoutFeedback supports only one child
 * >
 * > If you wish to have several child components, wrap them in a View.
 */
const TouchableWithoutFeedback = React.createClass({
  mixins: [TimerMixin, Touchable.Mixin],

  propTypes: {
    accessible: React.PropTypes.bool,
    accessibilityComponentType: React.PropTypes.oneOf(View.AccessibilityComponentType),
    accessibilityTraits: React.PropTypes.oneOfType([
      React.PropTypes.oneOf(View.AccessibilityTraits),
      React.PropTypes.arrayOf(React.PropTypes.oneOf(View.AccessibilityTraits)),
    ]),
    /**
     * If true, disable all interactions for this component.
     */
    disabled: React.PropTypes.bool,
    /**
     * Called when the touch is released, but not if cancelled (e.g. by a scroll
     * that steals the responder lock).
     */
    onPress: React.PropTypes.func,
    onPressIn: React.PropTypes.func,
    onPressOut: React.PropTypes.func,
    /**
     * Invoked on mount and layout changes with
     *
     *   `{nativeEvent: {layout: {x, y, width, height}}}`
     */
    onLayout: React.PropTypes.func,

    onLongPress: React.PropTypes.func,

    /**
     * Delay in ms, from the start of the touch, before onPressIn is called.
     */
    delayPressIn: React.PropTypes.number,
    /**
     * Delay in ms, from the release of the touch, before onPressOut is called.
     */
    delayPressOut: React.PropTypes.number,
    /**
     * Delay in ms, from onPressIn, before onLongPress is called.
     */
    delayLongPress: React.PropTypes.number,
    /**
     * When the scroll view is disabled, this defines how far your touch may
     * move off of the button, before deactivating the button. Once deactivated,
     * try moving it back and you'll see that the button is once again
     * reactivated! Move it back and forth several times while the scroll view
     * is disabled. Ensure you pass in a constant to reduce memory allocations.
     */
    pressRetentionOffset: EdgeInsetsPropType,
    /**
     * This defines how far your touch can start away from the button. This is
     * added to `pressRetentionOffset` when moving off of the button.
     * ** NOTE **
     * The touch area never extends past the parent view bounds and the Z-index
     * of sibling views always takes precedence if a touch hits two overlapping
     * views.
     */
    hitSlop: EdgeInsetsPropType,
  },

  getInitialState: function() {
    return this.touchableGetInitialState();
  },

  componentDidMount: function() {
    ensurePositiveDelayProps(this.props);
  },

  componentWillReceiveProps: function(nextProps: Object) {
    ensurePositiveDelayProps(nextProps);
  },

  /**
   * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
   * defined on your component.
   */
  touchableHandlePress: function(e: Event) {
    this.props.onPress && this.props.onPress(e);
  },

  touchableHandleActivePressIn: function(e: Event) {
    this.props.onPressIn && this.props.onPressIn(e);
  },

  touchableHandleActivePressOut: function(e: Event) {
    this.props.onPressOut && this.props.onPressOut(e);
  },

  touchableHandleLongPress: function(e: Event) {
    this.props.onLongPress && this.props.onLongPress(e);
  },

  touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET {
    return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
  },

  touchableGetHitSlop: function(): ?Object {
    return this.props.hitSlop;
  },

  touchableGetHighlightDelayMS: function(): number {
    return this.props.delayPressIn || 0;
  },

  touchableGetLongPressDelayMS: function(): number {
    return this.props.delayLongPress === 0 ? 0 :
      this.props.delayLongPress || 500;
  },

  touchableGetPressOutDelayMS: function(): number {
    return this.props.delayPressOut || 0;
  },

  render: function(): React.Element<any> {
    // Note(avik): remove dynamic typecast once Flow has been upgraded
    const child = React.Children.only(this.props.children);
    let children = child.props.children;
    warning(
      !child.type || child.type.displayName !== 'Text',
      'TouchableWithoutFeedback does not work well with Text children. Wrap children in a View instead. See ' +
        ((child._owner && child._owner.getName && child._owner.getName()) || '<unknown>')
    );
    if (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'View') {
      children = React.Children.toArray(children);
      children.push(Touchable.renderDebugView({color: 'red', hitSlop: this.props.hitSlop}));
    }
    const style = (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text') ?
      [child.props.style, {color: 'red'}] :
      child.props.style;
    return (React: any).cloneElement(child, {
      accessible: this.props.accessible !== false,
      accessibilityLabel: this.props.accessibilityLabel,
      accessibilityComponentType: this.props.accessibilityComponentType,
      accessibilityTraits: this.props.accessibilityTraits,
      testID: this.props.testID,
      onLayout: this.props.onLayout,
      hitSlop: this.props.hitSlop,
      onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
      onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest,
      onResponderGrant: this.touchableHandleResponderGrant,
      onResponderMove: this.touchableHandleResponderMove,
      onResponderRelease: this.touchableHandleResponderRelease,
      onResponderTerminate: this.touchableHandleResponderTerminate,
      style,
      children,
    });
  }
});

module.exports = TouchableWithoutFeedback;
<commit_msg>remove peculiar web language<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule TouchableWithoutFeedback
 * @flow
 */
'use strict';

const EdgeInsetsPropType = require('EdgeInsetsPropType');
const React = require('React');
const TimerMixin = require('react-timer-mixin');
const Touchable = require('Touchable');
const View = require('View');

const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
const warning = require('fbjs/lib/warning');

type Event = Object;

const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};

/**
 * Do not use unless you have a very good reason. All the elements that
 * respond to press should have a visual feedback when touched.
 *
 * > **NOTE**: TouchableWithoutFeedback supports only one child
 * >
 * > If you wish to have several child components, wrap them in a View.
 */
const TouchableWithoutFeedback = React.createClass({
  mixins: [TimerMixin, Touchable.Mixin],

  propTypes: {
    accessible: React.PropTypes.bool,
    accessibilityComponentType: React.PropTypes.oneOf(View.AccessibilityComponentType),
    accessibilityTraits: React.PropTypes.oneOfType([
      React.PropTypes.oneOf(View.AccessibilityTraits),
      React.PropTypes.arrayOf(React.PropTypes.oneOf(View.AccessibilityTraits)),
    ]),
    /**
     * If true, disable all interactions for this component.
     */
    disabled: React.PropTypes.bool,
    /**
     * Called when the touch is released, but not if cancelled (e.g. by a scroll
     * that steals the responder lock).
     */
    onPress: React.PropTypes.func,
    onPressIn: React.PropTypes.func,
    onPressOut: React.PropTypes.func,
    /**
     * Invoked on mount and layout changes with
     *
     *   `{nativeEvent: {layout: {x, y, width, height}}}`
     */
    onLayout: React.PropTypes.func,

    onLongPress: React.PropTypes.func,

    /**
     * Delay in ms, from the start of the touch, before onPressIn is called.
     */
    delayPressIn: React.PropTypes.number,
    /**
     * Delay in ms, from the release of the touch, before onPressOut is called.
     */
    delayPressOut: React.PropTypes.number,
    /**
     * Delay in ms, from onPressIn, before onLongPress is called.
     */
    delayLongPress: React.PropTypes.number,
    /**
     * When the scroll view is disabled, this defines how far your touch may
     * move off of the button, before deactivating the button. Once deactivated,
     * try moving it back and you'll see that the button is once again
     * reactivated! Move it back and forth several times while the scroll view
     * is disabled. Ensure you pass in a constant to reduce memory allocations.
     */
    pressRetentionOffset: EdgeInsetsPropType,
    /**
     * This defines how far your touch can start away from the button. This is
     * added to `pressRetentionOffset` when moving off of the button.
     * ** NOTE **
     * The touch area never extends past the parent view bounds and the Z-index
     * of sibling views always takes precedence if a touch hits two overlapping
     * views.
     */
    hitSlop: EdgeInsetsPropType,
  },

  getInitialState: function() {
    return this.touchableGetInitialState();
  },

  componentDidMount: function() {
    ensurePositiveDelayProps(this.props);
  },

  componentWillReceiveProps: function(nextProps: Object) {
    ensurePositiveDelayProps(nextProps);
  },

  /**
   * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
   * defined on your component.
   */
  touchableHandlePress: function(e: Event) {
    this.props.onPress && this.props.onPress(e);
  },

  touchableHandleActivePressIn: function(e: Event) {
    this.props.onPressIn && this.props.onPressIn(e);
  },

  touchableHandleActivePressOut: function(e: Event) {
    this.props.onPressOut && this.props.onPressOut(e);
  },

  touchableHandleLongPress: function(e: Event) {
    this.props.onLongPress && this.props.onLongPress(e);
  },

  touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET {
    return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
  },

  touchableGetHitSlop: function(): ?Object {
    return this.props.hitSlop;
  },

  touchableGetHighlightDelayMS: function(): number {
    return this.props.delayPressIn || 0;
  },

  touchableGetLongPressDelayMS: function(): number {
    return this.props.delayLongPress === 0 ? 0 :
      this.props.delayLongPress || 500;
  },

  touchableGetPressOutDelayMS: function(): number {
    return this.props.delayPressOut || 0;
  },

  render: function(): React.Element<any> {
    // Note(avik): remove dynamic typecast once Flow has been upgraded
    const child = React.Children.only(this.props.children);
    let children = child.props.children;
    warning(
      !child.type || child.type.displayName !== 'Text',
      'TouchableWithoutFeedback does not work well with Text children. Wrap children in a View instead. See ' +
        ((child._owner && child._owner.getName && child._owner.getName()) || '<unknown>')
    );
    if (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'View') {
      children = React.Children.toArray(children);
      children.push(Touchable.renderDebugView({color: 'red', hitSlop: this.props.hitSlop}));
    }
    const style = (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text') ?
      [child.props.style, {color: 'red'}] :
      child.props.style;
    return (React: any).cloneElement(child, {
      accessible: this.props.accessible !== false,
      accessibilityLabel: this.props.accessibilityLabel,
      accessibilityComponentType: this.props.accessibilityComponentType,
      accessibilityTraits: this.props.accessibilityTraits,
      testID: this.props.testID,
      onLayout: this.props.onLayout,
      hitSlop: this.props.hitSlop,
      onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
      onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest,
      onResponderGrant: this.touchableHandleResponderGrant,
      onResponderMove: this.touchableHandleResponderMove,
      onResponderRelease: this.touchableHandleResponderRelease,
      onResponderTerminate: this.touchableHandleResponderTerminate,
      style,
      children,
    });
  }
});

module.exports = TouchableWithoutFeedback;
<|endoftext|>


<commit_before>(function () {
function autoCallback(fn) {
  fn();
}

// Localize the splat test functions
var test = Splat.test,
    assert = Splat.assert;

// Create a function to test modules
function testModule(moduleName, runner) {
  // Fallback test runner
  runner = runner || autoCallback;

  test(moduleName + ' can run a single batch', function () {
    var hasRun = false,
        suite = new Skeleton;

    // Generate a simple batch
    suite.addBatch({
      'single batch': {
        'runs': function () {
          hasRun = true;
        }
      }
    });

    // Export and run the test
    suite.exportTo(moduleName);
    runner(function () {
      // Make sure the test ran the batch
      assert(hasRun);
    });
  });

  test(moduleName + ' supports multiple batches', function () {
    var hasRun1 = false,
        hasRun2 = false,
        suite = new Skeleton;

    suite.addBatch({
      'batch1': {
        'runs': function () {
          hasRun1 = true;
        }
      }
    });

    suite.addBatch({
      'batch2': {
        'runs': function () {
          hasRun2 = true;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      assert(hasRun1);
      assert(hasRun2);
    });
  });

  test(moduleName + ' supports beforeEach', function () {
    var beforeBool = true,
        runCount = 0,
        suite = new Skeleton;

    suite.addBatch({
      'eachTest': {
        'beforeEach': function () {
          if (beforeBool || runCount > 0) {
            runCount += 1;
          }
        },
        'test1': function () {
          beforeBool = false;
          var a = 1 + 1;
        },
        'test2': function () {
          beforeBool = false;
          var b = 1 + 1;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      assert(runCount === 2);
    });
  });

  test(moduleName + ' supports afterEach', function () {
    var afterBool = false,
        runCount = 0,
        suite = new Skeleton;

    suite.addBatch({
      'eachTest': {
        'afterEach': function () {
          if (afterBool) {
            runCount += 1;
          }
        },
        'test1': function () {
          var a = 1 + 1;
          afterBool = true;
        },
        'test2': function () {
          var b = 1 + 1;
          afterBool = true;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      setTimeout(function () {
        assert(runCount === 2);
      }, 20);
    });
  });

  // TODO: Get this working
  // test(moduleName + ' supports async topics', function () {
    // var called = false,
        // suite = new Skeleton;

    // suite.addBatch({
      // 'async': {
        // topic: Skeleton.async(function () {
          // var callback = this.callback;
          // setTimeout(function () {
            // called = true;
            // callback();
          // }, 100);
        // }),
        // 'test1': function () {
          // assert(called);
        // }
      // }
    // });

    // suite.exportTo(moduleName);
    // runner(function () {
      // assert(called);
    // });
  // });

  // TODO: Handle .async .beforeEach and .afterEach in helper method

  test(moduleName + ' supports async tests', function () {
    var called1 = false,
        called2 = false,
        suite = new Skeleton;

    suite.addBatch({
      'async': {
        'test1': Skeleton.async(function () {
          var callback = this.callback;
          assert(typeof callback === 'function');

          setTimeout(function () {
            called1 = true;
            callback();
          }, 100);
        })
      }
    });

    // Once the asynchronous test has run, assert via a second test
    // TODO: If this does not work, use .afterEach
    suite.addBatch({
      'after sync': {
        'test2': function () {
          console.log('z');
          if (called1 === true) {
          console.log('hm');
            called2 = true;
          }
        }
      }
    });

    // Export the two suites
    suite.exportTo(moduleName);

    // Assert that the tests are run in order (even when async)
    runner(function () {
      // Make sure that after sync has not been called in 10ms
      setTimeout(function () {
        console.log('a');
        assert(called2 === false);
        console.log('b');
      }, 10);

      // But after the async test, everything is good
      setTimeout(function () {
        console.log('c', called1, called2);
        assert(called1);
        assert(called2);
        console.log('d');
      }, 300);
    });
  });
}

// Expose testModule to the window scope
window.testModule = testModule;
}());<commit_msg>Async test working properly<commit_after>(function () {
function autoCallback(fn) {
  fn();
}

// Localize the splat test functions
var test = Splat.test,
    assert = Splat.assert;

// Create a function to test modules
function testModule(moduleName, runner) {
  // Fallback test runner
  runner = runner || autoCallback;

  test(moduleName + ' can run a single batch', function () {
    var hasRun = false,
        suite = new Skeleton;

    // Generate a simple batch
    suite.addBatch({
      'single batch': {
        'runs': function () {
          hasRun = true;
        }
      }
    });

    // Export and run the test
    suite.exportTo(moduleName);
    runner(function () {
      // Make sure the test ran the batch
      assert(hasRun);
    });
  });

  test(moduleName + ' supports multiple batches', function () {
    var hasRun1 = false,
        hasRun2 = false,
        suite = new Skeleton;

    suite.addBatch({
      'batch1': {
        'runs': function () {
          hasRun1 = true;
        }
      }
    });

    suite.addBatch({
      'batch2': {
        'runs': function () {
          hasRun2 = true;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      assert(hasRun1);
      assert(hasRun2);
    });
  });

  test(moduleName + ' supports beforeEach', function () {
    var beforeBool = true,
        runCount = 0,
        suite = new Skeleton;

    suite.addBatch({
      'eachTest': {
        'beforeEach': function () {
          if (beforeBool || runCount > 0) {
            runCount += 1;
          }
        },
        'test1': function () {
          beforeBool = false;
          var a = 1 + 1;
        },
        'test2': function () {
          beforeBool = false;
          var b = 1 + 1;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      assert(runCount === 2);
    });
  });

  test(moduleName + ' supports afterEach', function () {
    var afterBool = false,
        runCount = 0,
        suite = new Skeleton;

    suite.addBatch({
      'eachTest': {
        'afterEach': function () {
          if (afterBool) {
            runCount += 1;
          }
        },
        'test1': function () {
          var a = 1 + 1;
          afterBool = true;
        },
        'test2': function () {
          var b = 1 + 1;
          afterBool = true;
        }
      }
    });

    suite.exportTo(moduleName);
    runner(function () {
      setTimeout(function () {
        assert(runCount === 2);
      }, 20);
    });
  });

  // TODO: Get this working
  // test(moduleName + ' supports async topics', function () {
    // var called = false,
        // suite = new Skeleton;

    // suite.addBatch({
      // 'async': {
        // topic: Skeleton.async(function () {
          // var callback = this.callback;
          // setTimeout(function () {
            // called = true;
            // callback();
          // }, 100);
        // }),
        // 'test1': function () {
          // assert(called);
        // }
      // }
    // });

    // suite.exportTo(moduleName);
    // runner(function () {
      // assert(called);
    // });
  // });

  // TODO: Handle .async .beforeEach and .afterEach in helper method

  test(moduleName + ' supports async tests', function () {
    var called1 = false,
        called2 = false,
        suite = new Skeleton;

    suite.addBatch({
      'async': {
        // Once the asynchronous test has run, assert via a second test
        'afterEach': function () {
          if (called1 === true) {
            called2 = true;
          }
        },
        'test1': Skeleton.async(function () {
          var callback = this.callback;
          assert(typeof callback === 'function');

          setTimeout(function () {
            called1 = true;
            callback();
          }, 100);
        })
      }
    });

    // Export the two suites
    suite.exportTo(moduleName);

    // Assert that the tests are run in order (even when async)
    runner(function () {
      // Make sure that after sync has not been called in 10ms
      setTimeout(function () {
        assert(called2 === false);
      }, 10);

      // But after the async test, everything is good
      setTimeout(function () {
        assert(called1);
        assert(called2);
      }, 300);
    });
  });
}

// Expose testModule to the window scope
window.testModule = testModule;
}());<|endoftext|>


<commit_before>/**
* Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
* Use of this source code is governed by a BSD License (see LICENSE).
+*/

'use strict';

var React = require('react');
var ReactRouter = require('react-router');

var AssignmentStore = require('stores/AssignmentStore');
var Button = require('components/Button');
var CommitteeStore = require('stores/CommitteeStore');
var ConferenceContext = require('components/ConferenceContext');
var CountryStore = require('stores/CountryStore');
var CurrentUserStore = require('stores/CurrentUserStore');
var CurrentUserActions = require('actions/CurrentUserActions');
var DelegateSelect = require('components/DelegateSelect');
var DelegateStore = require('stores/DelegateStore');
var InnerView = require('components/InnerView');
var ServerAPI = require('lib/ServerAPI');

var ChairAttendanceView = React.createClass({
  mixins: [
    ReactRouter.History,
  ],

  render: function() {
    return (
      <InnerView>

Assignments

          Here you can view your tentative assignments for BMUN {conference.session}. If you
          would like to request more slots, please email
          info@bmun.org. The assignment finalization deadline is January 23rd.
          After assignment finalization we will ask that you assign the
          delegates you have added in the delegates tab to the assignments
          given to you.

      </InnerView>
    );
  },
});

module.exports = ChairAttendanceView;
<commit_msg>Chair view<commit_after>/**
* Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
* Use of this source code is governed by a BSD License (see LICENSE).
+*/

'use strict';

var React = require('react');
var ReactRouter = require('react-router');

var AssignmentStore = require('stores/AssignmentStore');
var Button = require('components/Button');
var CommitteeStore = require('stores/CommitteeStore');
var ConferenceContext = require('components/ConferenceContext');
var CountryStore = require('stores/CountryStore');
var CurrentUserStore = require('stores/CurrentUserStore');
var CurrentUserActions = require('actions/CurrentUserActions');
var DelegateSelect = require('components/DelegateSelect');
var DelegateStore = require('stores/DelegateStore');
var InnerView = require('components/InnerView');
var ServerAPI = require('lib/ServerAPI');
var User = require('utils/User');

var ChairAttendanceView = React.createClass({
  mixins: [
    ReactRouter.History,
  ],

  componentDidMount: function() {
    console.log(this.props.user);
    if (!User.isChair(this.props.user)) {
      this.history.pushState(null, '/login');
    }
  },

  render: function() {
    return (
      <InnerView>

Assignments

          Here you can view your tentative assignments for BMUN {conference.session}. If you
          would like to request more slots, please email
          info@bmun.org. The assignment finalization deadline is January 23rd.
          After assignment finalization we will ask that you assign the
          delegates you have added in the delegates tab to the assignments
          given to you.

      </InnerView>
    );
  },
});

module.exports = ChairAttendanceView;
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides the Design Time Metadata for the sap.ui.layout.form.FormContainer control
sap.ui.define([],
	function() {
	"use strict";

	function _allFormElementsInvisible(oFormContainer){

		return oFormContainer.getFormElements().every(function(oFormElement){
			return oFormElement.getVisible() === false;
		});
	}

	return {
		actions: {
			remove: {
				changeType: "hideControl"
			},
			rename: {
				changeType: "renameGroup",
				domRef: function (oFormContainer) {
					return jQuery(oFormContainer.getRenderedDomRef()).find(".sapUiFormTitle")[0];
				},
				isEnabled : function (oFormContainer) {
					return !(oFormContainer.getToolbar() || !oFormContainer.getTitle());
				}
			}
		},
		aggregations : {
			formElements : {
				domRef: function (oFormContainer) {
					var oDomRef = oFormContainer.getDomRef();
					if (!oDomRef && oFormContainer.getFormElements().length === 0 || _allFormElementsInvisible(oFormContainer)) {
						var oHeader = oFormContainer.getTitle() || oFormContainer.getToolbar();
						if (oHeader) {
							return oHeader.getDomRef();
						}
					} else {
						return oDomRef;
					}
				},
				actions: {
					move: "moveControls"
				}
			},
			toolbar : {
				domRef: function (oFormContainer) {
					var oToolbar = oFormContainer.getToolbar();
					if (oToolbar) {
						return oToolbar.getDomRef();
					}
				}
			}
		},
		name: {
			singular: "GROUP_CONTROL_NAME",
			plural: "GROUP_CONTROL_NAME_PLURAL"
		}
	};

}, /* bExport= */ false);<commit_msg>[INTERNAL][FIX] sap.ui.layout domref for string type FormContainer in designtime<commit_after>/*!
 * ${copyright}
 */

// Provides the Design Time Metadata for the sap.ui.layout.form.FormContainer control
sap.ui.define([],
	function() {
	"use strict";

	function _allFormElementsInvisible(oFormContainer){

		return oFormContainer.getFormElements().every(function(oFormElement){
			return oFormElement.getVisible() === false;
		});
	}

	return {
		actions: {
			remove: {
				changeType: "hideControl"
			},
			rename: {
				changeType: "renameGroup",
				domRef: function (oFormContainer) {
					return jQuery(oFormContainer.getRenderedDomRef()).find(".sapUiFormTitle")[0];
				},
				isEnabled : function (oFormContainer) {
					return !(oFormContainer.getToolbar() || !oFormContainer.getTitle());
				}
			}
		},
		aggregations : {
			formElements : {
				domRef: function (oFormContainer) {
					var oDomRef = oFormContainer.getDomRef();
					var oHeader = oFormContainer.getTitle() || oFormContainer.getToolbar();
					if (!oDomRef && (oFormContainer.getFormElements().length === 0 || _allFormElementsInvisible(oFormContainer)) && oHeader instanceof sap.ui.core.Element) {
						return oHeader.getDomRef();
					} else if (typeof oHeader === "string") {
						return jQuery(oDomRef).find(".sapUiFormTitle").get(0);
					} else {
						return oDomRef;
					}
				},
				actions: {
					move: "moveControls"
				}
			},
			toolbar : {
				domRef: function (oFormContainer) {
					var oToolbar = oFormContainer.getToolbar();
					if (oToolbar) {
						return oToolbar.getDomRef();
					}
				}
			}
		},
		name: {
			singular: "GROUP_CONTROL_NAME",
			plural: "GROUP_CONTROL_NAME_PLURAL"
		}
	};

}, /* bExport= */ false);<|endoftext|>


<commit_before>var Address4 = require("ip-address").Address4;
var Address6 = require("ip-address").Address6;

var config = require("../helpers/config");
var controller = require("../helpers/controller");
var Tools = require("../helpers/tools");

module.exports = function(req, res, next) {
    console.log(req.ip, req.connection.remoteAddress, req.headers["x-forwarded-for"], req.headers["x-client-ip"], req.socket.ip);
    if (req.socket.ip) {
        Object.defineProperty(req, "ip", { value: req.socket.ip });
        next();
        return;
    }
    var trueIp = Tools.correctAddress(req.ip || req.connection.remoteAddress);
    if (!trueIp)
        return res.sendStatus(500);
    if (config("system.detectRealIp", true)) {
        var ip = req.headers["x-forwarded-for"];
        if (!ip)
            ip = req.headers["x-client-ip"];
        if (ip) {
            var address = Tools.correctAddress(ip);
            if (!address)
                return res.sendStatus(500);
            trueIp = address;
        }
    }
    if (config("system.useXRealIp", false)) {
        var ip = req.headers["x-real-ip"];
        var address = Tools.correctAddress(ip);
        if (!address)
            return res.sendStatus(500);
        trueIp = address;
    }
    Object.defineProperty(req, "ip", { value: trueIp });
    Object.defineProperty(req.socket, "ip", { value: trueIp });
    next();
};
<commit_msg>Debug<commit_after>var Address4 = require("ip-address").Address4;
var Address6 = require("ip-address").Address6;

var config = require("../helpers/config");
var controller = require("../helpers/controller");
var Tools = require("../helpers/tools");

module.exports = function(req, res, next) {
    console.log(req.ip, req.connection.remoteAddress, req.headers["x-forwarded-for"], req.headers["x-client-ip"], req.socket.ip);
    /*if (req.socket.ip) {
        Object.defineProperty(req, "ip", { value: req.socket.ip });
        next();
        return;
    }*/
    var trueIp = Tools.correctAddress(req.ip || req.connection.remoteAddress);
    if (!trueIp)
        return res.sendStatus(500);
    if (config("system.detectRealIp", true)) {
        var ip = req.headers["x-forwarded-for"];
        if (!ip)
            ip = req.headers["x-client-ip"];
        if (ip) {
            var address = Tools.correctAddress(ip);
            if (!address)
                return res.sendStatus(500);
            trueIp = address;
        }
    }
    if (config("system.useXRealIp", false)) {
        var ip = req.headers["x-real-ip"];
        var address = Tools.correctAddress(ip);
        if (!address)
            return res.sendStatus(500);
        trueIp = address;
    }
    Object.defineProperty(req, "ip", { value: trueIp });
    //Object.defineProperty(req.socket, "ip", { value: trueIp });
    next();
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import compose from 'recompose/compose';
import { withHandlers } from 'recompose';

import { RECT, CIRC, LINE } from 'vclub/constants/whiteboardElements';

import styles from './ElementsPanel.css';

const enhance = compose(
  withHandlers({
    onClickForRect: props => () => props.onClick(RECT),
    onClickForLine: props => () => props.onClick(LINE),
    onClickForCircle: props => () => props.onClick(CIRC),
  })
);

function ElementsPanel(props) {
  const {
    onClickForRect, onClickForLine, onClickForCircle,
    nextFigureType,
  } = props;

  const gCN = (elm, nextFigureType) =>
    elm === nextFigureType
      ? styles.buttonCurrent
      : styles.button;

  return (

        <button onClick={onClickForRect} className={gCN(RECT, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <rect x="5" y="5" width="190" height="190" />
          </svg>
          {/* Rect */}
        </button>

        <button onClick={onClickForLine} className={gCN(LINE, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <circle cx="100" cy="100" r="100" />
          </svg>
          {/* Line */}
        </button>

        <button onClick={onClickForCircle} className={gCN(CIRC, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <line x1="20" y1="180" x2="180" y2="20" stroke="black" strokeWidth="20" />
          </svg>
        </button>

  );
}

ElementsPanel.propTypes = {
  onClickForRect: PropTypes.func,
  onClickForLine: PropTypes.func,
  onClickForCircle: PropTypes.func,
  nextFigureType: PropTypes.number,
};

export default enhance(ElementsPanel);
<commit_msg>change elements' buttons to correct<commit_after>import React, { PropTypes } from 'react';
import compose from 'recompose/compose';
import { withHandlers } from 'recompose';

import { RECT, CIRC, LINE } from 'vclub/constants/whiteboardElements';

import styles from './ElementsPanel.css';

const enhance = compose(
  withHandlers({
    onClickForRect: props => () => props.onClick(RECT),
    onClickForLine: props => () => props.onClick(LINE),
    onClickForCircle: props => () => props.onClick(CIRC),
  })
);

function ElementsPanel(props) {
  const {
    onClickForRect, onClickForLine, onClickForCircle,
    nextFigureType,
  } = props;

  const gCN = (elm, nextFigureType) =>
    elm === nextFigureType
      ? styles.buttonCurrent
      : styles.button;

  return (

        <button onClick={onClickForRect} className={gCN(RECT, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <rect x="5" y="5" width="190" height="190" />
          </svg>
          {/* Rect */}
        </button>

        <button onClick={onClickForLine} className={gCN(LINE, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <line x1="20" y1="180" x2="180" y2="20" stroke="black" strokeWidth="20" />
          </svg>
          {/* Line */}
        </button>

        <button onClick={onClickForCircle} className={gCN(CIRC, nextFigureType)}>
          <svg viewBox="0 0 200 200">
            <circle cx="100" cy="100" r="100" />
          </svg>
        </button>

  );
}

ElementsPanel.propTypes = {
  onClickForRect: PropTypes.func,
  onClickForLine: PropTypes.func,
  onClickForCircle: PropTypes.func,
  nextFigureType: PropTypes.number,
};

export default enhance(ElementsPanel);
<|endoftext|>


<commit_before>const MAX_IMAGE_SIZE_BYTES = 16 * 1024 * 1024

export default function attachImage (this, e) {
  e.preventDefault()
  const file = e.target.files[0]
  const fr = new FileReader()
  fr.onload = () => {
    if (!fr.result.startsWith('data:image')) {
      this.setState({uploadError: 'Only images, please!'})
    } else if (fr.result.length > MAX_IMAGE_SIZE_BYTES) {
      this.setState({uploadError: `Only images under ${MAX_IMAGE_SIZE_BYTES} bytes, please!`})
    } else {
      this.setState({data: fr.result})
    }
  }
  fr.readAsDataURL(file)
}
<commit_msg>Fix attachImage util to work better<commit_after>const MAX_IMAGE_SIZE_BYTES = 100 * 1024

/**
 * To use:
 * import attachImage from "src/util/attachImage"
 *
 * And add the following to the component class:
 * onAttachImage = attachImage.bind(this)
 *
 * Now you can render an HTML5 file input, e.g.:
 * <input type="file" onChange={this.onAttachImage} />
 */
export default function attachImage (e) {
  e.preventDefault()
  const file = e.target.files[0]
  const fr = new FileReader()
  fr.onload = () => {
    if (!fr.result.startsWith('data:image')) {
      this.setState({uploadError: 'Only images, please!'})
    } else if (fr.result.length > MAX_IMAGE_SIZE_BYTES) {
      this.setState({uploadError: `Only images under ${MAX_IMAGE_SIZE_BYTES} bytes, please!`})
    } else {
      this.setState({data: fr.result})
    }
  }
  fr.readAsDataURL(file)
}
<|endoftext|>