<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { Button, Modal, FormGroup, ControlLabel, FormControl, InputGroup } from 'react-bootstrap'
import { translate } from 'react-i18next'
import Icon from '../Common/Icon'

class RenameTree extends React.Component {
  constructor(props) {
    super(props)

    this.renderTree = this.renderTree.bind(this)
    this.handleShow = this.handleShow.bind(this)
    this.handleClose = this.handleClose.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleError = this.handleError.bind(this)
    this.convertPathMapToTree = this.convertPathMapToTree.bind(this)
    this.checkTreeRenamable = this.checkTreeRenamable.bind(this)

    this.state = {
      show: false,
      newPath: RenameTree.getPath({ removeTrailingSlash: true }),
      pathMap: {},
      error: null,
      errors: {},
      renamable: false,
      removing: false,
      timeoutId: null,
    }

    // TODO: DropdownのReact化の際に消す？
    $("a[data-target='#renameTree']").click(this.handleShow)
  }

  static getPath(options = { removeTrailingSlash: false }) {
    const { removeTrailingSlash } = options
    let path
    path = decodeURIComponent(location.pathname)
    if (removeTrailingSlash) {
      path = RenameTree.removeTrailingSlash(path)
    }
    return path
  }

  static addTrailingSlash(string) {
    return string.endsWith('/') ? string : `${string}/`
  }

  static removeTrailingSlash(string) {
    return string.endsWith('/') ? string.substring(0, string.length - 1) : string
  }

  convertPathMapToTree(pathMap) {
    let tree = {}
    const generateNode = (path, name, children = {}) => ({
      [path]: { path, name, children },
    })
    const generateRoot = path => generateNode(path, path)
    const assignRecurcive = (tree, parents, path, name) => {
      if (parents.length === 0) {
        return generateNode(path, name)
      }
      let parent = parents[0]
      let children = tree[parent].children
      name = path.replace(parent, '')
      return {
        ...tree,
        [parent]: {
          ...tree[parent],
          children: {
            ...children,
            ...assignRecurcive(children, parents.slice(1), path, name),
          },
        },
      }
    }
    const treeName = path => path.replace(/\\/g, '/').replace(/\/[^/]*\/?$/, '')
    const getParents = (paths, path) =>
      paths
        .filter(
          p =>
            path !== p &&
            path.startsWith(RenameTree.removeTrailingSlash(p)) &&
            treeName(p) !== treeName(path) &&
            !p.endsWith('/'),
        )
        .sort()
    Object.keys(pathMap)
      .sort()
      .forEach(
        (path, index, paths) =>
          (tree = index === 0 ? generateRoot(path) : assignRecurcive(tree, getParents(paths, path), path)),
      )
    return tree
  }

  renderTree(pathMap, errors) {
    const tree = this.convertPathMapToTree(pathMap)

    const getErrors = path => errors[pathMap[path]]

    const renderRoot = tree => Object.values(tree).map(renderNode)

    const renderChanges = path => (

        <Icon name="arrow-right" /> {pathMap[path]}

    )

    const { t } = this.props
    const DottedLine = () => (

        <svg>
          <line x1="0" x2="100%" y2="50%" y1="50%" />
        </svg>

    )
    const renderNodeErrors = nodeErrors => (

        <DottedLine />
        {nodeErrors.map(e => t(e)).join(', ')}

    )

    const renderNode = function({ path, name, children }) {
      const isRoot = name === path
      const isEmpty = o => Object.keys(o).length === 0
      const nodeErrors = getErrors(path)
      const hasChildren = !isEmpty(children)
      const hasNodeErrors = nodeErrors !== undefined && nodeErrors.length > 0
      return (

            {name} {isRoot && renderChanges(path)}
            {hasNodeErrors && renderNodeErrors(nodeErrors)}

          {hasChildren &&
{renderRoot(children)}
}

      )
    }

    return renderRoot(tree)
  }

  handleClose() {
    this.setState({ show: false })
  }

  handleShow() {
    this.setState({ show: true })
  }

  handleChange(e) {
    clearTimeout(this.state.timeoutId)
    const timeoutId = setTimeout(() => this.checkTreeRenamable(), 600)
    this.setState({ newPath: e.target.value, timeoutId })
  }

  async checkTreeRenamable() {
    const { crowi } = this.props
    const { newPath } = this.state
    const path = RenameTree.getPath({ removeTrailingSlash: true })
    try {
      const data = await crowi.apiPost('/pages.checkTreeRenamable', { path, new_path: newPath })
      const { path_map: pathMap } = data
      // ${pathMap} has not ${path} key if location is PageList
      pathMap[path] = newPath
      this.setState({ pathMap, renamable: true, error: null })
    } catch (error) {
      this.handleError(error)
    }
  }

  async handleSubmit() {
    const { crowi } = this.props
    const { newPath } = this.state
    const path = RenameTree.getPath({ removeTrailingSlash: true })
    const createRedirect = 1
    this.setState({ removing: true })
    try {
      const data = await crowi.apiPost('/pages.renameTree', {
        path,
        new_path: newPath,
        create_redirect: createRedirect,
      })
      const { pages } = data
      const urls = pages.map(({ path }) => path)
      const exists = path => urls.includes(path)
      const redirect = to => () => (top.location.href = to)
      const pageUrl = `${newPath}?redirectFrom=${RenameTree.getPath()}`
      const listUrl = RenameTree.addTrailingSlash(newPath)
      setTimeout(redirect(exists(newPath) ? pageUrl : listUrl), 1000)
    } catch (error) {
      this.handleError(error)
    }
  }

  handleError(error) {
    const { info } = error
    let newState = { renamable: false, error: error.message, removing: false }
    if (info && Object.keys(info).length > 0) {
      const { path_map: pathMap, errors } = info
      const { newPath } = this.state
      const path = RenameTree.getPath({ removeTrailingSlash: true })
      // ${pathMap} has not ${path} key if location is PageList
      pathMap[path] = newPath
      this.setState({ ...newState, pathMap, errors })
    } else {
      this.setState(newState)
    }
  }

  render() {
    const { show, newPath, pathMap, error, errors, renamable, removing } = this.state
    const { t } = this.props
    return (
      <Modal show={show} onHide={this.handleClose}>
        <Modal.Header closeButton>
          <Modal.Title id="contained-modal-title-lg">{t('Rename tree')}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <FormGroup>
            <ControlLabel>{t('Current page name')}</ControlLabel>
            {RenameTree.getPath()}
          </FormGroup>
          <FormGroup>
            <ControlLabel>{t('New page name')}</ControlLabel>
            <InputGroup>
              <InputGroup.Addon>{location.origin}</InputGroup.Addon>
              <FormControl name="new_path" value={newPath} onChange={this.handleChange} />
            </InputGroup>
          </FormGroup>

{this.renderTree(pathMap, errors)}

        </Modal.Body>

        <Modal.Footer>
          {error && (

                <Icon name="times-circle" /> {t(error)}

          )}
          {removing && (

                 Page tree moved! Redirecting to new location.

          )}
          <Button type="submit" bsStyle="primary" onClick={this.handleSubmit} disabled={!renamable}>
            Rename!
          </Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

RenameTree.propTypes = {
  crowi: PropTypes.object.isRequired,
  t: PropTypes.func.isRequired,
}

export default translate()(RenameTree)
<commit_msg>Disable button when removing<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { Button, Modal, FormGroup, ControlLabel, FormControl, InputGroup } from 'react-bootstrap'
import { translate } from 'react-i18next'
import Icon from '../Common/Icon'

class RenameTree extends React.Component {
  constructor(props) {
    super(props)

    this.renderTree = this.renderTree.bind(this)
    this.handleShow = this.handleShow.bind(this)
    this.handleClose = this.handleClose.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleError = this.handleError.bind(this)
    this.convertPathMapToTree = this.convertPathMapToTree.bind(this)
    this.checkTreeRenamable = this.checkTreeRenamable.bind(this)

    this.state = {
      show: false,
      newPath: RenameTree.getPath({ removeTrailingSlash: true }),
      pathMap: {},
      error: null,
      errors: {},
      renamable: false,
      removing: false,
      timeoutId: null,
    }

    // TODO: DropdownのReact化の際に消す？
    $("a[data-target='#renameTree']").click(this.handleShow)
  }

  static getPath(options = { removeTrailingSlash: false }) {
    const { removeTrailingSlash } = options
    let path
    path = decodeURIComponent(location.pathname)
    if (removeTrailingSlash) {
      path = RenameTree.removeTrailingSlash(path)
    }
    return path
  }

  static addTrailingSlash(string) {
    return string.endsWith('/') ? string : `${string}/`
  }

  static removeTrailingSlash(string) {
    return string.endsWith('/') ? string.substring(0, string.length - 1) : string
  }

  convertPathMapToTree(pathMap) {
    let tree = {}
    const generateNode = (path, name, children = {}) => ({
      [path]: { path, name, children },
    })
    const generateRoot = path => generateNode(path, path)
    const assignRecurcive = (tree, parents, path, name) => {
      if (parents.length === 0) {
        return generateNode(path, name)
      }
      let parent = parents[0]
      let children = tree[parent].children
      name = path.replace(parent, '')
      return {
        ...tree,
        [parent]: {
          ...tree[parent],
          children: {
            ...children,
            ...assignRecurcive(children, parents.slice(1), path, name),
          },
        },
      }
    }
    const treeName = path => path.replace(/\\/g, '/').replace(/\/[^/]*\/?$/, '')
    const getParents = (paths, path) =>
      paths
        .filter(
          p =>
            path !== p &&
            path.startsWith(RenameTree.removeTrailingSlash(p)) &&
            treeName(p) !== treeName(path) &&
            !p.endsWith('/'),
        )
        .sort()
    Object.keys(pathMap)
      .sort()
      .forEach(
        (path, index, paths) =>
          (tree = index === 0 ? generateRoot(path) : assignRecurcive(tree, getParents(paths, path), path)),
      )
    return tree
  }

  renderTree(pathMap, errors) {
    const tree = this.convertPathMapToTree(pathMap)

    const getErrors = path => errors[pathMap[path]]

    const renderRoot = tree => Object.values(tree).map(renderNode)

    const renderChanges = path => (

        <Icon name="arrow-right" /> {pathMap[path]}

    )

    const { t } = this.props
    const DottedLine = () => (

        <svg>
          <line x1="0" x2="100%" y2="50%" y1="50%" />
        </svg>

    )
    const renderNodeErrors = nodeErrors => (

        <DottedLine />
        {nodeErrors.map(e => t(e)).join(', ')}

    )

    const renderNode = function({ path, name, children }) {
      const isRoot = name === path
      const isEmpty = o => Object.keys(o).length === 0
      const nodeErrors = getErrors(path)
      const hasChildren = !isEmpty(children)
      const hasNodeErrors = nodeErrors !== undefined && nodeErrors.length > 0
      return (

            {name} {isRoot && renderChanges(path)}
            {hasNodeErrors && renderNodeErrors(nodeErrors)}

          {hasChildren &&
{renderRoot(children)}
}

      )
    }

    return renderRoot(tree)
  }

  handleClose() {
    this.setState({ show: false })
  }

  handleShow() {
    this.setState({ show: true })
  }

  handleChange(e) {
    clearTimeout(this.state.timeoutId)
    const timeoutId = setTimeout(() => this.checkTreeRenamable(), 600)
    this.setState({ newPath: e.target.value, timeoutId })
  }

  async checkTreeRenamable() {
    const { crowi } = this.props
    const { newPath } = this.state
    const path = RenameTree.getPath({ removeTrailingSlash: true })
    try {
      const data = await crowi.apiPost('/pages.checkTreeRenamable', { path, new_path: newPath })
      const { path_map: pathMap } = data
      // ${pathMap} has not ${path} key if location is PageList
      pathMap[path] = newPath
      this.setState({ pathMap, renamable: true, error: null })
    } catch (error) {
      this.handleError(error)
    }
  }

  async handleSubmit() {
    const { crowi } = this.props
    const { newPath } = this.state
    const path = RenameTree.getPath({ removeTrailingSlash: true })
    const createRedirect = 1
    this.setState({ removing: true })
    try {
      const data = await crowi.apiPost('/pages.renameTree', {
        path,
        new_path: newPath,
        create_redirect: createRedirect,
      })
      const { pages } = data
      const urls = pages.map(({ path }) => path)
      const exists = path => urls.includes(path)
      const redirect = to => () => (top.location.href = to)
      const pageUrl = `${newPath}?redirectFrom=${RenameTree.getPath()}`
      const listUrl = RenameTree.addTrailingSlash(newPath)
      setTimeout(redirect(exists(newPath) ? pageUrl : listUrl), 1000)
    } catch (error) {
      this.handleError(error)
    }
  }

  handleError(error) {
    const { info } = error
    let newState = { renamable: false, error: error.message, removing: false }
    if (info && Object.keys(info).length > 0) {
      const { path_map: pathMap, errors } = info
      const { newPath } = this.state
      const path = RenameTree.getPath({ removeTrailingSlash: true })
      // ${pathMap} has not ${path} key if location is PageList
      pathMap[path] = newPath
      this.setState({ ...newState, pathMap, errors })
    } else {
      this.setState(newState)
    }
  }

  render() {
    const { show, newPath, pathMap, error, errors, renamable, removing } = this.state
    const { t } = this.props
    return (
      <Modal show={show} onHide={this.handleClose}>
        <Modal.Header closeButton>
          <Modal.Title id="contained-modal-title-lg">{t('Rename tree')}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <FormGroup>
            <ControlLabel>{t('Current page name')}</ControlLabel>
            {RenameTree.getPath()}
          </FormGroup>
          <FormGroup>
            <ControlLabel>{t('New page name')}</ControlLabel>
            <InputGroup>
              <InputGroup.Addon>{location.origin}</InputGroup.Addon>
              <FormControl name="new_path" value={newPath} onChange={this.handleChange} />
            </InputGroup>
          </FormGroup>

{this.renderTree(pathMap, errors)}

        </Modal.Body>

        <Modal.Footer>
          {error && (

                <Icon name="times-circle" /> {t(error)}

          )}
          {removing && (

                 Page tree moved! Redirecting to new location.

          )}
          <Button type="submit" bsStyle="primary" onClick={this.handleSubmit} disabled={!renamable || removing}>
            Rename!
          </Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

RenameTree.propTypes = {
  crowi: PropTypes.object.isRequired,
  t: PropTypes.func.isRequired,
}

export default translate()(RenameTree)
<|endoftext|>


<commit_before>import {state, string, props} from 'cerebral/tags'
import {set, when} from 'cerebral/operators'
import {httpGet} from 'cerebral-provider-http/operators'
import showFlash from '../../common/factories/showFlash'
import mergeUsers from './mergeUsers'

export default [
  when(state`admin.usersSortDir`, usersSortDir => usersSortDir === 'ascending'),
  {
    true: set(props`sortDir`, 'asc'),
    false: set(props`sortDir`, 'desc'),
  },
  set(
    props`sort`,
    string`sortby=${state`admin.usersSortBy`}&sortdir=${props`sortDir`}`
  ),
  set(
    props`pagination`,
    string`&page=${state`admin.currentPage`}&pagesize=${state`admin.pageSize`}`
  ),
  when(state`admin.searchString`, searchString => searchString !== ''),
  {
    true: set(props`search`, string`&search=${state`admin.searchString`}`),
    false: set(props`search`, ''),
  },
  httpGet(string`/users?${props`sort`}${props`pagination`}${props`search`}`),
  {
    success: [mergeUsers, set(state`admin.pages`, props`result.pages`)],
    error: showFlash('Could not fetch users from database', 'error'),
  },
]
<commit_msg>revert(client): switch back to sequence syntax<commit_after>import {sequence} from 'cerebral'
import {state, string, props} from 'cerebral/tags'
import {set, when} from 'cerebral/operators'
import {httpGet} from 'cerebral-provider-http/operators'
import showFlash from '../../common/factories/showFlash'
import mergeUsers from './mergeUsers'

export default sequence('Fetch users from database', [
  when(state`admin.usersSortDir`, usersSortDir => usersSortDir === 'ascending'),
  {
    true: set(props`sortDir`, 'asc'),
    false: set(props`sortDir`, 'desc'),
  },
  set(
    props`sort`,
    string`sortby=${state`admin.usersSortBy`}&sortdir=${props`sortDir`}`
  ),
  set(
    props`pagination`,
    string`&page=${state`admin.currentPage`}&pagesize=${state`admin.pageSize`}`
  ),
  when(state`admin.searchString`, searchString => searchString !== ''),
  {
    true: set(props`search`, string`&search=${state`admin.searchString`}`),
    false: set(props`search`, ''),
  },
  httpGet(string`/users?${props`sort`}${props`pagination`}${props`search`}`),
  {
    success: [mergeUsers, set(state`admin.pages`, props`result.pages`)],
    error: showFlash('Could not fetch users from database', 'error'),
  },
])
<|endoftext|>


<commit_before>var through     = require('through2');
var gutil       = require('gulp-util');
var fm          = require('front-matter');
var PluginError = gutil.PluginError;
var path        = require('path');
var fs           = require('fs');

module.exports = function(options) {
  var configs = [];

  function bufferContents(file, enc, cb) {
    var config;
    var content;

    if(file.isNull()) return cb(null, file);

    if(file.isBuffer()) {
      try {
        content = fm(String(file.contents));
      } catch (e) {
        return cb(new PluginError('Gulp Dynamic Routing', e));
      }

      if(content.attributes.name) {
        file.contents = new Buffer(content.body);
        config = content.attributes;
        var relativePath = path.relative(__dirname + path.sep + '..' + path.sep + options.root, file.path);
        config.path = '/' + relativePath.split(path.sep).join('/');
        configs.push(config);
      }
    }

    this.push(file);

    return cb();
  }

  function endStream(cb) {
    var self = this;
    var appPath = options.path;

    configs.sort(function(a, b) {
      return a.url < b.url;
    });

    fs.writeFile(appPath, 'var foundationRoutes = ' + JSON.stringify(configs) + '; \n', function(err) {
      if(err) throw err;
      cb();
    });

  }

  return through.obj(bufferContents, endStream);
};
<commit_msg>Using process cwd to get directory name, might need to switch to callsite<commit_after>var through     = require('through2');
var gutil       = require('gulp-util');
var fm          = require('front-matter');
var PluginError = gutil.PluginError;
var path        = require('path');
var fs           = require('fs');

module.exports = function(options) {
  var configs = [];
  var directory = process.cwd();

  function bufferContents(file, enc, cb) {
    var config;
    var content;

    if(file.isNull()) return cb(null, file);

    if(file.isBuffer()) {
      try {
        content = fm(String(file.contents));
      } catch (e) {
        return cb(new PluginError('Gulp Dynamic Routing', e));
      }

      if(content.attributes.name) {
        file.contents = new Buffer(content.body);
        config = content.attributes;
        var relativePath = path.relative(directory + path.sep + options.root, file.path);
        config.path = '/' + relativePath.split(path.sep).join('/');
        configs.push(config);
      }
    }

    this.push(file);

    return cb();
  }

  function endStream(cb) {
    var self = this;
    var appPath = options.path;

    configs.sort(function(a, b) {
      return a.url < b.url;
    });

    fs.writeFile(appPath, 'var foundationRoutes = ' + JSON.stringify(configs) + '; \n', function(err) {
      if(err) throw err;
      cb();
    });

  }

  return through.obj(bufferContents, endStream);
};
<|endoftext|>


<commit_before>"use strict";

import { assert, BigInteger, Buffer, check, util } from "verifyme_utility"

import Blinder from "../blinder"
import BlindSignaturePacket from "../../pgp/blind_signature_packet"
import ButunEcdsaBlindingContext from "./blinding_context"
import server from "../../server_requests"

/**
 * Representation of the ECDSA blinding algorithm presented by Ismail Butun and Mehmet Demirer
 * in "A blind digital signature scheme using elliptic curve digital signature algorithm"
 *
 * http://journals.tubitak.gov.tr/elektrik/issues/elk-13-21-4/elk-21-4-4-1102-1051.pdf
 *
 * The variable naming follows the algorithms notation.
 */
export default class ButunEcdsaBlinder extends Blinder
{
  constructor()
  {
    super();
  };

  /**
   * Initializes the internal {ButunEcdsaBlindingContext}.
   *
   * @param {KeyManager} key_manager
   *    A {KeyManager} containing the signers public key which is necessary
   *    to extract the elliptic curve public parameter.
   * @param {BigInteger} token
   *    This is used to validate the blinded request.
   */
  async initContext(key_manager, token)
  {
    assert(check.isKeyManagerForEcdsaSign(key_manager));
    assert(check.isBigInteger(token));

    const context = ButunEcdsaBlindingContext.fromKey(key_manager);
    context.blinding_factor = {
      a: await util.generateRandomScalar(context.curve),
      b: await util.generateRandomScalar(context.curve)
    };

    context.hashed_token = util.calculateSha512(token);

    this.context = context;
    this.key_manager = key_manager;
    this.token = token;
  }

  /**
   * Blinds the given message.
   *
   *    blinding_factor_a * message * signers_public_point * inverse_requester_public_point (mod N)
   *
   * @param {BigInteger} message
   *    The original message.
   * @param {{signer: Point, requester: Point}} public_points
   *    An {object} containing the requesters and
   *    signers public blinding points.
   *
   * @returns {BigInteger}
   *    The blinded message.
   */
  blind(message, public_points)
  {
    assert(check.isBigInteger(message));
    assert(check.isObject(public_points));
    assert(public_points.hasOwnProperty("signer") && check.isPoint(public_points.signer));
    assert(public_points.hasOwnProperty("requester") && check.isPoint(public_points.requester));
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const n = this.context.curve.n;
    const a = this.context.blinding_factor.a;

    const R = public_points.requester;
    const r = R.affineX.mod(n);
    const r_inv = r.modInverse(n);

    const Ŕ = public_points.signer;
    const ŕ = Ŕ.affineX.mod(n);

    return a.multiply(message).multiply(ŕ).multiply(r_inv).mod(n);
  }

  /**
   * Unblinds the given signed blinded message.
   *
   *    (signed_blinded_message * requester_public_point * inverse_signers_public_point)
   *    + (blinding_factor_b * original_message) (mod N)
   *
   * @param {BigInteger} message
   *    The signed blinded message.
   * @param {BigInteger} original_message
   *    The message to be signed.
   * @param {{signer: Point, requester: Point}} public_points
   *    An {object} containing the requesters and
   *    signers public blinding points.
   *
   * @returns {BigInteger}
   *    The unblinded signed message.
   */
  unblind(signed_blinded_message, original_message, public_points)
  {
    assert(check.isBigInteger(signed_blinded_message));
    assert(check.isBigInteger(original_message));
    assert(check.isObject(public_points));
    assert(public_points.hasOwnProperty("signer") && check.isPoint(public_points.signer));
    assert(public_points.hasOwnProperty("requester") && check.isPoint(public_points.requester));
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const n = this.context.curve.n;

    assert(signed_blinded_message.compareTo(BigInteger.ZERO) > 0);
    assert(signed_blinded_message.compareTo(n) < 0);

    const R = public_points.requester;
    const r = R.affineX.mod(n);

    const Ŕ = public_points.signer;
    const ŕ = Ŕ.affineX.mod(n);
    const ŕ_inv = ŕ.modInverse(n);

    const b = this.context.blinding_factor.b;
    const bm = b.multiply(original_message);

    return signed_blinded_message.multiply(r).multiply(ŕ_inv).add(bm).mod(n);
  }

  /**
   * Forges a Butun ecdsa based blind signature.
   *
   * To achieve this the prepared raw signature is blinded and send to the server.
   * The server signs the blinded message and the result is send back.
   * Afterwards the result is unblinded and inject into the given signature packet.
   *
   * Based on: http://journals.tubitak.gov.tr/elektrik/issues/elk-13-21-4/elk-21-4-4-1102-1051.pdf
   *
   * @param {BlindSignaturePacket} packet
   *    The prepared {BlindSignaturePacket} including the raw signature.
   */
  async forgeSignature(packet)
  {
    assert(packet instanceof BlindSignaturePacket);
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const hash = util.calculateSha512(packet.raw_signature);
    const message = packet.key.pub.trunc_hash(hash.toBuffer());

    const public_points = await this.requestPublicPoints();
    const blinded_message = this.blind(message, public_points);

    const signed_blinded_message = await server.requestButunEcdsaBlinding(blinded_message, this.context);
    const signed_message = this.unblind(signed_blinded_message, message, public_points);

    const signature = Buffer.concat([
      signed_message.to_mpi_buffer(),
      public_points.requester.getEncoded(false)
    ]);

    packet.sig = signature;
    packet.raw = packet.write_unframed();
  }

  /**
   * Calculates the public blinding information which are
   * Necessary to blind and unblind the message.
   *
   * @returns {{signer: Point, requester: Point}}
   *    Signers and requester public curve point.
   */
  async requestPublicPoints()
  {
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const curve = this.context.curve;
    const n = this.context.curve.n;
    const G = this.context.curve.G;
    const a = this.context.blinding_factor.a;
    const b = this.context.blinding_factor.b;

    const Ŕ = await server.requestButunEcdsaInitialization(this.context);
    assert(curve.isOnCurve(Ŕ));

    const ŕ = Ŕ.affineX.mod(n);
    assert(ŕ.compareTo(BigInteger.ZERO) > 0);
    assert(ŕ.compareTo(n) < 0);

    const aŔ = Ŕ.multiply(a);
    const bG = G.multiply(b);
    const R = aŔ.add(bG);
    assert(curve.isOnCurve(R));

    return { signer: Ŕ, requester: R };
  }
}
<commit_msg>Client Blinding: fix butun signature creation<commit_after>"use strict";

import { assert, BigInteger, Buffer, check, util } from "verifyme_utility"

import Blinder from "../blinder"
import BlindSignaturePacket from "../../pgp/blind_signature_packet"
import ButunEcdsaBlindingContext from "./blinding_context"
import server from "../../server_requests"

/**
 * Representation of the ECDSA blinding algorithm presented by Ismail Butun and Mehmet Demirer
 * in "A blind digital signature scheme using elliptic curve digital signature algorithm"
 *
 * http://journals.tubitak.gov.tr/elektrik/issues/elk-13-21-4/elk-21-4-4-1102-1051.pdf
 *
 * The variable naming follows the algorithms notation.
 */
export default class ButunEcdsaBlinder extends Blinder
{
  constructor()
  {
    super();
  };

  /**
   * Initializes the internal {ButunEcdsaBlindingContext}.
   *
   * @param {KeyManager} key_manager
   *    A {KeyManager} containing the signers public key which is necessary
   *    to extract the elliptic curve public parameter.
   * @param {BigInteger} token
   *    This is used to validate the blinded request.
   */
  async initContext(key_manager, token)
  {
    assert(check.isKeyManagerForEcdsaSign(key_manager));
    assert(check.isBigInteger(token));

    const context = ButunEcdsaBlindingContext.fromKey(key_manager);
    context.blinding_factor = {
      a: await util.generateRandomScalar(context.curve),
      b: await util.generateRandomScalar(context.curve)
    };

    context.hashed_token = util.calculateSha512(token);

    this.context = context;
    this.key_manager = key_manager;
    this.token = token;
  }

  /**
   * Blinds the given message.
   *
   *    blinding_factor_a * message * signers_public_point * inverse_requester_public_point (mod N)
   *
   * @param {BigInteger} message
   *    The original message.
   * @param {{signer: Point, requester: Point}} public_points
   *    An {object} containing the requesters and
   *    signers public blinding points.
   *
   * @returns {BigInteger}
   *    The blinded message.
   */
  blind(message, public_points)
  {
    assert(check.isBigInteger(message));
    assert(check.isObject(public_points));
    assert(public_points.hasOwnProperty("signer") && check.isPoint(public_points.signer));
    assert(public_points.hasOwnProperty("requester") && check.isPoint(public_points.requester));
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const n = this.context.curve.n;
    const a = this.context.blinding_factor.a;

    const R = public_points.requester;
    const r = R.affineX.mod(n);
    const r_inv = r.modInverse(n);

    const Ŕ = public_points.signer;
    const ŕ = Ŕ.affineX.mod(n);

    return a.multiply(message).multiply(ŕ).multiply(r_inv).mod(n);
  }

  /**
   * Unblinds the given signed blinded message.
   *
   *    (signed_blinded_message * requester_public_point * inverse_signers_public_point)
   *    + (blinding_factor_b * original_message) (mod N)
   *
   * @param {BigInteger} message
   *    The signed blinded message.
   * @param {BigInteger} original_message
   *    The message to be signed.
   * @param {{signer: Point, requester: Point}} public_points
   *    An {object} containing the requesters and
   *    signers public blinding points.
   *
   * @returns {BigInteger}
   *    The unblinded signed message.
   */
  unblind(signed_blinded_message, original_message, public_points)
  {
    assert(check.isBigInteger(signed_blinded_message));
    assert(check.isBigInteger(original_message));
    assert(check.isObject(public_points));
    assert(public_points.hasOwnProperty("signer") && check.isPoint(public_points.signer));
    assert(public_points.hasOwnProperty("requester") && check.isPoint(public_points.requester));
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const n = this.context.curve.n;

    assert(signed_blinded_message.compareTo(BigInteger.ZERO) > 0);
    assert(signed_blinded_message.compareTo(n) < 0);

    const R = public_points.requester;
    const r = R.affineX.mod(n);

    const Ŕ = public_points.signer;
    const ŕ = Ŕ.affineX.mod(n);
    const ŕ_inv = ŕ.modInverse(n);

    const b = this.context.blinding_factor.b;
    const bm = b.multiply(original_message);

    return signed_blinded_message.multiply(r).multiply(ŕ_inv).add(bm).mod(n);
  }

  /**
   * Forges a Butun ecdsa based blind signature.
   *
   * To achieve this the prepared raw signature is blinded and send to the server.
   * The server signs the blinded message and the result is send back.
   * Afterwards the result is unblinded and inject into the given signature packet.
   *
   * Based on: http://journals.tubitak.gov.tr/elektrik/issues/elk-13-21-4/elk-21-4-4-1102-1051.pdf
   *
   * @param {BlindSignaturePacket} packet
   *    The prepared {BlindSignaturePacket} including the raw signature.
   */
  async forgeSignature(packet)
  {
    assert(packet instanceof BlindSignaturePacket);
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const hash = util.calculateSha512(packet.raw_signature);
    const message = packet.key.pub.trunc_hash(hash.toBuffer());

    const public_points = await this.requestPublicPoints();
    const blinded_message = this.blind(message, public_points);

    const signed_blinded_message = await server.requestButunEcdsaBlinding(blinded_message, this.context);
    const signed_message = this.unblind(signed_blinded_message, message, public_points);

    const signature = Buffer.concat([
      signed_message.to_mpi_buffer(),
      this.context.curve.point_to_mpi_buffer(public_points.requester)
    ]);

    packet.sig = signature;
    packet.raw = packet.write_unframed();
  }

  /**
   * Calculates the public blinding information which are
   * Necessary to blind and unblind the message.
   *
   * @returns {{signer: Point, requester: Point}}
   *    Signers and requester public curve point.
   */
  async requestPublicPoints()
  {
    assert(ButunEcdsaBlindingContext.isValidBlindingContext(this.context));

    const curve = this.context.curve;
    const n = this.context.curve.n;
    const G = this.context.curve.G;
    const a = this.context.blinding_factor.a;
    const b = this.context.blinding_factor.b;

    const Ŕ = await server.requestButunEcdsaInitialization(this.context);
    assert(curve.isOnCurve(Ŕ));

    const ŕ = Ŕ.affineX.mod(n);
    assert(ŕ.compareTo(BigInteger.ZERO) > 0);
    assert(ŕ.compareTo(n) < 0);

    const aŔ = Ŕ.multiply(a);
    const bG = G.multiply(b);
    const R = aŔ.add(bG);
    assert(curve.isOnCurve(R));

    return { signer: Ŕ, requester: R };
  }
}
<|endoftext|>


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

var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/tr');

bcv.set_options({
  'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

String.prototype.replaceSplice = function (start, end, string) {
  return this.substr(0,start) + string + this.substr(end);
};

function process_line (line) {
  line = line + "\n"; // restore that which readline rightfully stole
  if (!line.match(/^(#|\[\^\d+\]:) /)) { // skip footnotes and headings for now
    var offset = 0;
    var lastEnd = 0;
    var lastOsis = null;
    var refs = bcv.parse(line).osis_and_indices();
    refs.forEach(function(ref) {
      var context = ( lastEnd + 4 ) >= ref.indices[0] ? lastOsis : null;
      var pretty = formatter('yc-long', ref.osis, context);
      lastEnd = ref.indices[1];
      lastOsis = ref.osis;
      line = line.replaceSplice(ref.indices[0] + offset, ref.indices[1] + offset, pretty);
      offset += ref.indices[0] - ref.indices[1] + pretty.length;
    });
  }
  process.stdout.write(line);
}

rl.on('line', process_line);
<commit_msg>Process chains of references in single lumps<commit_after>#!/usr/bin/env node

var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/tr');

bcv.set_options({
  'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

String.prototype.replaceSplice = function (start, end, string) {
  return this.substr(0,start) + string + this.substr(end);
};

function isChained(context, ref, line, offset) {
  var dist = ref.indices[0] - context.indices[1];
  if ( dist >= 4 ) { return false; }
  var connector = line.substr(context.indices[1] + offset, dist);
  return (/^[;, ]+$/).test(connector);
}

function mergeRefs(a, b) {
  return {
    osis: a.osis + "," + b.osis,
    translations: a.translations,
    indices: [ a.indices[0], b.indices[1] ]
  };
}

function process_line (line) {
  line = line + "\n"; // restore that which readline rightfully stole
  if (!line.match(/^(#|\[\^\d+\]:) /)) { // skip footnotes and headings for now
    var offset = 0;
    var previousOffset = 0;
    var context = null;
    var refs = bcv.parse(line).osis_and_indices();
    refs.forEach(function(ref) {
      if ( context && isChained(context, ref, line, offset) ) {
        var mref = mergeRefs(context, ref);
        ref = mref;
        offset -= previousOffset;
      } else {
        previousOffset = 0;
      }
      var pretty = formatter('yc-long', ref.osis);
      line = line.replaceSplice(ref.indices[0] + offset, ref.indices[1] + offset + previousOffset, pretty);
      previousOffset = ref.indices[0] - ref.indices[1] + pretty.length;
      offset += previousOffset;
      context = ref;
    });
  }
  process.stdout.write(line);
}

rl.on('line', process_line);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { createQuiz } from '../../services/firebase/createQuiz'

export class AddQuiz extends Component {
  constructor() {
    super();
    this.state = {
      owner: '',
      subject: '',
      question: '',
      answer: '',
      choice1: '',
      choice2: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    createQuiz(this);
  }

  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          Subject: <input type="text" name="subject" placeholder="subject" onChange={this.handleChange} value={this.state.subject} />

          Question: <input type="text" name="question" placeholder="question" onChange={this.handleChange} value={this.state.question} />

          Answer: <input type="text" name="answer" placeholder="answer" onChange={this.handleChange} value={this.state.answer} />

          Choice1: <input type="text" name="choice1" placeholder="choice1" onChange={this.handleChange} value={this.state.choice1} />

          Choice2: <input type="text" name="choice2" placeholder="choice2" onChange={this.handleChange} value={this.state.choice2} />

          <button>Add Quiz</button>
        </form>

    )
  }
}<commit_msg>Change input field to blank after click add quiz<commit_after>import React, { Component } from 'react'
import { createQuiz } from '../../services/firebase/createQuiz'

export class AddQuiz extends Component {
  constructor() {
    super();
    this.state = {
      owner: '',
      subject: '',
      question: '',
      answer: '',
      choice1: '',
      choice2: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    createQuiz(this).then(this.setState.bind(this));
  }

  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          Subject: <input type="text" name="subject" placeholder="subject" onChange={this.handleChange} value={this.state.subject} />

          Question: <input type="text" name="question" placeholder="question" onChange={this.handleChange} value={this.state.question} />

          Answer: <input type="text" name="answer" placeholder="answer" onChange={this.handleChange} value={this.state.answer} />

          Choice1: <input type="text" name="choice1" placeholder="choice1" onChange={this.handleChange} value={this.state.choice1} />

          Choice2: <input type="text" name="choice2" placeholder="choice2" onChange={this.handleChange} value={this.state.choice2} />

          <button>Add Quiz</button>
        </form>

    )
  }
}<|endoftext|>


<commit_before>#!/bin/env node

'use strict';

const chokidar = require('chokidar');
const exec = require('child_process').exec;
const fs = require('fs-extra');
const path = require('path');
const program = require('commander');

const debug = require('../src/util/debug')('bin:import');
const die = require('../src/util/die');
const home = require('../src/config/home');
const imp = require('../src/import/import');
const log = require('../src/couch/log');

var processChain = Promise.resolve();
const importFiles = {};
const createdDirs = {};

program
    .usage('<file>')
    .option('-l, --limit <number>', 'Limit of files to import')
    .option('-w, --watch', 'Watch files')
    .parse(process.argv);

let prom = Promise.resolve();
if (program.args[0]) {
    debug(`file argument: ${program.args[0]}`);
    // TODO add 2 arguments: db and import names
    throw new Error('not ready');
    //const file = path.resolve(program.args[0]);
    //
    //prom = prom.then(() => {
    //    return imp.import(config, file);
    //});
} else if (!program.watch) {
    debug('no watch');
    // import all
    let homeDir = getHomeDir();

    prom = prom.then(() => findFiles(homeDir))
        .then(paths => {
            const limit = +program.limit || paths.length;
            debug(`limit is ${limit}`);
            var i = 0, count = 0;
            var p = Promise.resolve();
            while(count < limit && i < paths.length) {
                let file;
                if(file = checkFile(homeDir, paths[i])) {
                    count++;
                    p = processFile(file.database, file.importName, homeDir, paths[i]);
                }
                i++;
            }
            return p;
        });
} else if (program.watch) {
    // watch files to import
    let homeDir = getHomeDir();
    debug(`watch ${homeDir}`);
    chokidar.watch(homeDir, {
        ignored: /[\/\\](\.|processed|node_modules)}/,
        persistent: true
    }).on('all', function (event, p) {
        debug.trace(`watch event: ${event} - ${p}`);
        let file = checkFile(homeDir, p);
        if (event !== 'add' && event !== 'change' || !file) {
            return;
        }
        processFile(file.database, file.importName, homeDir, p);
    });
} else {
    console.error('UNREACHABLE');
    process.exit(1);
}

prom.catch(function (err) {
    console.error(err.message || err);
    process.exit(1);
});

function findFiles(homeDir) {
    return new Promise(function (resolve, reject) {
        exec("find . -maxdepth 4 -mindepth 4 -type f -not -regex '.*/\\(processed\\|node_modules\\|\\.\\).*'", {
            cwd: homeDir,
            maxBuffer: 10 * 1000 * 1024
        }, function (err, stdout) {
            if (err) return reject(err);
            let paths = stdout.split('\n');
            paths = paths.filter(path => path);
            debug(`findFiles found ${paths.length} files`);
            resolve(paths);
        });
    });
}

function getHomeDir() {
    let homeDir = home.get('homeDir');
    if (!homeDir) {
        die('homeDir must be set to import all');
    }
    return homeDir;
}

function checkFile(homeDir, p) {
    p = path.resolve(homeDir, p);
    const relpath = path.relative(homeDir, p);
    const elements = relpath.split('/');
    if (elements.length !== 4) return false;
    if(elements[2] !== 'to_process') return false;

    if (hasImportFile(p)) {
        return {
            database: elements[0],
            importName: elements[1]
        };
    }
}

function processFile(database, importName, homeDir, p) {
    debug.trace(`process file ${p}`);
    p = path.resolve(homeDir, p);
    let parsedPath = path.parse(p);

    processChain = processChain.then(() => {
        return imp.import(database, importName, p);
    }).then(() => {
        // mv to processed
        return new Promise(function (resolve, reject) {
            let dir = path.join(parsedPath.dir, '../processed/' + getMonth());
            createDir(dir);
            fs.rename(p, path.join(dir, parsedPath.base), function (err) {
                if (err) return reject(err);
                resolve();
            });
        });
    }).catch(() => {
        // mv to errored
        return new Promise(function (resolve, reject) {
            let dir = path.join(parsedPath.dir, '../errored/' + getMonth());
            createDir(dir);
            fs.rename(p, path.join(dir, parsedPath.base), function (err) {
                if (err) return reject(err);
                resolve();
            });
        });
    });

    return processChain;
}

function hasImportFile(p) {
    const importFile = path.resolve(p, '../../import.js');
    if(importFiles[p]) return true;

    try {
        fs.accessSync(importFile);
        return true;
    } catch (e) {
        return false;
    }
}

function createDir(dir) {
    if(createdDirs[dir]) return;

    fs.mkdirpSync(dir);
    createdDirs[dir] = true;
}

function getMonth() {
    var now = new Date();
    return now.getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2);
}
<commit_msg>fix ignore more files<commit_after>#!/bin/env node

'use strict';

const chokidar = require('chokidar');
const exec = require('child_process').exec;
const fs = require('fs-extra');
const path = require('path');
const program = require('commander');

const debug = require('../src/util/debug')('bin:import');
const die = require('../src/util/die');
const home = require('../src/config/home');
const imp = require('../src/import/import');
const log = require('../src/couch/log');

var processChain = Promise.resolve();
const importFiles = {};
const createdDirs = {};

program
    .usage('<file>')
    .option('-l, --limit <number>', 'Limit of files to import')
    .option('-w, --watch', 'Watch files')
    .parse(process.argv);

let prom = Promise.resolve();
if (program.args[0]) {
    debug(`file argument: ${program.args[0]}`);
    // TODO add 2 arguments: db and import names
    throw new Error('not ready');
    //const file = path.resolve(program.args[0]);
    //
    //prom = prom.then(() => {
    //    return imp.import(config, file);
    //});
} else if (!program.watch) {
    debug('no watch');
    // import all
    let homeDir = getHomeDir();

    prom = prom.then(() => findFiles(homeDir))
        .then(paths => {
            const limit = +program.limit || paths.length;
            debug(`limit is ${limit}`);
            var i = 0, count = 0;
            var p = Promise.resolve();
            while(count < limit && i < paths.length) {
                let file;
                if(file = checkFile(homeDir, paths[i])) {
                    count++;
                    p = processFile(file.database, file.importName, homeDir, paths[i]);
                }
                i++;
            }
            return p;
        });
} else if (program.watch) {
    // watch files to import
    let homeDir = getHomeDir();
    debug(`watch ${homeDir}`);
    chokidar.watch(homeDir, {
        ignored: /[\/\\](\.|processed|errored|node_modules)/,
        persistent: true
    }).on('all', function (event, p) {
        debug.trace(`watch event: ${event} - ${p}`);
        let file = checkFile(homeDir, p);
        if (event !== 'add' && event !== 'change' || !file) {
            return;
        }
        processFile(file.database, file.importName, homeDir, p);
    });
} else {
    console.error('UNREACHABLE');
    process.exit(1);
}

prom.catch(function (err) {
    console.error(err.message || err);
    process.exit(1);
});

function findFiles(homeDir) {
    return new Promise(function (resolve, reject) {
        exec("find . -maxdepth 4 -mindepth 4 -type f -not -regex '.*/\\(processed\\|node_modules\\|\\.\\).*'", {
            cwd: homeDir,
            maxBuffer: 10 * 1000 * 1024
        }, function (err, stdout) {
            if (err) return reject(err);
            let paths = stdout.split('\n');
            paths = paths.filter(path => path);
            debug(`findFiles found ${paths.length} files`);
            resolve(paths);
        });
    });
}

function getHomeDir() {
    let homeDir = home.get('homeDir');
    if (!homeDir) {
        die('homeDir must be set to import all');
    }
    return homeDir;
}

function checkFile(homeDir, p) {
    p = path.resolve(homeDir, p);
    const relpath = path.relative(homeDir, p);
    const elements = relpath.split('/');
    if (elements.length !== 4) return false;
    if(elements[2] !== 'to_process') return false;

    if (hasImportFile(p)) {
        return {
            database: elements[0],
            importName: elements[1]
        };
    }
}

function processFile(database, importName, homeDir, p) {
    debug.trace(`process file ${p}`);
    p = path.resolve(homeDir, p);
    let parsedPath = path.parse(p);

    processChain = processChain.then(() => {
        return imp.import(database, importName, p);
    }).then(() => {
        // mv to processed
        return new Promise(function (resolve, reject) {
            let dir = path.join(parsedPath.dir, '../processed/' + getMonth());
            createDir(dir);
            fs.rename(p, path.join(dir, parsedPath.base), function (err) {
                if (err) return reject(err);
                resolve();
            });
        });
    }).catch(() => {
        // mv to errored
        return new Promise(function (resolve, reject) {
            let dir = path.join(parsedPath.dir, '../errored/' + getMonth());
            createDir(dir);
            fs.rename(p, path.join(dir, parsedPath.base), function (err) {
                if (err) return reject(err);
                resolve();
            });
        });
    });

    return processChain;
}

function hasImportFile(p) {
    const importFile = path.resolve(p, '../../import.js');
    if(importFiles[p]) return true;

    try {
        fs.accessSync(importFile);
        return true;
    } catch (e) {
        return false;
    }
}

function createDir(dir) {
    if(createdDirs[dir]) return;

    fs.mkdirpSync(dir);
    createdDirs[dir] = true;
}

function getMonth() {
    var now = new Date();
    return now.getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2);
}
<|endoftext|>


<commit_before>// https://github.com/nteract/nteract/issues/389
import CodeMirror from 'codemirror';

import 'codemirror/mode/meta';
import 'codemirror/mode/python/python';

CodeMirror.defineMode('ipython', (conf, parserConf) => {
  const ipythonConf = Object.assign({}, parserConf, {
    name: 'python',
    singleOperators: new RegExp('^[\\+\\-\\*/%&|@\\^~<>!\\?]'),
    identifiers: new RegExp('^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*'), // Technically Python3
  });
  return CodeMirror.getMode(conf, ipythonConf);
}, 'python');

CodeMirror.defineMIME('text/x-ipython', 'ipython');

// omex

function wordRegexp(words) {
  return new RegExp('^((' + words.join(')|(') + '))\\b');
}

const wordOperators = wordRegexp(['a', 'is']);
const commonKeywords = [
  // antimony
  'model', 'end', 'species', 'var', 'const', 'compartment', 'substanceOnly', 'function', 'unit',
  // phrasedml
  'simulate', 'run', 'repeat', 'plot', 'report', 'for', 'in', 'with'
  ];
const commonBuiltins = [];

CodeMirror.defineMode('omex', function() {
  const myKeywords = commonKeywords, myBuiltins = commonBuiltins;

  const keywords = wordRegexp(myKeywords);
  const builtins = wordRegexp(myBuiltins);
  const identifiers = /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
  const boundary_species = /^\$[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;

  return {
    startState: function() {return {inString: false};},
    token: function(stream, state) {
      // Handle comments
      if (!state.inString && (stream.peek() == '#' || stream.match('//'))) {
        stream.skipToEnd();
        return 'comment';
      }

      // Handle line magics
      if (!state.inString && (stream.peek() == '%')) {
        stream.skipToEnd();
        return 'string';
      }

      // Handle strings
      if (!state.inString && stream.peek() == '"') {
        stream.next();            // Skip quote
        state.inString = true;    // Update state
      }

      if (state.inString) {
        if (stream.skipTo('"')) { // Quote found on this line
          stream.next();          // Skip quote
          state.inString = false; // Clear flag
        } else {
          stream.skipToEnd();    // Rest of line is string
        }
        return 'string';          // Token style
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        let floatLiteral = false;
        // Floats
        if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be 'imaginary'
          stream.eat(/J/i);
          return 'number';
        }
        // Integers
        let intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01_]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
          // Decimal literals may be 'imaginary'
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be 'long'
          stream.eat(/L/i);
          return 'number';
        }
      }

      // Handle SBO terms
      if (stream.match(/^SBO:[0-9]+/)) {
          return 'number';
      }

      // Handle keywords
      if (stream.match(keywords)) {
        return 'keyword';
      }

      // Handle identifiers
      if (stream.match(identifiers)) {
        stream.eatSpace()
        if (stream.peek() == ':') {
          // reaction
          return 'def'
        }
        return 'variable';
      }
      if (stream.match(boundary_species)) {
        return 'variable-2';
      }

      // Handle reaction arrows
      if (stream.match('->') || stream.match('=>')) {
        return 'operator';
      }

      // Handle operators
      if (stream.match(/[*/+-]/)) {
        return 'operator';
      }

      stream.next();
      return null; // Unstyled token
    }
  };
});

CodeMirror.registerHelper('hintWords', 'antimony', commonKeywords.concat(commonBuiltins));
<commit_msg>handle absolute uris<commit_after>// https://github.com/nteract/nteract/issues/389
import CodeMirror from 'codemirror';

import 'codemirror/mode/meta';
import 'codemirror/mode/python/python';

CodeMirror.defineMode('ipython', (conf, parserConf) => {
  const ipythonConf = Object.assign({}, parserConf, {
    name: 'python',
    singleOperators: new RegExp('^[\\+\\-\\*/%&|@\\^~<>!\\?]'),
    identifiers: new RegExp('^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*'), // Technically Python3
  });
  return CodeMirror.getMode(conf, ipythonConf);
}, 'python');

CodeMirror.defineMIME('text/x-ipython', 'ipython');

// omex

function wordRegexp(words) {
  return new RegExp('^((' + words.join(')|(') + '))\\b');
}

const wordOperators = wordRegexp(['a', 'is']);
const commonKeywords = [
  // antimony
  'model', 'end', 'species', 'var', 'const', 'compartment', 'substanceOnly', 'function', 'unit',
  // phrasedml
  'simulate', 'run', 'repeat', 'plot', 'report', 'for', 'in', 'with'
  ];
const commonBuiltins = [];

CodeMirror.defineMode('omex', function() {
  const myKeywords = commonKeywords, myBuiltins = commonBuiltins;

  const keywords = wordRegexp(myKeywords);
  const builtins = wordRegexp(myBuiltins);
  const identifiers = /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
  const boundary_species = /^\$[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;

  return {
    startState: function() {return {inString: false};},
    token: function(stream, state) {
      // Handle absolute URIs
      if (stream.match(/^<http[^>]+>/)) {
          return 'string';
      }

      // Handle comments
      if (!state.inString && (stream.peek() == '#' || stream.match('//'))) {
        stream.skipToEnd();
        return 'comment';
      }

      // Handle line magics
      if (!state.inString && (stream.peek() == '%')) {
        stream.skipToEnd();
        return 'string';
      }

      // Handle strings
      if (!state.inString && stream.peek() == '"') {
        stream.next();            // Skip quote
        state.inString = true;    // Update state
      }

      if (state.inString) {
        if (stream.skipTo('"')) { // Quote found on this line
          stream.next();          // Skip quote
          state.inString = false; // Clear flag
        } else {
          stream.skipToEnd();    // Rest of line is string
        }
        return 'string';          // Token style
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        let floatLiteral = false;
        // Floats
        if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be 'imaginary'
          stream.eat(/J/i);
          return 'number';
        }
        // Integers
        let intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01_]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
          // Decimal literals may be 'imaginary'
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be 'long'
          stream.eat(/L/i);
          return 'number';
        }
      }

      // Handle SBO terms
      if (stream.match(/^SBO:[0-9]+/)) {
          return 'number';
      }

      // Handle keywords
      if (stream.match(keywords)) {
        return 'keyword';
      }

      // Handle identifiers
      if (stream.match(identifiers)) {
        stream.eatSpace()
        if (stream.peek() == ':') {
          // reaction
          return 'def'
        }
        return 'variable';
      }
      if (stream.match(boundary_species)) {
        return 'variable-2';
      }

      // Handle reaction arrows
      if (stream.match('->') || stream.match('=>')) {
        return 'operator';
      }

      // Handle operators
      if (stream.match(/[*/+-]/)) {
        return 'operator';
      }

      stream.next();
      return null; // Unstyled token
    }
  };
});

CodeMirror.registerHelper('hintWords', 'antimony', commonKeywords.concat(commonBuiltins));
<|endoftext|>


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

const lib = require('../index');
const AffineShapes = lib.AffineShapes;
const Intersection = lib.Intersection;
const Point2D = lib.Point2D;
const Matrix2D = lib.Matrix2D;

// define line
const line = {
    p1: new Point2D(40, 5),
    p2: new Point2D(70, 150)
};

// define rotated ellipse
const ellipse = {
    center: new Point2D(110, 60),
    radiusX: 100,
    radiusY: 50,
    angle: 10
};

// rotate the line into the ellipse's axis-aligned coordinate system
const radians = ellipse.angle * Math.PI / 180.0;
const rotation = Matrix2D.rotation(-radians);
const rotated_line = {
    p1: line.p1.transform(rotation),
    p2: line.p2.transform(rotation)
};

// find intersections
const result = Intersection.intersectEllipseLine(
    ellipse.center, ellipse.radiusX, ellipse.radiusY,
    rotated_line.p1, rotated_line.p2
);

// build SVG file showing the shapes, the center point, and intersection points
const intersectionSVG = result.points.map(p => {
    return `<circle cx="${p.x.toFixed(3)}" cy="${p.y.toFixed(3)}" r="2" stroke="red" fill="none"/>`
}).join("\n    ");

//
// NOTE: This SVG transforms the intersection points back into the original
// coordinate system. If you need to do that in your code, use something like
// the following:
//
// const unrotation = Matrix2D.rotation(radians);
// const unrotated_points = result.points(p => p.transform(unrotation));
//

const svg = `<svg xmlns="http://www.w3.org/2000/svg">
  <g transform="translate(10,10)">
    <g transform="rotate(${ellipse.angle})">
        <g transform="translate(${ellipse.center.x}, ${ellipse.center.y})">
            <ellipse rx="${ellipse.radiusX}" ry="${ellipse.radiusY}" stroke="blue" fill="none"/>
            <circle r="2" stroke="blue" fill="none"/>
        </g>
        ${intersectionSVG}
    </g>
    <line x1="${line.p1.x}" y1="${line.p1.y}" x2="${line.p2.x}" y2="${line.p2.y}" stroke="green"/>
  </g>
</svg>`

console.log(svg);
<commit_msg>No longer using AffineShapes<commit_after>#!/usr/bin/env node

const lib = require('../index');
const Intersection = lib.Intersection;
const Point2D = lib.Point2D;
const Matrix2D = lib.Matrix2D;

// define line
const line = {
    p1: new Point2D(40, 5),
    p2: new Point2D(70, 150)
};

// define rotated ellipse
const ellipse = {
    center: new Point2D(110, 60),
    radiusX: 100,
    radiusY: 50,
    angle: 10
};

// rotate the line into the ellipse's axis-aligned coordinate system
const radians = ellipse.angle * Math.PI / 180.0;
const rotation = Matrix2D.rotation(-radians);
const rotated_line = {
    p1: line.p1.transform(rotation),
    p2: line.p2.transform(rotation)
};

// find intersections
const result = Intersection.intersectEllipseLine(
    ellipse.center, ellipse.radiusX, ellipse.radiusY,
    rotated_line.p1, rotated_line.p2
);

// build SVG file showing the shapes, the center point, and intersection points
const intersectionSVG = result.points.map(p => {
    return `<circle cx="${p.x.toFixed(3)}" cy="${p.y.toFixed(3)}" r="2" stroke="red" fill="none"/>`
}).join("\n    ");

//
// NOTE: This SVG transforms the intersection points back into the original
// coordinate system. If you need to do that in your code, use something like
// the following:
//
// const unrotation = Matrix2D.rotation(radians);
// const unrotated_points = result.points(p => p.transform(unrotation));
//

const svg = `<svg xmlns="http://www.w3.org/2000/svg">
  <g transform="translate(10,10)">
    <g transform="rotate(${ellipse.angle})">
        <g transform="translate(${ellipse.center.x}, ${ellipse.center.y})">
            <ellipse rx="${ellipse.radiusX}" ry="${ellipse.radiusY}" stroke="blue" fill="none"/>
            <circle r="2" stroke="blue" fill="none"/>
        </g>
        ${intersectionSVG}
    </g>
    <line x1="${line.p1.x}" y1="${line.p1.y}" x2="${line.p2.x}" y2="${line.p2.y}" stroke="green"/>
  </g>
</svg>`

console.log(svg);
<|endoftext|>


<commit_before>import React from 'react';
import CheckboxTree from 'react-checkbox-tree';

const nodes = [
    {
        value: '/app',
        label: 'app',
        children: [
            {
                value: '/app/Http',
                label: 'Http',
                children: [
                    {
                        value: '/app/Http/Controllers',
                        label: 'Controllers',
                        children: [{
                            value: '/app/Http/Controllers/WelcomeController.js',
                            label: 'WelcomeController.js',
                        }],
                    },
                    {
                        value: '/app/Http/routes.js',
                        label: 'routes.js',
                    },
                ],
            },
            {
                value: '/app/Providers',
                label: 'Providers',
                children: [{
                    value: '/app/Http/Providers/EventServiceProvider.js',
                    label: 'EventServiceProvider.js',
                }],
            },
        ],
    },
    {
        value: '/config',
        label: 'config',
        children: [
            {
                value: '/config/app.js',
                label: 'app.js',
            },
            {
                value: '/config/database.js',
                label: 'database.js',
            },
        ],
    },
    {
        value: '/public',
        label: 'public',
        children: [
            {
                value: '/public/assets/',
                label: 'assets',
                children: [{
                    value: '/public/assets/style.css',
                    label: 'style.css',
                }],
            },
            {
                value: '/public/index.html',
                label: 'index.html',
            },
        ],
    },
    {
        value: '/.env',
        label: '.env',
    },
    {
        value: '/.gitignore',
        label: '.gitignore',
    },
    {
        value: '/README.md',
        label: 'README.md',
    },
];

class FilterExample extends React.Component {
    constructor() {
        super();

        this.state = {
            checked: [
                '/app/Http/Controllers/WelcomeController.js',
                '/app/Http/routes.js',
                '/public/assets/style.css',
                '/public/index.html',
                '/.gitignore',
            ],
            expanded: [
                '/app',
            ],
            filterText: "",
            nodes: nodes,
            nodesFiltered: nodes
        };

        this.onCheck = this.onCheck.bind(this);
        this.onExpand = this.onExpand.bind(this);
        this.setFilterText = this.setFilterText.bind(this);
        this.filterTree = this.filterTree.bind(this);
        this.nodeFilter = this.nodeFilter.bind(this);
    }

    onCheck(checked) {
        this.setState({ checked });
    }

    onExpand(expanded) {
        this.setState({ expanded });
    }

    nodeFilter (node: Node) {
        const children = (node.children || []).map(this.nodeFilter).filter(c => c !== null);

        return node.label.indexOf(this.state.filterText) !== -1 || children.length ? {...node, children: children } : null;
    }

    filterTree () {
        if (!this.state.filterText) {
            return this.setState({
                nodesFiltered: this.state.nodes
            });
        }

        const nodesFiltered = this.state.nodes.map(this.nodeFilter).filter(n => n !== null);

        this.setState({
            nodesFiltered: nodesFiltered
        });
    }

    setFilterText(e) {
        this.setState({filterText: e.target.value}, this.filterTree);
    }

    render() {
        const { checked, expanded } = this.state;

        return (

                <input type="text" placeholder="Search" value={ this.state.filterText } onChange={ this.setFilterText } />
                <CheckboxTree
                    checked={checked}
                    expanded={expanded}
                    nodes={this.state.nodesFiltered}
                    onCheck={this.onCheck}
                    onExpand={this.onExpand}
                />

        );
    }
}

export default FilterExample;
<commit_msg>Using single quotes<commit_after>import React from 'react';
import CheckboxTree from 'react-checkbox-tree';

const nodes = [
    {
        value: '/app',
        label: 'app',
        children: [
            {
                value: '/app/Http',
                label: 'Http',
                children: [
                    {
                        value: '/app/Http/Controllers',
                        label: 'Controllers',
                        children: [{
                            value: '/app/Http/Controllers/WelcomeController.js',
                            label: 'WelcomeController.js',
                        }],
                    },
                    {
                        value: '/app/Http/routes.js',
                        label: 'routes.js',
                    },
                ],
            },
            {
                value: '/app/Providers',
                label: 'Providers',
                children: [{
                    value: '/app/Http/Providers/EventServiceProvider.js',
                    label: 'EventServiceProvider.js',
                }],
            },
        ],
    },
    {
        value: '/config',
        label: 'config',
        children: [
            {
                value: '/config/app.js',
                label: 'app.js',
            },
            {
                value: '/config/database.js',
                label: 'database.js',
            },
        ],
    },
    {
        value: '/public',
        label: 'public',
        children: [
            {
                value: '/public/assets/',
                label: 'assets',
                children: [{
                    value: '/public/assets/style.css',
                    label: 'style.css',
                }],
            },
            {
                value: '/public/index.html',
                label: 'index.html',
            },
        ],
    },
    {
        value: '/.env',
        label: '.env',
    },
    {
        value: '/.gitignore',
        label: '.gitignore',
    },
    {
        value: '/README.md',
        label: 'README.md',
    },
];

class FilterExample extends React.Component {
    constructor() {
        super();

        this.state = {
            checked: [
                '/app/Http/Controllers/WelcomeController.js',
                '/app/Http/routes.js',
                '/public/assets/style.css',
                '/public/index.html',
                '/.gitignore',
            ],
            expanded: [
                '/app',
            ],
            filterText: "",
            nodes: nodes,
            nodesFiltered: nodes
        };

        this.onCheck = this.onCheck.bind(this);
        this.onExpand = this.onExpand.bind(this);
        this.setFilterText = this.setFilterText.bind(this);
        this.filterTree = this.filterTree.bind(this);
        this.nodeFilter = this.nodeFilter.bind(this);
    }

    onCheck(checked) {
        this.setState({ checked });
    }

    onExpand(expanded) {
        this.setState({ expanded });
    }

    nodeFilter (node: Node) {
        const children = (node.children || []).map(this.nodeFilter).filter(c => c !== null);

        return node.label.indexOf(this.state.filterText) !== -1 || children.length ? {...node, children: children } : null;
    }

    filterTree () {
        if (!this.state.filterText) {
            return this.setState({
                nodesFiltered: this.state.nodes
            });
        }

        const nodesFiltered = this.state.nodes.map(this.nodeFilter).filter(n => n !== null);

        this.setState({
            nodesFiltered: nodesFiltered
        });
    }

    setFilterText(e) {
        this.setState({filterText: e.target.value}, this.filterTree);
    }

    render() {
        const { checked, expanded } = this.state;

        return (

                <input type='text' placeholder='Search' value={ this.state.filterText } onChange={ this.setFilterText } />
                <CheckboxTree
                    checked={checked}
                    expanded={expanded}
                    nodes={this.state.nodesFiltered}
                    onCheck={this.onCheck}
                    onExpand={this.onExpand}
                />

        );
    }
}

export default FilterExample;
<|endoftext|>


<commit_before>/*
 * Verwaltet Server-(Ajax)-Requests. Antworten vom Server werden als JSON
 * erwartet.
 *
 * @author Philipp Kemmeter
 */

/** Alles statisch */
GE.Ajax = {};

/** Welche Funktion bei erfolgreichem Request aufgerufen werden soll */
GE.Ajax.callback_functions = [];

/**
 * Der Name der Session, den der Server vergeben hat (muss mitgesandt werden
 * zur Identifikation der Verbindung
 */
GE.Ajax.session_name = 'sid';

/**
 * Die ID der Session, den der Server vergeben hat (muss mitgesandt werden
 * zur Identifikation der Verbindung
 */
GE.Ajax.session_id = '';

/**
 * Array von XHR-Objekten. Immer, wenn gerade eines in Gebrauch
 * ist, wird ein neues erzeugt. Alte, ungenutzte, werden dann wieder
 * freigegeben und deren Slots können erneut benutzt werden.
 */
GE.Ajax.xml_http_requests = [];

/**
 * Array, das angibt, ob das XHR-Objekt in xml_http_requests mit demselben
 * Index gerade in gebrauch ist, oder nicht.
 */
GE.Ajax.xhr_available = [];

/**
 * Anzahl der Requests. Wird beim Abschicken hochgezählt, damit Cachen
 * vermieden wird.
 */
GE.Ajax.request_num = 0;

/**
 * Gibt ein neu erzeugtes XHR-Objekt zurück
 *
 * @return XMLHttpRequest
 * @throws Error
 */
GE.Ajax.create_new_request = function() {
	if (typeof XMLHttpRequest != 'undefined')
		return new XMLHttpRequest();
	else if (window.ActiveXObject) {
		var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",
		             "MSXML2.XmlHttp.3.0",  "MSXML2.XmlHttp.4.0",
		             "MSXML2.XmlHttp.5.0"];
		for (var i = avers.length -1; i >= 0; i--) {
			try {
				httpObj = new ActiveXObject(avers[i]);
				return httpObj;
			} catch(e) {}
		}
	}
	throw new Error('XMLHttp (AJAX) not supported');
};

/**
 * Gibt den Index des nächsten freien XHR-Objekts zurück
 *
 * @access private
 * @return uint
 * @throws Error
 */
GE.Ajax.get_xhr_index = function() {
	var n = GE.Ajax.xhr_available.length;
	var result;
	for (var i = 0; i < n; i++) {
		if (GE.Ajax.xhr_available[i]) {
			result = i;
			break;
		}
	}

	if (i == n) {
		// Wenn kein neues gefunden werden konnte, dann ein neues erzeugen
		GE.Ajax.xml_http_requests[n] =
			GE.Ajax.create_new_request();
		result = n;
	}
	// und als "not available" markieren
	GE.Ajax.xhr_available[result] = false;

	return result;
};

/**
 * Sendet einen Request an den durch die URL bestimmten Server. Wird post_data
 * angegeben, werden sie als POST-Daten versandt, ansonsten wird die URL
 * inklusive aller mitgelieferten Parameter als GET versandt.
 * Die angegebene callback_function wird dann bei Erfolg aufgerufen.
 *
 * @param string url					Bestimmt das Ziel des Requests
 * @param Function callback_function	Welche Funktion bei Erfolg aufzurufen
 *                                      ist
 * @param string post_data[optional]	ggf. POST-Daten zum Versenden
 * @param bool no_parse[=false]			Ob die Serverantwort geparst werden
 *                                      soll
 * @throws Error						wenn Request nicht gesendet werden
 *                                      konnte
 */

GE.Ajax.send_request = function(url, callback_function, post_data, no_parse) {
	var xhri = GE.Ajax.get_xhr_index();
	var xhr = GE.Ajax.xml_http_requests[xhri];

	GE.Ajax.callback_functions[xhri] = callback_function;
	var method = typeof(post_data == 'undefined') ? "GET" : "POST";

	url = (url.indexOf('?') == -1) ? url + '?' : url + '&';
	url += "anti_cache=" + GE.Ajax.request_num;
	if (GE.Ajax.session_name && GE.Ajax.session_id)
		url += "&"+GE.Ajax.session_name + "="
				+ GE.Ajax.session_id;
	xhr.open(method, url, true);
	xhr.onreadystatechange = function() {
		var my_xhr = GE.Ajax.xml_http_requests[xhri];
		if ((my_xhr.readyState == 4) && (my_xhr.status == 200)) {
			GE.Ajax.xhr_available[xhri] = true;

			if (GE.Ajax.callback_functions[xhri]) {
				if(no_parse) {
					GE.Ajax.callback_functions[xhri].call(this,
						null, my_xhr.responseText);
				}
				else {
					if (JSON && JSON.parse)
						var o = JSON.parse(my_xhr.responseText);
					else
						var o = eval('(' + my_xhr.responseText + ')');

					if (o.sid)
						GE.Ajax.session_id = o.sid;

					GE.Ajax.callback_functions[xhri].call(this,
						o.err, o.result);
				}
			};
		}
	};
	if (method == "POST") {
		xhr.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded;charset=UTF-8");
		/* Unsafe: Wird von modernen Browser nicht erlaubt
		 * xhr.setRequestHeader("Content-length", post_data.length);
		 */
		xhr.send(encodeURI(post_data));
	}
	else {
		xhr.setRequestHeader("Content-type",
			"text/plain;charset=UTF-8");
		/* Unsafe: Wird von modernen Browser nicht erlaubt
		 * xhr.setRequestHeader("Content-length", 0);
		 */
		xhr.send(null);
	}
	GE.Ajax.request_num++;
	return true;
};

<commit_msg>minor fix for ie<commit_after>/*
 * Verwaltet Server-(Ajax)-Requests. Antworten vom Server werden als JSON
 * erwartet.
 *
 * @author Philipp Kemmeter
 */

/** Alles statisch */
GE.Ajax = {};

/** Welche Funktion bei erfolgreichem Request aufgerufen werden soll */
GE.Ajax.callback_functions = [];

/**
 * Der Name der Session, den der Server vergeben hat (muss mitgesandt werden
 * zur Identifikation der Verbindung
 */
GE.Ajax.session_name = 'sid';

/**
 * Die ID der Session, den der Server vergeben hat (muss mitgesandt werden
 * zur Identifikation der Verbindung
 */
GE.Ajax.session_id = '';

/**
 * Array von XHR-Objekten. Immer, wenn gerade eines in Gebrauch
 * ist, wird ein neues erzeugt. Alte, ungenutzte, werden dann wieder
 * freigegeben und deren Slots können erneut benutzt werden.
 */
GE.Ajax.xml_http_requests = [];

/**
 * Array, das angibt, ob das XHR-Objekt in xml_http_requests mit demselben
 * Index gerade in gebrauch ist, oder nicht.
 */
GE.Ajax.xhr_available = [];

/**
 * Anzahl der Requests. Wird beim Abschicken hochgezählt, damit Cachen
 * vermieden wird.
 */
GE.Ajax.request_num = 0;

/**
 * Gibt ein neu erzeugtes XHR-Objekt zurück
 *
 * @return XMLHttpRequest
 * @throws Error
 */
GE.Ajax.create_new_request = function() {
	if (typeof XMLHttpRequest != 'undefined')
		return new XMLHttpRequest();
	else if (window.ActiveXObject) {
		var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",
		             "MSXML2.XmlHttp.3.0",  "MSXML2.XmlHttp.4.0",
		             "MSXML2.XmlHttp.5.0"];
		for (var i = avers.length -1; i >= 0; i--) {
			try {
				httpObj = new ActiveXObject(avers[i]);
				return httpObj;
			} catch(e) {}
		}
	}
	throw new Error('XMLHttp (AJAX) not supported');
};

/**
 * Gibt den Index des nächsten freien XHR-Objekts zurück
 *
 * @access private
 * @return uint
 * @throws Error
 */
GE.Ajax.get_xhr_index = function() {
	var n = GE.Ajax.xhr_available.length;
	var result;
	for (var i = 0; i < n; i++) {
		if (GE.Ajax.xhr_available[i]) {
			result = i;
			break;
		}
	}

	if (i == n) {
		// Wenn kein neues gefunden werden konnte, dann ein neues erzeugen
		GE.Ajax.xml_http_requests[n] =
			GE.Ajax.create_new_request();
		result = n;
	}
	// und als "not available" markieren
	GE.Ajax.xhr_available[result] = false;

	return result;
};

/**
 * Sendet einen Request an den durch die URL bestimmten Server. Wird post_data
 * angegeben, werden sie als POST-Daten versandt, ansonsten wird die URL
 * inklusive aller mitgelieferten Parameter als GET versandt.
 * Die angegebene callback_function wird dann bei Erfolg aufgerufen.
 *
 * @param string url					Bestimmt das Ziel des Requests
 * @param Function callback_function	Welche Funktion bei Erfolg aufzurufen
 *                                      ist
 * @param string post_data[optional]	ggf. POST-Daten zum Versenden
 * @param bool no_parse[=false]			Ob die Serverantwort geparst werden
 *                                      soll
 * @throws Error						wenn Request nicht gesendet werden
 *                                      konnte
 */

GE.Ajax.send_request = function(url, callback_function, post_data, no_parse) {
	var xhri = GE.Ajax.get_xhr_index();
	var xhr = GE.Ajax.xml_http_requests[xhri];

	GE.Ajax.callback_functions[xhri] = callback_function;
	var method = (typeof(post_data) == 'undefined') ? "GET" : "POST";

	url = (url.indexOf('?') == -1) ? url + '?' : url + '&';
	url += "anti_cache=" + GE.Ajax.request_num;
	if (GE.Ajax.session_name && GE.Ajax.session_id)
		url += "&"+GE.Ajax.session_name + "="
				+ GE.Ajax.session_id;
	xhr.open(method, url, true);
	xhr.onreadystatechange = function() {
		var my_xhr = GE.Ajax.xml_http_requests[xhri];
		if ((my_xhr.readyState == 4) && (my_xhr.status == 200)) {
			GE.Ajax.xhr_available[xhri] = true;

			if (GE.Ajax.callback_functions[xhri]) {
				if(no_parse) {
					GE.Ajax.callback_functions[xhri].call(this,
						null, my_xhr.responseText);
				}
				else {
					if (JSON && JSON.parse)
						var o = JSON.parse(my_xhr.responseText);
					else
						var o = eval('(' + my_xhr.responseText + ')');

					if (o.sid)
						GE.Ajax.session_id = o.sid;

					GE.Ajax.callback_functions[xhri].call(this,
						o.err, o.result);
				}
			};
		}
	};
	if (method == "POST") {
		xhr.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded;charset=UTF-8");
		/* Unsafe: Wird von modernen Browser nicht erlaubt
		 * xhr.setRequestHeader("Content-length", post_data.length);
		 */
		xhr.send(encodeURI(post_data));
	}
	else {
		xhr.setRequestHeader("Content-type",
			"text/plain;charset=UTF-8");
		/* Unsafe: Wird von modernen Browser nicht erlaubt
		 * xhr.setRequestHeader("Content-length", 0);
		 */
		xhr.send(null);
	}
	GE.Ajax.request_num++;
	return true;
};

<|endoftext|>


<commit_before>(function(ns) {

    'use strict';

    var unit = ns.unit('com.github.amsemy.warby.unit.Widget', implementation);

    unit.require('lib.*');

    function implementation(units) {
        var $ = units.lib.$;

        /**
         * Параметры виджета.
         *
         * @namespace  Widget~Settings
         * @property  {String} name
         *            Имя виджета (id тега виджета).
         * @property  {String} constructor
         *            Функция-конструктор виджета.
         */

        /**
         * Создаёт виджет.
         *
         * @constructor
         * @param  {Widget~Settings} settings
         *         Параметры виджета.
         */
        var Widget = function(settings) {
            settings = (settings == null ? {} : settings);
            if (settings.name == null || settings.name === "") {
                throw new Error("Undefined 'settings.name' param");
            }
            this._name = settings.name;
        };

        /**
         * Возвращает элемент, который содержит тело виджета.
         *
         * @returns  {jQuery}
         *           Объект jQuery.
         */
        Widget.prototype.getWidgetObj = function() {
            return $("#" + this._name);
        };

        return Widget;

    }

})(gumup);
<commit_msg>Rename Widget._name to Widget.name<commit_after>(function(ns) {

    'use strict';

    var unit = ns.unit('com.github.amsemy.warby.unit.Widget', implementation);

    unit.require('lib.*');

    function implementation(units) {
        var $ = units.lib.$;

        /**
         * Параметры виджета.
         *
         * @namespace  Widget~Settings
         * @property  {String} name
         *            Имя виджета (id тега виджета).
         * @property  {String} constructor
         *            Функция-конструктор виджета.
         */

        /**
         * Создаёт виджет.
         *
         * @constructor
         * @param  {Widget~Settings} settings
         *         Параметры виджета.
         */
        var Widget = function(settings) {
            settings = (settings == null ? {} : settings);
            if (settings.name == null || settings.name === "") {
                throw new Error("Undefined 'settings.name' param");
            }
            this.name = settings.name;
        };

        /**
         * Возвращает элемент, который содержит тело виджета.
         *
         * @returns  {jQuery}
         *           Объект jQuery.
         */
        Widget.prototype.getWidgetObj = function() {
            return $("#" + this.name);
        };

        return Widget;

    }

})(gumup);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  name: 'Tabata',

  requires: [
    'foam.util.Timer'
  ],

  properties: [
    {
      class: 'Int',
      name: 'rounds',
      label: 'Number of rounds',
      value: 8
    },
    {
      class: 'Int',
      name: 'workTime',
      value: 20,
      units: 'seconds'
    },
    {
      class: 'Int',
      name: 'restTime',
      value: 10,
      units: 'seconds'
    },
    {
      class: 'Int',
      value: 5,
      name: 'warmupTime'
    },
    {
      class: 'Int',
      name: 'currentRound',
      value: 1
    },
    {
      class: 'Int',
      name: 'seconds',
      label: 'Total time'
    },
    {
      class: 'Int',
      name: 'elapsed',
      units: 'seconds',
      hidden: true,
      value: 0
    },
    {
      class: 'Int',
      name: 'remaining',
      units: 'seconds',
      value: 0,
      postSet: function(_, s) {
        if ( s == 0 ) {
          this.state.next(this);
        }
      }
    },
    {
      class: 'String',
      name: 'action'
    },
    {
      class: 'Int',
      name: 'roundLength',
      hidden: true,
      units: 'seconds'
    },
    {
      class: 'Int',
      name: 'roundStart',
      hidden: true,
      units: 'seconds'
    },
    {
      name: 'timer',
      hidden: true,
      factory: function() {
        var t = this.Timer.create();
t.timeWarp = 10;
        this.seconds$ = t.time$.map(function(t) { return Math.floor(t / 1000); });
        return t;
      }
    },
    {
      name: 'state',
      factory: function() {
        return this.Warmup.create();
      },
      hidden: true
    }
  ],

  methods: [
    function init() {
      this.elapsed$ = this.slot(function(seconds, roundStart) {
        return seconds - roundStart;
      });
      this.remaining$ = this.slot(function(elapsed, roundLength) {
        return roundLength - elapsed;
      });
    }
  ],

  classes: [
    {
      name: 'Warmup',
      methods: [
        function start(t) {
          t.roundLength = t.warmupTime;
          t.roundStart = t.seconds;
          t.action = 'Warmup';
        },
        function next(t) {
          t.state = t.Work.create();
          t.state.start(t);
        }
      ]
    },
    {
      name: 'Work',
      methods: [
        function start(t) {
          t.roundLength = t.workTime;
          t.roundStart = t.seconds;
          t.action = 'WORK!';
        },
        function next(t) {
          t.currentRound++;
          if ( t.currentRound >= t.rounds + 1 ) {
            t.state = t.Finish.create();
          } else {
            t.state = t.Rest.create();
          }

          t.state.start(t);
        }
      ]
    },
    {
      name: 'Rest',
      methods: [
        function start(t) {
          t.roundLength = t.restTime;
          t.roundStart = t.seconds;
          t.action = 'Rest';
        },
        function next(t) {
          t.state = t.Work.create();
          t.state.start(t);
        }
      ]
    },
    {
      name: 'Finish',
      methods: [
        function start(t) {
          t.action = 'Finished.';
          t.roundLength = 0;
          t.roundStart = t.seconds;
          t.stop();
        },
        function next(t) {
        }
      ]
    }
  ],

  actions: [
    {
      name: 'start',
      code: function() {
        this.timer.start();
        this.state.start(this);
      }
    },
    {
      name: 'stop',
      code: function() {
        this.timer.stop();
      }
    },
    {
      name: 'reset',
      code: function() {
        this.timer.stop();
        this.timer = undefined;
        this.currentRound = undefined;
        this.state = undefined;
        this.action = undefined;
      }
    }
  ]
});
<commit_msg>Renamed warmputTime to setupTime in Tabata.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  name: 'Tabata',

  requires: [
    'foam.util.Timer'
  ],

  properties: [
    {
      class: 'Int',
      name: 'rounds',
      label: 'Number of rounds',
      value: 8
    },
    {
      class: 'Int',
      name: 'workTime',
      value: 20,
      units: 'seconds'
    },
    {
      class: 'Int',
      name: 'restTime',
      value: 10,
      units: 'seconds'
    },
    {
      class: 'Int',
      value: 5,
      name: 'setupTime'
    },
    {
      class: 'Int',
      name: 'currentRound',
      value: 1
    },
    {
      class: 'Int',
      name: 'seconds',
      label: 'Total time'
    },
    {
      class: 'Int',
      name: 'elapsed',
      units: 'seconds',
      hidden: true,
      value: 0
    },
    {
      class: 'Int',
      name: 'remaining',
      units: 'seconds',
      value: 0,
      postSet: function(_, s) {
        if ( s == 0 ) {
          this.state.next(this);
        }
      }
    },
    {
      class: 'String',
      name: 'action'
    },
    {
      class: 'Int',
      name: 'roundLength',
      hidden: true,
      units: 'seconds'
    },
    {
      class: 'Int',
      name: 'roundStart',
      hidden: true,
      units: 'seconds'
    },
    {
      name: 'timer',
      hidden: true,
      factory: function() {
        var t = this.Timer.create();
 t.timeWarp = 10;
        this.seconds$ = t.time$.map(function(t) { return Math.floor(t / 1000); });
        return t;
      }
    },
    {
      name: 'state',
      factory: function() {
        return this.Warmup.create();
      },
      hidden: true
    }
  ],

  methods: [
    function init() {
      this.elapsed$ = this.slot(function(seconds, roundStart) {
        return seconds - roundStart;
      });
      this.remaining$ = this.slot(function(elapsed, roundLength) {
        return roundLength - elapsed;
      });
    }
  ],

  classes: [
    {
      name: 'Warmup',
      methods: [
        function start(t) {
          t.roundLength = t.setupTime;
          t.roundStart = t.seconds;
          t.action = 'Warmup';
        },
        function next(t) {
          t.state = t.Work.create();
          t.state.start(t);
        }
      ]
    },
    {
      name: 'Work',
      methods: [
        function start(t) {
          t.roundLength = t.workTime;
          t.roundStart = t.seconds;
          t.action = 'WORK!';
        },
        function next(t) {
          t.currentRound++;
          if ( t.currentRound >= t.rounds + 1 ) {
            t.state = t.Finish.create();
          } else {
            t.state = t.Rest.create();
          }

          t.state.start(t);
        }
      ]
    },
    {
      name: 'Rest',
      methods: [
        function start(t) {
          t.roundLength = t.restTime;
          t.roundStart = t.seconds;
          t.action = 'Rest';
        },
        function next(t) {
          t.state = t.Work.create();
          t.state.start(t);
        }
      ]
    },
    {
      name: 'Finish',
      methods: [
        function start(t) {
          t.action = 'Finished';
          t.roundLength = 0;
          t.roundStart = t.seconds;
          t.stop();
        },
        function next(t) {
        }
      ]
    }
  ],

  actions: [
    {
      name: 'start',
      code: function() {
        this.timer.start();
        this.state.start(this);
      }
    },
    {
      name: 'stop',
      code: function() {
        this.timer.stop();
      }
    },
    {
      name: 'reset',
      code: function() {
        this.timer.stop();
        this.timer = undefined;
        this.currentRound = undefined;
        this.state = undefined;
        this.action = undefined;
      }
    }
  ]
});
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";

    var StyleSheet = require("boost/StyleSheet");
    var LayoutPropTypes = require("boost/LayoutPropTypes");

    var validator = StyleSheet.validator;
    var number = validator.number;
    var dp = validator.dp;
    var string = validator.string;
    var color = validator.color;
    var font = validator.font;
    var _enum = validator.oneOf;

    var TextStylePropTypes = StyleSheet.createPropTypes(LayoutPropTypes /*ViewPropTypes*/ , {
        "color": color,
        //"fontFamily": string,
        "fontFamily": font,
        "fontSize": number,
        "fontStyle": _enum('normal', 'italic'),
        "fontWeight": _enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'),
        "letterSpacing": number,
        "lineHeight": dp,
        "textAlign": _enum("auto", 'left', 'right', 'center', 'justify'),
        //"textDecorationColor": string,
        //"textDecorationLine": _enum("none", 'underline', 'line-through', 'underline line-through'),
        //"textDecorationStyle": _enum("solid", 'double', 'dotted', 'dashed'),
        "writingDirection": _enum("auto", 'ltr', 'rtl')
    });

    module.exports = TextStylePropTypes;
});
<commit_msg>修改文本样式<commit_after>define(function (require, exports, module) {
    "use strict";

    var StyleSheet = require("boost/StyleSheet");
    var LayoutPropTypes = require("boost/LayoutPropTypes");
    //var ViewPropTypes = require("boost/ViewPropTypes");

    var validator = StyleSheet.validator;
    var number = validator.number;
    var dp = validator.dp;
    var string = validator.string;
    var color = validator.color;
    var font = validator.font;
    var _enum = validator.oneOf;

    var TextStylePropTypes = StyleSheet.createPropTypes(LayoutPropTypes, {
        "color": color,
        //"fontFamily": string,
        "backgroundColor": color, //
        "fontFamily": font,
        "fontSize": number,
        "fontStyle": _enum('normal', 'italic'),
        "fontWeight": _enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'),
        "letterSpacing": number,
        "lineHeight": dp,
        "textAlign": _enum("auto", 'left', 'right', 'center', 'justify'),
        //"textDecorationColor": string,
        //"textDecorationLine": _enum("none", 'underline', 'line-through', 'underline line-through'),
        //"textDecorationStyle": _enum("solid", 'double', 'dotted', 'dashed'),
        "writingDirection": _enum("auto", 'ltr', 'rtl')
    });

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