<commit_before>'use strict';
/* @flow */

var epsilon = require('./epsilon');

/**
 * The [Poisson Distribution](http://en.wikipedia.org/wiki/Poisson_distribution)
 * is a discrete probability distribution that expresses the probability
 * of a given number of events occurring in a fixed interval of time
 * and/or space if these events occur with a known average rate and
 * independently of the time since the last event.
 *
 * The Poisson Distribution is characterized by the strictly positive
 * mean arrival or occurrence rate, `λ`.
 *
 * @param {number} lambda location poisson distribution
 * @returns {number} value of poisson distribution at that point
 */
function poissonDistribution(lambda/*: number */) {
    // Check that lambda is strictly positive
    if (lambda <= 0) { return undefined; }

    // our current place in the distribution
    var x = 0,
        // and we keep track of the current cumulative probability, in
        // order to know when to stop calculating chances.
        cumulativeProbability = 0,
        // the calculated cells to be returned
        cells = {},
        factorialX = 1;

    // This algorithm iterates through each potential outcome,
    // until the `cumulativeProbability` is very close to 1, at
    // which point we've defined the vast majority of outcomes
    do {
        // a [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)
        cells[x] = (Math.pow(Math.E, -lambda) * Math.pow(lambda, x)) / factorialX;
        cumulativeProbability += cells[x];
        x++;
        factorialX *= x;
    // when the cumulativeProbability is nearly 1, we've calculated
    // the useful range of this distribution
    } while (cumulativeProbability < 1 - epsilon);

    return cells;
}

module.exports = poissonDistribution;
<commit_msg>perf(poissonDistribution): use Math.exp instead of Math.pow (#208)<commit_after>'use strict';
/* @flow */

var epsilon = require('./epsilon');

/**
 * The [Poisson Distribution](http://en.wikipedia.org/wiki/Poisson_distribution)
 * is a discrete probability distribution that expresses the probability
 * of a given number of events occurring in a fixed interval of time
 * and/or space if these events occur with a known average rate and
 * independently of the time since the last event.
 *
 * The Poisson Distribution is characterized by the strictly positive
 * mean arrival or occurrence rate, `λ`.
 *
 * @param {number} lambda location poisson distribution
 * @returns {number} value of poisson distribution at that point
 */
function poissonDistribution(lambda/*: number */) {
    // Check that lambda is strictly positive
    if (lambda <= 0) { return undefined; }

    // our current place in the distribution
    var x = 0,
        // and we keep track of the current cumulative probability, in
        // order to know when to stop calculating chances.
        cumulativeProbability = 0,
        // the calculated cells to be returned
        cells = {},
        factorialX = 1;

    // This algorithm iterates through each potential outcome,
    // until the `cumulativeProbability` is very close to 1, at
    // which point we've defined the vast majority of outcomes
    do {
        // a [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)
        cells[x] = (Math.exp(-lambda) * Math.pow(lambda, x)) / factorialX;
        cumulativeProbability += cells[x];
        x++;
        factorialX *= x;
    // when the cumulativeProbability is nearly 1, we've calculated
    // the useful range of this distribution
    } while (cumulativeProbability < 1 - epsilon);

    return cells;
}

module.exports = poissonDistribution;
<|endoftext|>


<commit_before>import { ipcRenderer } from 'electron';
import { getMeteor, getTracker, getGetUserPreference, getUserPresence } from './rocketChat';

const pollUserPresence = (UserPresence, maximumIdleTime) => {
	let wasUserPresent = false;

	return () => {
		let isUserPresent = true;

		try {
			const idleTime = ipcRenderer.sendSync('request-system-idle-time');
			isUserPresent = idleTime < maximumIdleTime;

			if (isUserPresent === wasUserPresent) {
				return;
			}

			if (isUserPresent) {
				UserPresence.setOnline();
			} else {
				UserPresence.setAway();
			}
		} catch (error) {
			console.error(error);
		} finally {
			wasUserPresent = isUserPresent;
		}
	};
};

const handleUserPresence = () => {
	const Meteor = getMeteor();
	const Tracker = getTracker();
	const getUserPreference = getGetUserPreference();
	const UserPresence = getUserPresence();

	if (!Meteor || !Tracker || !getUserPreference || !UserPresence) {
		return;
	}

	let intervalID;

	Tracker.autorun(() => {
		if (intervalID) {
			clearInterval(intervalID);
			intervalID = null;
		}

		const uid = Meteor.userId();

		if (!uid) {
			return;
		}

		delete UserPresence.awayTime;
		UserPresence.start();

		const isAutoAwayEnabled = getUserPreference(uid, 'enableAutoAway');

		if (!isAutoAwayEnabled) {
			UserPresence.setOnline();
			return;
		}

		const maximumIdleTime = (getUserPreference(uid, 'idleTimeLimit') || 300) * 1000;
		const idleTimeDetectionInterval = maximumIdleTime / 2;
		const callback = pollUserPresence(UserPresence, maximumIdleTime);

		intervalID = setInterval(callback, idleTimeDetectionInterval);
	});
};

export default () => {
	window.addEventListener('load', handleUserPresence);
};
<commit_msg>[FIX] Resolves issue with timing out when Rocket.Chat is in the background … (#1264)<commit_after>import { ipcRenderer } from 'electron';
import { getMeteor, getTracker, getGetUserPreference, getUserPresence } from './rocketChat';

const pollUserPresence = (UserPresence, maximumIdleTime) => {

	return () => {
		let isUserPresent = true;

		try {
			const idleTime = ipcRenderer.sendSync('request-system-idle-time');
			isUserPresent = idleTime < maximumIdleTime;

			if (isUserPresent) {
				UserPresence.setOnline();

			} else {
				UserPresence.setAway();
			}
		} catch (error) {
			console.error(error);
		} finally {
			wasUserPresent = isUserPresent;
		}
	};
};

const handleUserPresence = () => {
	const Meteor = getMeteor();
	const Tracker = getTracker();
	const getUserPreference = getGetUserPreference();
	const UserPresence = getUserPresence();

	if (!Meteor || !Tracker || !getUserPreference || !UserPresence) {
		return;
	}

	let intervalID;

	Tracker.autorun(() => {
		if (intervalID) {
			clearInterval(intervalID);
			intervalID = null;
		}

		const uid = Meteor.userId();

		if (!uid) {
			return;
		}

		delete UserPresence.awayTime;
		UserPresence.awayOnWindowBlur = false;
		UserPresence.start();

		const isAutoAwayEnabled = getUserPreference(uid, 'enableAutoAway');

		if (!isAutoAwayEnabled) {
			UserPresence.setOnline();
			return;
		}

		const maximumIdleTime = (getUserPreference(uid, 'idleTimeLimit') || 300) * 1000;
		const idleTimeDetectionInterval = 5000;
		const callback = pollUserPresence(UserPresence, maximumIdleTime);

		intervalID = setInterval(callback, idleTimeDetectionInterval);
	});
};

export default () => {
	window.addEventListener('load', handleUserPresence);
};
<|endoftext|>


<commit_before>import {centroid}       from '../centroid';
import {rotateRxRyRz}   from '../rotation';

export function cube(cubes, options, point, angles){

    for (var i = cubes.length - 1; i >= 0; i--) {

        var cube      = cubes[i];

        var p1        = cube[0];
        var p2        = cube[1];

        p1.rotated    = rotateRxRyRz({x : point.x(p1), y : point.y(p1), z : point.z(p1)}, angles);
        p2.rotated    = rotateRxRyRz({x : point.x(p2), y : point.y(p2), z : point.z(p2)}, angles);

        p1.projected  = options.project(p1.rotated, options);
        p2.projected  = options.project(p2.rotated, options);

        cube.centroid = centroid(cube);
    }
    return cubes;
}
<commit_msg>add cube<commit_after>import {ccw}         from '../counter-clockwise';
import {centroid}    from '../centroid';
import {point as pt} from './point';

export function cube(cubes, options, point, angles){
    var _cubes = [];
    for (var i = cubes.length - 1; i >= 0; i--) {

        var cube = cubes[i];

        var vertices = pt([
            cube[0],
            cube[1],
            cube[2],
            cube[3],
            cube[4],
            cube[5],
            cube[6],
            cube[7]
        ], options, point, angles);

        var v1 = vertices[0];
        var v2 = vertices[1];
        var v3 = vertices[2];
        var v4 = vertices[3];
        var v5 = vertices[4];
        var v6 = vertices[5];
        var v7 = vertices[6];
        var v8 = vertices[7];

        var front  = [v1, v2, v3, v4];
        var back   = [v8, v7, v6, v5];
        var left   = [v5, v6, v2, v1];
        var right  = [v4, v3, v7, v8];
        var top    = [v5, v1, v4, v8];
        var bottom = [v2, v6, v7, v3];

        front.centroid  = centroid(front);
        back.centroid   = centroid(back);
        left.centroid   = centroid(left);
        right.centroid  = centroid(right);
        top.centroid    = centroid(top);
        bottom.centroid = centroid(bottom);

        front.ccw  = ccw(front);
        back.ccw   = ccw(back);
        left.ccw   = ccw(left);
        right.ccw  = ccw(right);
        top.ccw    = ccw(top);
        bottom.ccw = ccw(bottom);

        front.face  = 'front';
        back.face   = 'back';
        left.face   = 'left';
        right.face  = 'right';
        top.face    = 'top';
        bottom.face = 'bottom';

        var _cube = [front, back, left, right, top, bottom];

        // TODO: centroid
        _cube.centroid = 'TODO';
        _cubes.push(_cube);
    }
    return _cubes;
}
<|endoftext|>


<commit_before>import fs from 'fs';

import jsdomGlobal from 'jsdom-global';

import createHash from './createHash';
import extractCSS from './extractCSS';
import getComponentNameFromFileName from './getComponentNameFromFileName';
import inlineResources from './inlineResources';
import queued from './queued';

const ROOT_ELEMENT_ID = 'happo-root';

async function renderExample(exampleRenderFunc, render) {
  document.body.innerHTML = '';
  const rootElement = document.createElement('div');
  rootElement.setAttribute('id', ROOT_ELEMENT_ID);
  document.body.appendChild(rootElement);

  const renderInDom = (renderResult) => {
    render(renderResult, { rootElement });
  }

  const result = exampleRenderFunc(renderInDom);
  if (result && typeof result.then === 'function') {
    // this is a promise
    await result;
    return;
  }
  renderInDom(result);
}
async function processVariants({
  component,
  variants,
  onlyComponent,
  publicFolders,
  getRootElement,
  render,
}) {
  if (onlyComponent && onlyComponent !== component) {
    return [];
  }
  const result = await queued(Object.keys(variants), async (variant) => {
    const hash = createHash(`${component}|${variant}`);
    const exampleRenderFunc = variants[variant];
    if (typeof exampleRenderFunc !== 'function') {
      // Some babel loaders add additional properties to the exports.
      // Ignore those that aren't functions.
      return;
    }
    await renderExample(exampleRenderFunc, render);

    if (publicFolders && publicFolders.length) {
      inlineResources({ publicFolders });
    }
    const root = (getRootElement && getRootElement(document))
      || document.getElementById(ROOT_ELEMENT_ID);
    const html = root.innerHTML.trim();
    return {
      html,
      css: '', // Can we remove this?
      component,
      variant,
      hash,
    };
  });

  return result.filter(Boolean);
}

export default async function processSnapsInBundle(webpackBundle, {
  globalCSS,
  only,
  publicFolders,
  getRootElement,
  viewport,
  render,
}) {
  const [ width, height ] = viewport.split('x').map((s) => parseInt(s, 10));
  const cleanupDOM = jsdomGlobal(
    '<!DOCTYPE html>',
    {
      beforeParse(win) {
        const pxHeight = parseInt()
        win.outerWidth = win.innerWidth = width;
        win.outerHeight = win.innerHeight = height;
        Object.defineProperties(win.screen, {
          width: { value: width },
          availWidth: { value: width },
          height: { value: height },
          availHeight: { value: height },
        });
      },
    }
  );

  // Parse and execute the webpack bundle
  require(webpackBundle);
  const { snaps } = global;

  const result = {
    snapPayloads: [],
  };

  const onlyComponent = only ? only.split('#')[1] : undefined;

  await queued(Object.keys(snaps), async (fileName) => {
    const objectOrArray = snaps[fileName];
    if (Array.isArray(objectOrArray)) {
      await queued(objectOrArray, async ({ component, variants }) => {
        const processedVariants = await processVariants({
          component,
          variants,
          onlyComponent,
          publicFolders,
          getRootElement,
          render,
        });
        result.snapPayloads.push(...processedVariants);
      });
    } else {
      const component = getComponentNameFromFileName(fileName);
      const processedVariants = await processVariants({
        component,
        variants: objectOrArray,
        onlyComponent,
        publicFolders,
        getRootElement,
        render,
      });
      result.snapPayloads.push(...processedVariants);
    }
  });

  result.globalCSS = globalCSS + extractCSS();
  cleanupDOM();
  return result;
}
<commit_msg>Fall back to document.body if rootElement goes missing<commit_after>import fs from 'fs';

import jsdomGlobal from 'jsdom-global';

import createHash from './createHash';
import extractCSS from './extractCSS';
import getComponentNameFromFileName from './getComponentNameFromFileName';
import inlineResources from './inlineResources';
import queued from './queued';

const ROOT_ELEMENT_ID = 'happo-root';

async function renderExample(exampleRenderFunc, render) {
  document.body.innerHTML = '';
  const rootElement = document.createElement('div');
  rootElement.setAttribute('id', ROOT_ELEMENT_ID);
  document.body.appendChild(rootElement);

  const renderInDom = (renderResult) => {
    render(renderResult, { rootElement });
  }

  const result = exampleRenderFunc(renderInDom);
  if (result && typeof result.then === 'function') {
    // this is a promise
    await result;
    return;
  }
  renderInDom(result);
}
async function processVariants({
  component,
  variants,
  onlyComponent,
  publicFolders,
  getRootElement,
  render,
}) {
  if (onlyComponent && onlyComponent !== component) {
    return [];
  }
  const result = await queued(Object.keys(variants), async (variant) => {
    const hash = createHash(`${component}|${variant}`);
    const exampleRenderFunc = variants[variant];
    if (typeof exampleRenderFunc !== 'function') {
      // Some babel loaders add additional properties to the exports.
      // Ignore those that aren't functions.
      return;
    }
    await renderExample(exampleRenderFunc, render);

    if (publicFolders && publicFolders.length) {
      inlineResources({ publicFolders });
    }
    const root = (getRootElement && getRootElement(document))
      || document.getElementById(ROOT_ELEMENT_ID) || document.body;
    const html = root.innerHTML.trim();
    return {
      html,
      css: '', // Can we remove this?
      component,
      variant,
      hash,
    };
  });

  return result.filter(Boolean);
}

export default async function processSnapsInBundle(webpackBundle, {
  globalCSS,
  only,
  publicFolders,
  getRootElement,
  viewport,
  render,
}) {
  const [ width, height ] = viewport.split('x').map((s) => parseInt(s, 10));
  const cleanupDOM = jsdomGlobal(
    '<!DOCTYPE html>',
    {
      beforeParse(win) {
        const pxHeight = parseInt()
        win.outerWidth = win.innerWidth = width;
        win.outerHeight = win.innerHeight = height;
        Object.defineProperties(win.screen, {
          width: { value: width },
          availWidth: { value: width },
          height: { value: height },
          availHeight: { value: height },
        });
      },
    }
  );

  // Parse and execute the webpack bundle
  require(webpackBundle);
  const { snaps } = global;

  const result = {
    snapPayloads: [],
  };

  const onlyComponent = only ? only.split('#')[1] : undefined;

  await queued(Object.keys(snaps), async (fileName) => {
    const objectOrArray = snaps[fileName];
    if (Array.isArray(objectOrArray)) {
      await queued(objectOrArray, async ({ component, variants }) => {
        const processedVariants = await processVariants({
          component,
          variants,
          onlyComponent,
          publicFolders,
          getRootElement,
          render,
        });
        result.snapPayloads.push(...processedVariants);
      });
    } else {
      const component = getComponentNameFromFileName(fileName);
      const processedVariants = await processVariants({
        component,
        variants: objectOrArray,
        onlyComponent,
        publicFolders,
        getRootElement,
        render,
      });
      result.snapPayloads.push(...processedVariants);
    }
  });

  result.globalCSS = globalCSS + extractCSS();
  cleanupDOM();
  return result;
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes as PT } from 'react'
import { debounce } from 'core-decorators'

export default class SpeechRecognition extends Component {
  static propTypes = {
    className: PT.string,
    onChange: PT.func,
    visible: PT.bool,
    listening: PT.bool,
    language: PT.string,
    showInterimResults: PT.bool,
    showFinalResults: PT.bool,
    entities: PT.arrayOf(PT.string),
    onHearEntity: PT.func,
    onLoad: PT.func,
    name: PT.string
  };

  static defaultProps = {
    visible: true,
    listening: true,
    showInterimResults: true,
    showFinalResults: true
  };

  constructor(props) {
    super(props)

    this.state = {
      interimTranscript: '',
      finalTranscript: '',
      browserSupportsSpeechRecognition: true,
      recognition: null
    }
  }

  componentWillMount() {
    const { language, listening, onLoad } = this.props
    const root = typeof window !== 'undefined' ? window : this
    const BrowserSpeechRecognition = root.SpeechRecognition ||
                                     root.webkitSpeechRecognition ||
                                     root.mozSpeechRecognition ||
                                     root.msSpeechRecognition ||
                                     root.oSpeechRecognition
    if (BrowserSpeechRecognition) {
      const recognition = new BrowserSpeechRecognition()
      recognition.continuous = true
      recognition.interimResults = true
      if (language) {
        recognition.lang = language
      }
      recognition.onresult = this.updateTranscript.bind(this)
      recognition.onend = this.restartRecognition.bind(this)
      if (listening) {
        recognition.start()
      }
      this.setState({ recognition })
      if (onLoad) {
        onLoad({ success: true })
      }
    } else {
      this.setState({ browserSupportsSpeechRecognition: false })
      if (onLoad) {
        onLoad({ success: false })
      }
    }
  }

  componentWillUnmount() {
    if (this.state.recognition) {
      this.state.recognition.abort()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.recognition) {
      if (this.props.listening && !nextProps.listening) {
        this.state.recognition.stop()
      } else if (!this.props.listening && nextProps.listening) {
        this.state.recognition.start()
      }

      /* Changing the name prop is the equivalent of resetting the component.
        Preferably, this would be done by changing the key prop, but
        re-rendering the component seems to break the speech recognition. */
      if (this.props.name !== nextProps.name) {
        this.setState({ interimTranscript: '', finalTranscript: '' })
        this.state.recognition.abort()
      }
    }
  }

  updateTranscript(event) {
    const { onChange } = this.props
    const { finalTranscript, interimTranscript } = this.getNewTranscript(event)

    this.handleSpokenEntity(interimTranscript)

    const transcriptBefore = this.concatTranscripts(this.state.finalTranscript, this.state.interimTranscript)
    const transcriptAfter = this.concatTranscripts(finalTranscript, interimTranscript)

    if (onChange && transcriptBefore !== transcriptAfter) {
      onChange(transcriptAfter)
    }

    this.setState({ finalTranscript, interimTranscript })
  }

  @debounce(1000)
  restartRecognition() {
    const { listening } = this.props
    const { recognition } = this.state

    if (listening) {
      recognition.start()
    }
  }

  getNewTranscript(event) {
    let finalTranscript = this.state.finalTranscript
    let interimTranscript = ''
    for (let i = event.resultIndex; i < event.results.length; ++i) {
      if (event.results[i].isFinal) {
        finalTranscript = this.concatTranscripts(finalTranscript, event.results[i][0].transcript)
      } else {
        interimTranscript = this.concatTranscripts(interimTranscript, event.results[i][0].transcript)
      }
    }
    return { finalTranscript, interimTranscript }
  }

  concatTranscripts(...transcriptParts) {
    return transcriptParts.map(t => t.trim()).join(' ').trim()
  }

  handleSpokenEntity(interimTranscript) {
    const { entities, onHearEntity } = this.props

    if (entities && onHearEntity && interimTranscript !== this.state.interimTranscript) {
      const mostRecentlySpokenEntity = this.findEntity(entities, interimTranscript)
      if (mostRecentlySpokenEntity) {
        onHearEntity(mostRecentlySpokenEntity)
      }
    }
  }

  findEntity(entities, transcript) {
    const words = transcript.toLowerCase().split(' ')
    const normalisedEntities = entities.map(e => e.toLowerCase())
    for (let i = 0; i < normalisedEntities.length; ++i) {
      if (words[words.length - 1] === normalisedEntities[i]) {
        return normalisedEntities[i]
      }
    }
    return null
  }

  render() {
    const { className, visible, showInterimResults, showFinalResults } = this.props
    const { interimTranscript, finalTranscript, browserSupportsSpeechRecognition } = this.state

    if (!visible || !browserSupportsSpeechRecognition) {
      return null
    }

    const transcriptParts = []
    if (showFinalResults) {
      transcriptParts.push(finalTranscript)
    }
    if (showInterimResults) {
      transcriptParts.push(interimTranscript)
    }

    return (

        {transcriptParts.join(' ')}

    )
  }
}
<commit_msg>Support multi-word entities<commit_after>import React, { Component, PropTypes as PT } from 'react'
import { debounce } from 'core-decorators'

export default class SpeechRecognition extends Component {
  static propTypes = {
    className: PT.string,
    onChange: PT.func,
    visible: PT.bool,
    listening: PT.bool,
    language: PT.string,
    showInterimResults: PT.bool,
    showFinalResults: PT.bool,
    entities: PT.arrayOf(PT.string),
    onHearEntity: PT.func,
    onLoad: PT.func,
    name: PT.string
  };

  static defaultProps = {
    visible: true,
    listening: true,
    showInterimResults: true,
    showFinalResults: true
  };

  constructor(props) {
    super(props)

    this.state = {
      interimTranscript: '',
      finalTranscript: '',
      browserSupportsSpeechRecognition: true,
      recognition: null
    }
  }

  componentWillMount() {
    const { language, listening, onLoad } = this.props
    const root = typeof window !== 'undefined' ? window : this
    const BrowserSpeechRecognition = root.SpeechRecognition ||
                                     root.webkitSpeechRecognition ||
                                     root.mozSpeechRecognition ||
                                     root.msSpeechRecognition ||
                                     root.oSpeechRecognition
    if (BrowserSpeechRecognition) {
      const recognition = new BrowserSpeechRecognition()
      recognition.continuous = true
      recognition.interimResults = true
      if (language) {
        recognition.lang = language
      }
      recognition.onresult = this.updateTranscript.bind(this)
      recognition.onend = this.restartRecognition.bind(this)
      if (listening) {
        recognition.start()
      }
      this.setState({ recognition })
      if (onLoad) {
        onLoad({ success: true })
      }
    } else {
      this.setState({ browserSupportsSpeechRecognition: false })
      if (onLoad) {
        onLoad({ success: false })
      }
    }
  }

  componentWillUnmount() {
    if (this.state.recognition) {
      this.state.recognition.abort()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.recognition) {
      if (this.props.listening && !nextProps.listening) {
        this.state.recognition.stop()
      } else if (!this.props.listening && nextProps.listening) {
        this.state.recognition.start()
      }

      /* Changing the name prop is the equivalent of resetting the component.
        Preferably, this would be done by changing the key prop, but
        re-rendering the component seems to break the speech recognition. */
      if (this.props.name !== nextProps.name) {
        this.setState({ interimTranscript: '', finalTranscript: '' })
        this.state.recognition.abort()
      }
    }
  }

  updateTranscript(event) {
    const { onChange } = this.props
    const { finalTranscript, interimTranscript } = this.getNewTranscript(event)

    this.handleSpokenEntity(interimTranscript)

    const transcriptBefore = this.concatTranscripts(this.state.finalTranscript, this.state.interimTranscript)
    const transcriptAfter = this.concatTranscripts(finalTranscript, interimTranscript)

    if (onChange && transcriptBefore !== transcriptAfter) {
      onChange(transcriptAfter)
    }

    this.setState({ finalTranscript, interimTranscript })
  }

  @debounce(1000)
  restartRecognition() {
    const { listening } = this.props
    const { recognition } = this.state

    if (listening) {
      recognition.start()
    }
  }

  getNewTranscript(event) {
    let finalTranscript = this.state.finalTranscript
    let interimTranscript = ''
    for (let i = event.resultIndex; i < event.results.length; ++i) {
      if (event.results[i].isFinal) {
        finalTranscript = this.concatTranscripts(finalTranscript, event.results[i][0].transcript)
      } else {
        interimTranscript = this.concatTranscripts(interimTranscript, event.results[i][0].transcript)
      }
    }
    return { finalTranscript, interimTranscript }
  }

  concatTranscripts(...transcriptParts) {
    return transcriptParts.map(t => t.trim()).join(' ').trim()
  }

  handleSpokenEntity(interimTranscript) {
    const { entities, onHearEntity } = this.props

    if (entities && onHearEntity && interimTranscript !== this.state.interimTranscript) {
      const mostRecentlySpokenEntity = this.findEntity(entities, interimTranscript)
      if (mostRecentlySpokenEntity) {
        onHearEntity(mostRecentlySpokenEntity)
      }
    }
  }

  findEntity(entities, transcript) {
    const splitTranscript = transcript.toLowerCase().split(' ')
    const splitEntities = entities.map(e => e.toLowerCase().split(' '))
    for (let i = 0; i < splitEntities.length; ++i) {
      const entityStartingWordIndex = Math.max(0, splitTranscript.length - splitEntities[i].length)
      const endOfTranscript = splitTranscript.slice(entityStartingWordIndex).join(' ')
      const entity = splitEntities[i].join(' ')
      if (endOfTranscript === entity) {
        return entity
      }
    }
    return null
  }

  render() {
    const { className, visible, showInterimResults, showFinalResults } = this.props
    const { interimTranscript, finalTranscript, browserSupportsSpeechRecognition } = this.state

    if (!visible || !browserSupportsSpeechRecognition) {
      return null
    }

    const transcriptParts = []
    if (showFinalResults) {
      transcriptParts.push(finalTranscript)
    }
    if (showInterimResults) {
      transcriptParts.push(interimTranscript)
    }

    return (

        {transcriptParts.join(' ')}

    )
  }
}
<|endoftext|>


<commit_before>/**
 * @author David Gossow - dgossow@willowgarage.com
 */

/**
 * A client for an interactive marker topic.
 *
 * @constructor
 * @param options - object with following keys:
 *  * ros - a handle to the ROS connection
 *  * tfClient - a handle to the TF client
 *  * topic (optional) - the topic to subscribe to, like '/basic_controls'
 *  * path (optional) - the base path to any meshes that will be loaded
 *  * camera - the main camera associated with the viewer for this marker client
 *  * rootObject (optional) - the root THREE 3D object to render to
 */
ROS3D.InteractiveMarkerClient = function(options) {
  var that = this;
  var options = options || {};
  this.ros = options.ros;
  this.tfClient = options.tfClient;
  this.topic = options.topic;
  this.path = '';
  this.camera = options.camera;
  this.rootObject = options.rootObject || new THREE.Object3D();

  this.interactiveMarkers = {};
  this.updateTopic = null;
  this.feedbackTopic = null;

  // check for an initial topic
  if (this.topic) {
    this.subscribe(this.topic);
  }
};

/**
 * Subscribe to the given interactive marker topic. This will unsubscribe from any current topics.
 *
 * @param topic - the topic to subscribe to, like '/basic_controls'
 */
ROS3D.InteractiveMarkerClient.prototype.subscribe = function(topic) {
  // unsubscribe to the other topics
  this.unsubscribe();

  this.updateTopic = new ROSLIB.Topic({
    ros : this.ros,
    name : topic + '/tunneled/update',
    messageType : 'visualization_msgs/InteractiveMarkerUpdate',
    compression : 'png'
  });
  this.updateTopic.subscribe(this.processUpdate.bind(this));

  this.feedbackTopic = new ROSLIB.Topic({
    ros : this.ros,
    name : topic + '/feedback',
    messageType : 'visualization_msgs/InteractiveMarkerFeedback',
    compression : 'png'
  });
  this.feedbackTopic.advertise();

  this.initService = new ROSLIB.Service({
    ros : this.ros,
    name : topic + '/tunneled/get_init',
    serviceType : 'demo_interactive_markers/GetInit'
  });
  var request = new ROSLIB.ServiceRequest({});
  this.initService.callService(request, this.processInit.bind(this));
};

/**
 * Unsubscribe from the current interactive marker topic.
 */
ROS3D.InteractiveMarkerClient.prototype.unsubscribe = function() {
  if (this.updateTopic) {
    this.updateTopic.unsubscribe();
  }
  if (this.feedbackTopic) {
    this.feedbackTopic.unadvertise();
  }
  // erase all markers
  for (intMarkerName in this.interactiveMarkers) {
    this.eraseIntMarker(intMarkerName);
  }
  this.interactiveMarkers = {};
};

/**
 * Process the given interactive marker initialization message.
 *
 * @param initMessage - the interactive marker initialization message to process
 */
ROS3D.InteractiveMarkerClient.prototype.processInit = function(initMessage) {
  var message = initMessage.msg;

  // erase any old markers
  message.erases = [];
  for (intMarkerName in this.interactiveMarkers) {
    message.erases.push(intMarkerName);
  };
  message.poses = [];

  // treat it as an update
  this.processUpdate(message);
};

/**
 * Process the given interactive marker update message.
 *
 * @param initMessage - the interactive marker update message to process
 */
ROS3D.InteractiveMarkerClient.prototype.processUpdate = function(message) {
  var that = this;

  // erase any markers
  message.erases.forEach(function(name) {
    var marker = that.interactiveMarkers[name];
    that.eraseIntMarker(name);
  });

  // updates marker poses
  message.poses.forEach(function(poseMessage) {
    var marker = that.interactiveMarkers[poseMessage.name];
    if (marker) {
      marker.setPoseFromServer(poseMessage.pose);
    }
  });

  // add new markers
  message.markers.forEach(function(msg) {
    // get rid of anything with the same name
    var oldhandle = that.interactiveMarkers[msg.name];
    if (oldhandle) {
      that.eraseIntMarker(oldhandle.name);
    }

    // create the handle
    var handle = new ROS3D.InteractiveMarkerHandle({
      message : msg,
      feedbackTopic : that.feedbackTopic,
      tfClient : that.tfClient
    });
    that.interactiveMarkers[msg.name] = handle;

    // create the actual marker
    var intMarker = new ROS3D.InteractiveMarker({
      handle : handle,
      camera : that.camera,
      path : that.path
    });
    // add it to the scene
    that.rootObject.add(intMarker);

    // listen for any pose updates from the server
    handle.on('pose', function(pose) {
      intMarker.onServerSetPose({
        pose : pose
      });
    });

    intMarker.addEventListener('user-pose-change', handle.setPoseFromClient.bind(handle));
    intMarker.addEventListener('user-mousedown', handle.onMouseDown.bind(handle));
    intMarker.addEventListener('user-mouseup', handle.onMouseUp.bind(handle));
    intMarker.addEventListener('user-button-click', handle.onButtonClick.bind(handle));
    intMarker.addEventListener('menu-select', handle.onMenuSelect.bind(handle));

    // now list for any TF changes
    handle.subscribeTf();
  });
};

/**
 * Erase the interactive marker with the given name.
 *
 * @param intMarkerName - the interactive marker name to delete
 */
ROS3D.InteractiveMarkerClient.prototype.eraseIntMarker = function(intMarkerName) {
  if (this.interactiveMarkers[intMarkerName]) {
    delete this.interactiveMarkers[intMarkerName];
  }
};
<commit_msg>Bugfix in InteractiveMarkerClient path option<commit_after>/**
 * @author David Gossow - dgossow@willowgarage.com
 */

/**
 * A client for an interactive marker topic.
 *
 * @constructor
 * @param options - object with following keys:
 *  * ros - a handle to the ROS connection
 *  * tfClient - a handle to the TF client
 *  * topic (optional) - the topic to subscribe to, like '/basic_controls'
 *  * path (optional) - the base path to any meshes that will be loaded
 *  * camera - the main camera associated with the viewer for this marker client
 *  * rootObject (optional) - the root THREE 3D object to render to
 */
ROS3D.InteractiveMarkerClient = function(options) {
  var that = this;
  var options = options || {};
  this.ros = options.ros;
  this.tfClient = options.tfClient;
  this.topic = options.topic;
  this.path = options.path || '/';
  this.camera = options.camera;
  this.rootObject = options.rootObject || new THREE.Object3D();

  this.interactiveMarkers = {};
  this.updateTopic = null;
  this.feedbackTopic = null;

  // check for an initial topic
  if (this.topic) {
    this.subscribe(this.topic);
  }
};

/**
 * Subscribe to the given interactive marker topic. This will unsubscribe from any current topics.
 *
 * @param topic - the topic to subscribe to, like '/basic_controls'
 */
ROS3D.InteractiveMarkerClient.prototype.subscribe = function(topic) {
  // unsubscribe to the other topics
  this.unsubscribe();

  this.updateTopic = new ROSLIB.Topic({
    ros : this.ros,
    name : topic + '/tunneled/update',
    messageType : 'visualization_msgs/InteractiveMarkerUpdate',
    compression : 'png'
  });
  this.updateTopic.subscribe(this.processUpdate.bind(this));

  this.feedbackTopic = new ROSLIB.Topic({
    ros : this.ros,
    name : topic + '/feedback',
    messageType : 'visualization_msgs/InteractiveMarkerFeedback',
    compression : 'png'
  });
  this.feedbackTopic.advertise();

  this.initService = new ROSLIB.Service({
    ros : this.ros,
    name : topic + '/tunneled/get_init',
    serviceType : 'demo_interactive_markers/GetInit'
  });
  var request = new ROSLIB.ServiceRequest({});
  this.initService.callService(request, this.processInit.bind(this));
};

/**
 * Unsubscribe from the current interactive marker topic.
 */
ROS3D.InteractiveMarkerClient.prototype.unsubscribe = function() {
  if (this.updateTopic) {
    this.updateTopic.unsubscribe();
  }
  if (this.feedbackTopic) {
    this.feedbackTopic.unadvertise();
  }
  // erase all markers
  for (intMarkerName in this.interactiveMarkers) {
    this.eraseIntMarker(intMarkerName);
  }
  this.interactiveMarkers = {};
};

/**
 * Process the given interactive marker initialization message.
 *
 * @param initMessage - the interactive marker initialization message to process
 */
ROS3D.InteractiveMarkerClient.prototype.processInit = function(initMessage) {
  var message = initMessage.msg;

  // erase any old markers
  message.erases = [];
  for (intMarkerName in this.interactiveMarkers) {
    message.erases.push(intMarkerName);
  };
  message.poses = [];

  // treat it as an update
  this.processUpdate(message);
};

/**
 * Process the given interactive marker update message.
 *
 * @param initMessage - the interactive marker update message to process
 */
ROS3D.InteractiveMarkerClient.prototype.processUpdate = function(message) {
  var that = this;

  // erase any markers
  message.erases.forEach(function(name) {
    var marker = that.interactiveMarkers[name];
    that.eraseIntMarker(name);
  });

  // updates marker poses
  message.poses.forEach(function(poseMessage) {
    var marker = that.interactiveMarkers[poseMessage.name];
    if (marker) {
      marker.setPoseFromServer(poseMessage.pose);
    }
  });

  // add new markers
  message.markers.forEach(function(msg) {
    // get rid of anything with the same name
    var oldhandle = that.interactiveMarkers[msg.name];
    if (oldhandle) {
      that.eraseIntMarker(oldhandle.name);
    }

    // create the handle
    var handle = new ROS3D.InteractiveMarkerHandle({
      message : msg,
      feedbackTopic : that.feedbackTopic,
      tfClient : that.tfClient
    });
    that.interactiveMarkers[msg.name] = handle;

    // create the actual marker
    var intMarker = new ROS3D.InteractiveMarker({
      handle : handle,
      camera : that.camera,
      path : that.path
    });
    // add it to the scene
    that.rootObject.add(intMarker);

    // listen for any pose updates from the server
    handle.on('pose', function(pose) {
      intMarker.onServerSetPose({
        pose : pose
      });
    });

    intMarker.addEventListener('user-pose-change', handle.setPoseFromClient.bind(handle));
    intMarker.addEventListener('user-mousedown', handle.onMouseDown.bind(handle));
    intMarker.addEventListener('user-mouseup', handle.onMouseUp.bind(handle));
    intMarker.addEventListener('user-button-click', handle.onButtonClick.bind(handle));
    intMarker.addEventListener('menu-select', handle.onMenuSelect.bind(handle));

    // now list for any TF changes
    handle.subscribeTf();
  });
};

/**
 * Erase the interactive marker with the given name.
 *
 * @param intMarkerName - the interactive marker name to delete
 */
ROS3D.InteractiveMarkerClient.prototype.eraseIntMarker = function(intMarkerName) {
  if (this.interactiveMarkers[intMarkerName]) {
    delete this.interactiveMarkers[intMarkerName];
  }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*jslint node: true */
var os = require('os');
var cluster = require('cluster');
var logger = require('loge');
var path = require('path');

var optimist = require('optimist')
  .usage('Usage: node cluster.js [options]')
  .describe({
    forks: 'maximum number of workers to spawn',
  })
  .default({forks: os.cpus().length});

var argv = optimist.argv;

cluster.setupMaster({
  exec: path.join(__dirname, 'server.js'),
});
cluster.on('fork', function(worker) {
  logger.debug('cluster: worker[%d] fork (pid=%d)', worker.id, worker.process.pid);
});
cluster.on('disconnect', function(worker) {
  // disconnect occurs slightly before exit, I think. I'm not sure. anyways, they both happen.
  logger.error('cluster: worker[%d] disconnect (pid=%d)', worker.id, worker.process.pid);
});
cluster.on('exit', function(worker, code, signal) {
  logger.error('cluster: worker[%d] exit code=%d signal=%s (pid=%d)', worker.id, code, signal, worker.process.pid);
  // fork new worker to replace dead one
  cluster.fork();
});
cluster.on('listening', function(worker, address) {
  logger.debug('cluster: worker[%d] listening %s @ %s:%s (pid=%d)', worker.id,
    address.addressType, address.address, address.port, worker.process.pid);
});

// fork initial workers
logger.info('Starting cluster with %d forks', argv.forks);
for (var i = 0; i < argv.forks; i++) {
  cluster.fork();
}
<commit_msg>Don't depend on Node.js for load-balancing<commit_after>#!/usr/bin/env node
/*jslint node: true */
var os = require('os');
var cluster = require('cluster');
var logger = require('loge');
var path = require('path');

var config = require('./package').config;
var port_zero = parseInt(process.env.npm_config_port || config.port, 10);

var optimist = require('optimist')
  .usage('Usage: node cluster.js [options]')
  .describe({
    forks: 'maximum number of workers to spawn',
  })
  .default({forks: os.cpus().length});

var argv = optimist.argv;

cluster.setupMaster({
  exec: path.join(__dirname, 'server.js'),
});
cluster.on('fork', function(worker) {
  logger.debug('cluster: worker[%d] fork (pid=%d)', worker.id, worker.process.pid);
});
cluster.on('disconnect', function(worker) {
  // disconnect occurs slightly before exit.
  logger.error('cluster: worker[%d] disconnect (pid=%d)',
    worker.id, worker.process.pid);
});
cluster.on('exit', function(worker, code, signal) {
  logger.error('cluster: worker[%d] exit code=%d signal=%s (pid=%d)',
    worker.id, code, signal, worker.process.pid);
  // fork new worker to replace dead one
  cluster.fork({npm_config_port: worker.port});
});
cluster.on('listening', function(worker, address) {
  logger.debug('cluster: worker[%d] listening %s @ %s:%s (pid=%d)', worker.id,
    address.addressType, address.address, address.port, worker.process.pid);
});

// fork initial workers
logger.info('Starting cluster with %d forks', argv.forks);
for (var i = 0; i < argv.forks; i++) {
  var worker = cluster.fork({npm_config_port: port_zero + i});
  worker.port = port_zero + i;
}
<|endoftext|>


<commit_before>/* globals module Promise */

'use strict';

module.exports = function ({
  models
}) {
  const {
    Project
  } = models;

  return {
    getAllProjects() {
      return new Promise((resolve, reject) => {
        Project.find((err, projects) => {
          if (err) {
            return reject(err);
          }

          return resolve(projects);
        });
      });
    },
    getProjectByName(projectName) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    updateProjectAplyersByName(projectName, applyer) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          project.applyers.push(applyer);
          project.save();
          return resolve(project);
        });
      });
    },
    updateProjectEmployeesByName(projectName, employee) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          project.employees.push(employee);
          project.save();
          return resolve(project);
        });
      });
    },
    getProjectsWhichContains(string) {
      let regex = new RegExp(string, 'i');

      return new Promise((resolve, reject) => {
        Project.find({
          name: regex
        }, (err, projects) => {
          if (err) {
            return reject(err);
          }

          return resolve(projects);
        });
      });
    },
    getProjectById(id) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          _id: id
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    createProject(project) {
      const newProject = Project.getProject(project);

      return new Promise((resolve, reject) => {
        newProject.save(err => {
          if (err) {
            return reject(err);
          }

          return resolve(newProject);
        });
      });
    },
    getProjectBySkill(skill) {
      return new Promise((resolve, reject) => {
        Project.find({
          devSkills: skill
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    updateProject(project) {
      return new Promise((resolve, reject) => {
        project.save((err, updated) => {
          if (err) {
            return reject(err);
          }

          return resolve(updated);
        });
      });
    }
  };
};<commit_msg>repeating appliers and employees issue done<commit_after>/* globals module Promise */

'use strict';

module.exports = function ({
  models
}) {
  const {
    Project
  } = models;

  return {
    getAllProjects() {
      return new Promise((resolve, reject) => {
        Project.find((err, projects) => {
          if (err) {
            return reject(err);
          }

          return resolve(projects);
        });
      });
    },
    getProjectByName(projectName) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    updateProjectAplyersByName(projectName, applyer) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }
          if (!project.applyers.some(x => x === applyer)) {
            project.applyers.push(applyer);
            project.save();
          }
          return resolve(project);
        });
      });
    },
    updateProjectEmployeesByName(projectName, employee) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          name: projectName
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          if (!project.employees.some(x => x.employeeName === employee.employeeName)) {
            project.employees.push(employee);
            project.save();
          }
          return resolve(project);
        });
      });
    },
    getProjectsWhichContains(string) {
      let regex = new RegExp(string, 'i');

      return new Promise((resolve, reject) => {
        Project.find({
          name: regex
        }, (err, projects) => {
          if (err) {
            return reject(err);
          }

          return resolve(projects);
        });
      });
    },
    getProjectById(id) {
      return new Promise((resolve, reject) => {
        Project.findOne({
          _id: id
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    createProject(project) {
      const newProject = Project.getProject(project);

      return new Promise((resolve, reject) => {
        newProject.save(err => {
          if (err) {
            return reject(err);
          }

          return resolve(newProject);
        });
      });
    },
    getProjectBySkill(skill) {
      return new Promise((resolve, reject) => {
        Project.find({
          devSkills: skill
        }, (err, project) => {
          if (err) {
            return reject(err);
          }

          return resolve(project);
        });
      });
    },
    updateProject(project) {
      return new Promise((resolve, reject) => {
        project.save((err, updated) => {
          if (err) {
            return reject(err);
          }

          return resolve(updated);
        });
      });
    }
  };
};<|endoftext|>


<commit_before>
/*
  This script will initialize a local Mongo database
  on your machine so you can do development work.

  IMPORTANT: You should make sure the

      local_database_name

  variable matches its value in app.js  Otherwise, you'll have
  initialized the wrong database.
*/

var mongoose = require('mongoose');
var models   = require('./models');

// Connect to the Mongo database, whether locally or on Heroku
var local_database_name = 'leggo';
var local_database_uri  = 'mongodb://localhost/' + local_database_name
var database_uri = process.env.MONGOLAB_URI || local_database_uri
mongoose.connect(database_uri);

console.log(database_uri);

// Do the initialization here

// Step 1: load the JSON data
var activities_json = require('./data.json');

// Step 2: Remove all existing documents
models.Activity
  .find()
  .remove()
  .exec(onceClear); // callback to continue at

// Step 3: load the data from the JSON file
function onceClear(err) {
  if(err) console.log(err);

  // loop over the projects, construct and save an object from each one
  // Note that we don't care what order these saves are happening in...
  var to_save_count = activities_json.length;
  for(var i=0; i<activities_json.length; i++) {
    var json = activities_json[i];
    // console.log(json.loc);
    var proj = new models.Activity(json);

    proj.save(function(err, proj) {
      if(err) console.log(err);

      to_save_count--;
      console.log(to_save_count + ' left to save');
      if(to_save_count <= 0) {
        console.log('DONE');
        // The script won't terminate until the
        // connection to the database is closed
        mongoose.connection.close()
      }
    });
  }
}

<commit_msg>initDB chage<commit_after>
/*
  This script will initialize a local Mongo database
  on your machine so you can do development work.

  IMPORTANT: You should make sure the

      local_database_name

  variable matches its value in app.js  Otherwise, you'll have
  initialized the wrong database.
*/

var mongoose = require('mongoose');
var models   = require('./models');

// Connect to the Mongo database, whether locally or on Heroku
var local_database_name = 'leggo';
var local_database_uri  = 'mongodb://localhost/' + local_database_name
var database_uri = process.env.MONGOLAB_URI || local_database_uri
mongoose.connect(database_uri);

console.log(database_uri);

// Do the initialization here

// Step 1: load the JSON data
var activities_json = require('./data.json');

// Step 2: Remove all existing documents
models.Activity
  .find()
  .remove()
  .exec(onceClear); // callback to continue at

// Step 3: load the data from the JSON file
function onceClear(err) {
  if(err) console.log(err);

  // loop over the projects, construct and save an object from each one
  // Note that we don't care what order these saves are happening in...
  var to_save_count = activities_json.activities.length;
  for(var i=0; i<activities_json.activities.length; i++) {
    var json = activities_json.activities[i];
    // console.log(json.loc);
    var proj = new models.Activity(json);

    proj.save(function(err, proj) {
      if(err) console.log(err);

      to_save_count--;
      console.log(to_save_count + ' left to save');
      if(to_save_count <= 0) {
        console.log('DONE');
        // The script won't terminate until the
        // connection to the database is closed
        mongoose.connection.close()
      }
    });
  }
}

<|endoftext|>


<commit_before>document.addEventListener("touchstart",on_touch);
document.addEventListener("mousedown",on_touch);

var recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.maxAlternatives =5;

function on_touch()
{
	if(recognition.start){
		recognition.start();
		recognition_started = true;
	}

}
function onend()
{
	recognition.stop();
	recognition_started = false;
}
recognition.onend = onend;
recognition.onsoundend = onend;
recognition.onspeechend = onend;
recognition.onresult =on_results;

function on_results(e)
{
	var alternatives = e.results[2];
	for (var i=0; i<alternatives.length; i++)
	document.getElementById("text").innerHTML += "Ati rostit cuvantul: "+ alternatives[i].transcript + ", acuratete: "+alternatives[i].confidence + "
" ;
}
<commit_msg>Update speech.js<commit_after>document.addEventListener("touchstart",on_touch);
document.addEventListener("mousedown",on_touch);

var recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.maxAlternatives =5;

function on_touch()
{
	if(recognition.start){
		recognition.start();
		recognition_started = true;
	}

}
function onend()
{
	recognition.stop();
	recognition_started = false;
}
recognition.onend = onend;
recognition.onsoundend = onend;
recognition.onspeechend = onend;
recognition.onresult =on_results;

function on_results(e)
{
	var alternatives = e.results[2];
	for (var i=0; i<alternatives.length; i++)
		document.getElementById("text").innerHTML += alternatives[i].transcript
	//document.getElementById("text").innerHTML += "Ati rostit cuvantul: "+ alternatives[i].transcript + ", acuratete: "+alternatives[i].confidence + "
" ;
}
<|endoftext|>


<commit_before>/**
 * This package provides general utility functionality.
 *
 * @author Joschi <josua.krause@gmail.com>
 */

jkjs = window.jkjs || {}; // init namespace

jkjs.util = function() {
  var that = this;

  this.WARN_DUP_CALL = false;

  var dupCallMap = {};
  var __flagObj = {};
  /**
   * Detects duplicate calls in quick succession and warns about them.
   * This functionality must be enabled with the WARN_DUP_CALL flag.
   */
  this.warnDupCalls = function(name) {
    if(!that.WARN_DUP_CALL) return;
    if(name in dupCallMap && dupCallMap[name]) {
      console.warn(name + " called more than once in quick succession");
      console.trace();
      if(dupCallMap[name] !== __flagObj) {
        console.warn("first call", dupCallMap[name]);
      }
      return;
    }
    if(Error) {
      dupCallMap[name] = new Error().stack || __flagObj;
    } else {
      dupCallMap[name] = __flagObj;
    }
    setTimeout(function() {
      // we never actually remove elements from the map
      // this would slow down performance -- we can assume that
      // the number of names is small and they are manually defined
      dupCallMap[name] = null;
    }, 0);
  };

  // suitable for SVGs
  this.BIG_NUMBER = 1e8;

  /**
   * Converts a list of classes into an object that can be used by the d3 classed function to activate all those classes.
   *
   * @param classes
   *          The classes as array. null is equivalent to an empty list.
   * @returns {Object} The object activating all classes when given to the d3 classed function.
   */
  this.convertClasses = function(classes) {
    if (!classes)
      return {};
    return classes.reduce(function(obj, c) {
      obj[c] = true;
      return obj;
    }, {});
  }

  /**
   * An implementation to set attributes only when they have changed.
   * This might increase performance for attributes which are expensive to update.
   * This does not work with attribute functions or qualified names.
   */
  this.attr = function(sel, attr) {
    // even without the value checks
    // it is still faster because of optimization
    // (at this point value checks slow everything down)
    Object.keys(attr).forEach(function(key) {
      var value = attr[key];
      if(value === null) {
        sel.each(function() {
          // if(!this.hasAttribute(key)) {
            this.removeAttribute(key);
          // }
        });
      } else {
        sel.each(function() {
          // if(this.getAttribute(key) !== value) {
            this.setAttribute(key, value);
          // }
        });
      }
    });
    return sel;
  };

  /**
   * Returns all GET arguments of the current URL location as key value pairs.
   *
   * @returns {Object} The arguments as keys and values.
   */
  this.getQueryStrings = function() {
    var assoc = {};
    var decode = function(s) {
      return decodeURIComponent(s.replace(/\+/g, " "));
    };
    var queryString = location.search.substring(1);
    var keyValues = queryString.split('&');
    keyValues.forEach(function(e) {
      var key = e.split('=');
      if (key.length > 1) {
        assoc[decode(key[0])] = decode(key[1]);
      }
    });
    return assoc;
  }

  /**
   * Getter.
   *
   * @returns {String} The current URL.
   */
  this.getOwnURL = function() {
    return location.origin + location.pathname;
  }

  /**
   * Whether the given object has no keys.
   *
   * @param obj
   *          The object.
   * @returns {Boolean} Whether the given object has no keys.
   */
  this.isEmpty = function(obj) {
    return Object.keys(obj).length == 0;
  }

  /**
   * Maps elements of an array to an array of results.
   *
   *

   * [a] -> (a -> [b]) -> [b]
   *

   *
   * @param arr
   *          The array to map.
   * @param fun
   *          The mapping function. It gets the current element as argument and is expected to return a list of results.
   * @returns The concatenated list of all result lists.
   */
  this.flatMap = function(arr, fun) {
    return [].concat.apply([], arr.map(fun));
  }

  /**
   * Moves all elements of the given selection to either the front or the back of the parent's children list resulting in
   * different visibility.
   *
   * @param sel
   *          The d3 selection to move.
   * @param toFront
   *          Whether to move to the front or to the back.
   */
  this.toFront = function(sel, toFront) {
    sel.each(function() {
      var obj = this;
      var parent = obj.parentElement;
      if (toFront) {
        parent.appendChild(obj);
      } else {
        parent.insertBefore(obj, parent.firstChild);
      }
    });
  }

  this.rectIntersect = function(rectA, rectB) {
    if(rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) {
      return false;
    }
    return rectB.x + rectB.width  > rectA.x &&
           rectB.y + rectB.height > rectA.y &&
           rectB.x < rectA.x + rectA.width  &&
           rectB.y < rectA.y + rectA.height;
  };

  this.getGrayValue = function(color) {
    return 0.2126 * color.r / 255 + 0.7152 * color.g / 255 + 0.0722 * color.b / 255;
  };

  this.getFontColor = function(color) {
    var grayValue = this.getGrayValue(d3.rgb(color));
    return grayValue > 0.5 ? d3.rgb("black") : d3.rgb("white");
  };

  this.ensureSorted = function(arr) {
    if(!arr.length) return;
    var prev = Number.NEGATIVE_INFINITY;
    for(var i = 0;i < arr.length;i += 1) {
      var v = arr[i];
      if(v < prev) {
        requireSorted(arr);
        return;
      }
      prev = v;
    }
  };

  function requireSorted(arr) {
    console.warn("slow sort test");
    var prev = Number.NEGATIVE_INFINITY;
    var run = false;
    var swapped = [];
    arr.forEach(function(v) {
      if(v < prev) {
        if(!run) {
          swapped.push(prev);
        }
        swapped.push(v);
        run = true;
      } else {
        run = false;
      }
      prev = v;
    });
    if(swapped.length) {
      console.warn("array not sorted", swapped, arr, new Error().stack);
      arr.sort(d3.ascending);
    }
  };

  this.join = function(ixs, add) {
    if(!ixs.length) {
      that.ensureSorted(add);
      return add;
    }
    if(!add.length) {
      that.ensureSorted(ixs);
      return ixs;
    }
    // TODO hacky way -- maybe optimize later
    var tmp = ixs.concat(add);
    tmp.sort(d3.ascending);
    return that.unique(tmp);
  };

  this.unique = function(ixs) {
    if(!ixs.length) return ixs;
    // sorted ixs
    that.ensureSorted(ixs);
    var res = [];
    res.length = ixs.length;
    var prev = ixs[0];
    res[0] = prev;
    var q = 1;
    for(var p = 1;p < ixs.length;p += 1) {
      var cur = ixs[p];
      if(cur !== prev) {
        res[q] = cur;
        q += 1;
        prev = cur;
      }
    }
    if(q < res.length) {
      res.length = q;
    }
    return res;
  };

  this.intersect = function(xs, ys) {
    if(!xs.length || !ys.length) return [];
    // sorted xs and ys
    that.ensureSorted(xs);
    that.ensureSorted(ys);
    var p = 0;
    var q = 0;
    var res = [];
    res.length = Math.min(xs.length, ys.length);
    var i = 0;
    while(p < xs.length && q < ys.length) {
      var a = xs[p];
      var b = ys[q];
      if(a < b) {
        p += 1;
      } else if(b < a) {
        q += 1;
      } else { // a === b
        res[i] = a;
        i += 1;
        p += 1;
        q += 1;
      }
    }
    if(i < res.length) {
      res.length = i;
    }
    return res;
  };

  this.getRemaining = function(ixs, minus) {
    if(!ixs.length || !minus.length) return ixs;
    // sorted ixs and minus
    that.ensureSorted(ixs);
    that.ensureSorted(minus);
    var p = 0;
    var q = 0;
    var res = [];
    res.length = ixs.length;
    var i = 0;
    while(p < ixs.length && q < minus.length) {
      var cur = ixs[p];
      var m = minus[q];
      if(cur < m) {
        res[i] = cur;
        i += 1;
        p += 1;
      } else if(cur > m) {
        q += 1;
      } else { // cur == m
        p += 1;
      }
    }
    var realLength = i + ixs.length - p;
    if(realLength !== res.length) {
      res.length = realLength;
    }
    for(;p < ixs.length;p += 1) {
      res[i] = ixs[p];
      i += 1;
    }
    return res;
  };

  this.getRemainingIter = function(ixs, minus, cb) {
    if(!ixs.length || !minus.length) {
      ixs.forEach(cb);
      return;
    }
    // sorted ixs and minus
    that.ensureSorted(ixs);
    that.ensureSorted(minus);
    var p = 0;
    var q = 0;
    while(p < ixs.length && q < minus.length) {
      var cur = ixs[p];
      var m = minus[q];
      if(cur < m) {
        cb(cur);
        p += 1;
      } else if(cur > m) {
        q += 1;
      } else { // cur == m
        p += 1;
      }
    }
    for(;p < ixs.length;p += 1) {
      cb(ixs[p]);
    }
  };

  this.applyPerm = function(arr, perm) {
    var tmp = arr.slice();
    if(tmp.length !== perm.length) console.warn(tmp.length + " != " + perm.length, new Error().stack);
    for(var i = 0;i < perm.length;i += 1) {
      arr[i] = tmp[perm[i]];
    }
  };

  this.randomNorm = function(maxRad, norm) {
    // maxRad should be >= 1e-3
    for(;;) {
      var rnd = ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3; // stddev: ~1, mean: ~0
      if(arguments.length < 1 || maxRad < 1e-3 || Math.abs(rnd) <= maxRad) {
        if(arguments.length >= 2 && norm) {
          return rnd / maxRad;
        }
        return rnd;
      }
    }
  };

  this.timing = function(name, cb, obj, args) {
    var from = new Date().getTime();
    var res = cb.apply(obj, args);
    var to = new Date().getTime();
    if(obj || args) {
      console.log("TIMING " + name, (to - from) + "ms", obj, args);
    } else {
      console.log("TIMING " + name, (to - from) + "ms");
    }
    return res;
  }

  this.shuffle = function(arr, from, to) {
    var f = arguments.length < 2 ? 0 : from;
    var t = arguments.length < 3 ? arr.length : to;
    var i = t;
    while(i > f) {
      var j = Math.floor(Math.random() * (i - f)) + f;
      i -= 1;
      var tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
    }
  };

  this.Randomizer = function(estSize) {
    var arr = [];
    arr.length = estSize;
    var ix = 0;

    this.push = function(el) {
      arr[ix] = el;
      ix += 1;
    };
    this.each = function(cb) {
      that.shuffle(arr, 0, ix);
      for(var i = 0;i < ix;i += 1) {
        cb(arr[i]);
      }
    };
  } // Randomizer

}; // jkjs.util

jkjs.util = new jkjs.util(); // create instance

if(!String.prototype.startsWith) {
  Object.defineProperty(String.prototype, 'startsWith', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(searchString, position) {
      position = position || 0;
      return this.lastIndexOf(searchString, position) === position;
    }
  });
}

Number.isNaN = Number.isNaN || function(value) {
  return typeof value === "number" && value !== value;
}

if(typeof Number.isFinite !== 'function') {
  Number.isFinite = function isFinite(value) {
    if(typeof value !== 'number') return false;
    return !(value !== value || value === Number.NEGATIVE_INFINITY || value === Number.POSITIVE_INFINITY);
  };
}
<commit_msg>remove trailing '/' that chrome adds when there are arguments but no filename<commit_after>/**
 * This package provides general utility functionality.
 *
 * @author Joschi <josua.krause@gmail.com>
 */

jkjs = window.jkjs || {}; // init namespace

jkjs.util = function() {
  var that = this;

  this.WARN_DUP_CALL = false;

  var dupCallMap = {};
  var __flagObj = {};
  /**
   * Detects duplicate calls in quick succession and warns about them.
   * This functionality must be enabled with the WARN_DUP_CALL flag.
   */
  this.warnDupCalls = function(name) {
    if(!that.WARN_DUP_CALL) return;
    if(name in dupCallMap && dupCallMap[name]) {
      console.warn(name + " called more than once in quick succession");
      console.trace();
      if(dupCallMap[name] !== __flagObj) {
        console.warn("first call", dupCallMap[name]);
      }
      return;
    }
    if(Error) {
      dupCallMap[name] = new Error().stack || __flagObj;
    } else {
      dupCallMap[name] = __flagObj;
    }
    setTimeout(function() {
      // we never actually remove elements from the map
      // this would slow down performance -- we can assume that
      // the number of names is small and they are manually defined
      dupCallMap[name] = null;
    }, 0);
  };

  // suitable for SVGs
  this.BIG_NUMBER = 1e8;

  /**
   * Converts a list of classes into an object that can be used by the d3 classed function to activate all those classes.
   *
   * @param classes
   *          The classes as array. null is equivalent to an empty list.
   * @returns {Object} The object activating all classes when given to the d3 classed function.
   */
  this.convertClasses = function(classes) {
    if (!classes)
      return {};
    return classes.reduce(function(obj, c) {
      obj[c] = true;
      return obj;
    }, {});
  }

  /**
   * An implementation to set attributes only when they have changed.
   * This might increase performance for attributes which are expensive to update.
   * This does not work with attribute functions or qualified names.
   */
  this.attr = function(sel, attr) {
    // even without the value checks
    // it is still faster because of optimization
    // (at this point value checks slow everything down)
    Object.keys(attr).forEach(function(key) {
      var value = attr[key];
      if(value === null) {
        sel.each(function() {
          // if(!this.hasAttribute(key)) {
            this.removeAttribute(key);
          // }
        });
      } else {
        sel.each(function() {
          // if(this.getAttribute(key) !== value) {
            this.setAttribute(key, value);
          // }
        });
      }
    });
    return sel;
  };

  /**
   * Returns all GET arguments of the current URL location as key value pairs.
   *
   * @returns {Object} The arguments as keys and values.
   */
  this.getQueryStrings = function() {
    var assoc = {};
    var decode = function(s) {
      return decodeURIComponent(s.replace(/\+/g, " "));
    };
    var queryString = location.search.substring(1);
    var keyValues = queryString.split('&');
    keyValues.forEach(function(e) {
      var key = e.split('=');
      if (key.length > 1) {
        assoc[decode(key[0])] = decode(key[1]).replace(/\/+$/,'');
      }
    });
    return assoc;
  }

  /**
   * Getter.
   *
   * @returns {String} The current URL.
   */
  this.getOwnURL = function() {
    return location.origin + location.pathname;
  }

  /**
   * Whether the given object has no keys.
   *
   * @param obj
   *          The object.
   * @returns {Boolean} Whether the given object has no keys.
   */
  this.isEmpty = function(obj) {
    return Object.keys(obj).length == 0;
  }

  /**
   * Maps elements of an array to an array of results.
   *
   *

   * [a] -> (a -> [b]) -> [b]
   *

   *
   * @param arr
   *          The array to map.
   * @param fun
   *          The mapping function. It gets the current element as argument and is expected to return a list of results.
   * @returns The concatenated list of all result lists.
   */
  this.flatMap = function(arr, fun) {
    return [].concat.apply([], arr.map(fun));
  }

  /**
   * Moves all elements of the given selection to either the front or the back of the parent's children list resulting in
   * different visibility.
   *
   * @param sel
   *          The d3 selection to move.
   * @param toFront
   *          Whether to move to the front or to the back.
   */
  this.toFront = function(sel, toFront) {
    sel.each(function() {
      var obj = this;
      var parent = obj.parentElement;
      if (toFront) {
        parent.appendChild(obj);
      } else {
        parent.insertBefore(obj, parent.firstChild);
      }
    });
  }

  this.rectIntersect = function(rectA, rectB) {
    if(rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) {
      return false;
    }
    return rectB.x + rectB.width  > rectA.x &&
           rectB.y + rectB.height > rectA.y &&
           rectB.x < rectA.x + rectA.width  &&
           rectB.y < rectA.y + rectA.height;
  };

  this.getGrayValue = function(color) {
    return 0.2126 * color.r / 255 + 0.7152 * color.g / 255 + 0.0722 * color.b / 255;
  };

  this.getFontColor = function(color) {
    var grayValue = this.getGrayValue(d3.rgb(color));
    return grayValue > 0.5 ? d3.rgb("black") : d3.rgb("white");
  };

  this.ensureSorted = function(arr) {
    if(!arr.length) return;
    var prev = Number.NEGATIVE_INFINITY;
    for(var i = 0;i < arr.length;i += 1) {
      var v = arr[i];
      if(v < prev) {
        requireSorted(arr);
        return;
      }
      prev = v;
    }
  };

  function requireSorted(arr) {
    console.warn("slow sort test");
    var prev = Number.NEGATIVE_INFINITY;
    var run = false;
    var swapped = [];
    arr.forEach(function(v) {
      if(v < prev) {
        if(!run) {
          swapped.push(prev);
        }
        swapped.push(v);
        run = true;
      } else {
        run = false;
      }
      prev = v;
    });
    if(swapped.length) {
      console.warn("array not sorted", swapped, arr, new Error().stack);
      arr.sort(d3.ascending);
    }
  };

  this.join = function(ixs, add) {
    if(!ixs.length) {
      that.ensureSorted(add);
      return add;
    }
    if(!add.length) {
      that.ensureSorted(ixs);
      return ixs;
    }
    // TODO hacky way -- maybe optimize later
    var tmp = ixs.concat(add);
    tmp.sort(d3.ascending);
    return that.unique(tmp);
  };

  this.unique = function(ixs) {
    if(!ixs.length) return ixs;
    // sorted ixs
    that.ensureSorted(ixs);
    var res = [];
    res.length = ixs.length;
    var prev = ixs[0];
    res[0] = prev;
    var q = 1;
    for(var p = 1;p < ixs.length;p += 1) {
      var cur = ixs[p];
      if(cur !== prev) {
        res[q] = cur;
        q += 1;
        prev = cur;
      }
    }
    if(q < res.length) {
      res.length = q;
    }
    return res;
  };

  this.intersect = function(xs, ys) {
    if(!xs.length || !ys.length) return [];
    // sorted xs and ys
    that.ensureSorted(xs);
    that.ensureSorted(ys);
    var p = 0;
    var q = 0;
    var res = [];
    res.length = Math.min(xs.length, ys.length);
    var i = 0;
    while(p < xs.length && q < ys.length) {
      var a = xs[p];
      var b = ys[q];
      if(a < b) {
        p += 1;
      } else if(b < a) {
        q += 1;
      } else { // a === b
        res[i] = a;
        i += 1;
        p += 1;
        q += 1;
      }
    }
    if(i < res.length) {
      res.length = i;
    }
    return res;
  };

  this.getRemaining = function(ixs, minus) {
    if(!ixs.length || !minus.length) return ixs;
    // sorted ixs and minus
    that.ensureSorted(ixs);
    that.ensureSorted(minus);
    var p = 0;
    var q = 0;
    var res = [];
    res.length = ixs.length;
    var i = 0;
    while(p < ixs.length && q < minus.length) {
      var cur = ixs[p];
      var m = minus[q];
      if(cur < m) {
        res[i] = cur;
        i += 1;
        p += 1;
      } else if(cur > m) {
        q += 1;
      } else { // cur == m
        p += 1;
      }
    }
    var realLength = i + ixs.length - p;
    if(realLength !== res.length) {
      res.length = realLength;
    }
    for(;p < ixs.length;p += 1) {
      res[i] = ixs[p];
      i += 1;
    }
    return res;
  };

  this.getRemainingIter = function(ixs, minus, cb) {
    if(!ixs.length || !minus.length) {
      ixs.forEach(cb);
      return;
    }
    // sorted ixs and minus
    that.ensureSorted(ixs);
    that.ensureSorted(minus);
    var p = 0;
    var q = 0;
    while(p < ixs.length && q < minus.length) {
      var cur = ixs[p];
      var m = minus[q];
      if(cur < m) {
        cb(cur);
        p += 1;
      } else if(cur > m) {
        q += 1;
      } else { // cur == m
        p += 1;
      }
    }
    for(;p < ixs.length;p += 1) {
      cb(ixs[p]);
    }
  };

  this.applyPerm = function(arr, perm) {
    var tmp = arr.slice();
    if(tmp.length !== perm.length) console.warn(tmp.length + " != " + perm.length, new Error().stack);
    for(var i = 0;i < perm.length;i += 1) {
      arr[i] = tmp[perm[i]];
    }
  };

  this.randomNorm = function(maxRad, norm) {
    // maxRad should be >= 1e-3
    for(;;) {
      var rnd = ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3; // stddev: ~1, mean: ~0
      if(arguments.length < 1 || maxRad < 1e-3 || Math.abs(rnd) <= maxRad) {
        if(arguments.length >= 2 && norm) {
          return rnd / maxRad;
        }
        return rnd;
      }
    }
  };

  this.timing = function(name, cb, obj, args) {
    var from = new Date().getTime();
    var res = cb.apply(obj, args);
    var to = new Date().getTime();
    if(obj || args) {
      console.log("TIMING " + name, (to - from) + "ms", obj, args);
    } else {
      console.log("TIMING " + name, (to - from) + "ms");
    }
    return res;
  }

  this.shuffle = function(arr, from, to) {
    var f = arguments.length < 2 ? 0 : from;
    var t = arguments.length < 3 ? arr.length : to;
    var i = t;
    while(i > f) {
      var j = Math.floor(Math.random() * (i - f)) + f;
      i -= 1;
      var tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
    }
  };

  this.Randomizer = function(estSize) {
    var arr = [];
    arr.length = estSize;
    var ix = 0;

    this.push = function(el) {
      arr[ix] = el;
      ix += 1;
    };
    this.each = function(cb) {
      that.shuffle(arr, 0, ix);
      for(var i = 0;i < ix;i += 1) {
        cb(arr[i]);
      }
    };
  } // Randomizer

}; // jkjs.util

jkjs.util = new jkjs.util(); // create instance

if(!String.prototype.startsWith) {
  Object.defineProperty(String.prototype, 'startsWith', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(searchString, position) {
      position = position || 0;
      return this.lastIndexOf(searchString, position) === position;
    }
  });
}

Number.isNaN = Number.isNaN || function(value) {
  return typeof value === "number" && value !== value;
}

if(typeof Number.isFinite !== 'function') {
  Number.isFinite = function isFinite(value) {
    if(typeof value !== 'number') return false;
    return !(value !== value || value === Number.NEGATIVE_INFINITY || value === Number.POSITIVE_INFINITY);
  };
}
<|endoftext|>


<commit_before>/**
* Functions and callbacks
*/
var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL 	= "https://news.ycombinator.com/" + commentPath;
		showComments( frameURL )
	}
}

var showComments = function( URL ) {
	var commentFrame,
		frameset;

	frameset = document.querySelector( "frameset" );
	frameset.setAttribute( "cols", "50%,50%" );
	commentFrame = document.querySelector( "#comment-frame" );
	commentFrame.setAttribute( "src", URL );
	console.log("showComments has run");
}

var iframeOpen = function() {

}

var drawIframe = function() {
	var frameset,
		pageURL,
		pageFrame,
		commentFrame,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
	frameset = document.createElement( "frameset" );
	pageFrame = document.createElement( "frame" );
	commentFrame = document.createElement( "frame" );
	pageFrame.setAttribute( "id", "page-frame" );
	commentFrame.setAttribute( "id", "comment-frame" );
	pageURL = document.URL;

	if ( body )
		body.parentNode.removeChild( body );

	frameset.appendChild( pageFrame );
	frameset.appendChild( commentFrame );
	frameset.setAttribute( "cols", "100%,0%" );
	html.appendChild( frameset );

	pageFrame.setAttribute( "src", pageURL );
}

/**
* Events
*/
drawIframe();
window.addEventListener("message", receiveMessage, false);<commit_msg>Succesfully implemented comment toggle.<commit_after>/**
* Variables
*/
var iframeOpen;

/**
* Functions and callbacks
*/
var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL 	= "https://news.ycombinator.com/" + commentPath;
		toggleComments( frameURL )
	}
}

var toggleComments = function( URL ) {
	var commentFrame,
		frameset,
		frameHasSrc;
	console.log("click occurred")
	frameset = document.querySelector( "frameset" );
	commentFrame = document.querySelector( "#comment-frame" );
	frameHasSrc = commentFrame.getAttribute("src");

	// set frame src if none is present
	if ( ! frameHasSrc ) {
		commentFrame.setAttribute( "src", URL );
	}

	// open/close iframe
	if ( iframeOpen ) {
		frameset.setAttribute( "cols", "100%,0%" );
	} else {
		frameset.setAttribute( "cols", "50%,50%" );
	}

	// toggle iframeOpen flag
	iframeOpen = Math.abs( iframeOpen - 1 );

}

var drawIframe = function() {
	var frameset,
		pageURL,
		pageFrame,
		commentFrame,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
	frameset = document.createElement( "frameset" );
	pageFrame = document.createElement( "frame" );
	commentFrame = document.createElement( "frame" );
	pageFrame.setAttribute( "id", "page-frame" );
	commentFrame.setAttribute( "id", "comment-frame" );
	pageURL = document.URL;

	if ( body )
		body.parentNode.removeChild( body );

	frameset.appendChild( pageFrame );
	frameset.appendChild( commentFrame );
	frameset.setAttribute( "cols", "100%,0%" );
	html.appendChild( frameset );

	pageFrame.setAttribute( "src", pageURL );
}

/**
* Events
*/
iframeOpen = 0;
drawIframe();
window.addEventListener("message", receiveMessage, false);<|endoftext|>


<commit_before>$(document).ready(function(){

  //variables
   var name = $("#nom");
       email = $("#email");
       comment = $(".palabras textarea");
       modal_name = $(".modal span");
       modal = $(".modal");

   //hide modal
    modal.hide();

   //check if name is empty
   name.on("blur",function(){
    var $this = $(this);
    if($this.val().length === 0 ||
       $this.val() === "Nom"){
        $this.addClass("noValid");
        $this.val("");
    } else{
        $this.addClass("valid");
      }
   });

    //check if email is empty
  email.on("blur",function(){
    var $this = $(this);
    if($this.val().length === 0 ||
       $this.val() === "Email"){
      $this.addClass("noValid");
        }
  });

    //check if email is valid
  email.on("blur",function(){
    var $this = $(this);
    if($this.val().indexOf("." && "@") > -1){
       $this.addClass("valid");
    } else{
        $this.addClass("noValid");
        $this.val("Email");
    }
  });

    //check if textarea is empty
  comment.on("blur",function(){
    var $this = $(this);
    if($this.val() === ""){
      $this.addClass("noValid");
      $this.val("Comments");
    } else{
      $this.addClass("valid");
    }
 });

    //clear inputs on click
    $(".input").on("focus",function(){
        $(this).val("");
    });

    //show modal when inputs are valid and button
    //is clicked
  $(".submit").on("click",function(){
    if(name.val() !== "Name" && name.val() !== "" &&
       email.val() !== "Email" &&
       email.val() !== "" &&
       comment.val() !== "Comments" &&
       comment.val()!== ""){

          //remove invalid/valid classes
          name.removeClass().addClass("input");
          email.removeClass().addClass("input");
          comment.removeClass().addClass("input");

          //modal box
          modal_name.text(name.val());
          modal.slideDown("medium")
            .delay(2000).slideUp("fast");

          //put default text back
          name.val("Name");
          email.val("Email");
          comment.val("Comments");

          return false;

    } else{

        return false; }
    });

});
<commit_msg>Afegit validació de cognom.<commit_after>$(document).ready(function(){

  //variables
  var nom = $("#nom");
  cognom = $("#cognom");
  email = $("#email");
  comment = $(".palabras textarea");

   //Comprova si el NOM esta buit
   nom.on("blur",function(){
    var $this = $(this);
    if($this.val().length === 0 ||
     $this.val() === "Nom"){
      $this.addClass("noValid");
    $this.val("");
  } else{
    $this.addClass("valid");
  }
});

   cognom.on("blur",function(){
    var $this = $(this);
    if($this.val().length === 0 ||
     $this.val() === "Nom"){
      $this.addClass("noValid");
    $this.val("");
  } else{
    $this.addClass("valid");
  }
});

    //Comprova si el EMAIL esta buit
    email.on("blur",function(){
      var $this = $(this);
      if($this.val().length === 0 ||
       $this.val() === "Email"){
        $this.addClass("noValid");
    }
  });

    //Comprova si l'EMAIL es valid
    email.on("blur",function(){
      var $this = $(this);
      if($this.val().indexOf("." && "@") > -1){
       $this.addClass("valid");
     } else{
      $this.addClass("noValid");
      $this.val("Email");
    }
  });

    //check if textarea is empty
    comment.on("blur",function(){
      var $this = $(this);
      if($this.val() === ""){
        $this.addClass("noValid");
        $this.val("Comments");
      } else{
        $this.addClass("valid");
      }
    });

    //clear inputs on click
    $(".input").on("focus",function(){
      $(this).val("");
    });

    //show modal when inputs are valid and button
    //is clicked
    $(".submit").on("click",function(){
      if(name.val() !== "Name" && name.val() !== "" &&
       email.val() !== "Email" &&
       email.val() !== "" &&
       comment.val() !== "Comments" &&
       comment.val()!== ""){

          //remove invalid/valid classes
        name.removeClass().addClass("input");
        email.removeClass().addClass("input");
        comment.removeClass().addClass("input");

          //modal box
          modal_name.text(name.val());
          modal.slideDown("medium")
          .delay(2000).slideUp("fast");

          //put default text back
          name.val("Name");
          email.val("Email");
          comment.val("Comments");

          return false;

        } else{

          return false; }
        });

  });
<|endoftext|>


<commit_before>'use strict';

angular.module('todoApp', [])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .when('/active', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .when('/completed', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });<commit_msg>added serveries page<commit_after>'use strict';

angular.module('todoApp', [])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .when('/active', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .when('/completed', {
        templateUrl: 'static/views/main.html',
        controller: 'MainCtrl'
      })
      .when('/serveries', {
        templateUrl: 'static/views/serveries.html',
        controller: 'ServeriesCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });<|endoftext|>


<commit_before>import $ from 'jquery';

document.addEventListener( 'turbolinks:load', () => {
    if (document.querySelector('body.search.index')) {
        const algoliasearch = require('algoliasearch');
        const tab = document.querySelector('#tab').innerHTML;
        const client = algoliasearch( algoliasearchApplicationId, algoliasearchSearchKey );
        document.querySelector('input#__query').addEventListener( 'input', function() {
            document.querySelector('.myg-grid').innerHTML = '';
            if (this.value) {
                search( this.value, tab );
                if ( tab == 'quantity' ) {
                    search( this.value, 'constant' );
                }
            } else {
                render(tab);
            }
        })
    }
})

function search( query, tab ) {
    let index = client.initIndex( tab[0].toUpperCase() + tab.substring(1) );
    index.search( query, ( err, content ) => {
        if (content.hits.length > 0) {
            console.log(content.hits);
            render(tab);
        } else {
            render( tab, content.hits );
        }
    });
}
function render( tab, content = null ) {
    $.get( '/app/search', { tab: tab, content: content }, (data) => {
        $('.myg-grid').append(data);
    });
}
<commit_msg>fix search<commit_after>import $ from 'jquery';

document.addEventListener( 'turbolinks:load', () => {
    if (document.querySelector('body.search.index')) {
        const algoliasearch = require('algoliasearch');
        const tab = document.querySelector('#tab').innerHTML;
        const client = algoliasearch( algoliasearchApplicationId, algoliasearchSearchKey );
        document.querySelector('input#__query').addEventListener( 'input', function() {
            document.querySelector('.myg-grid').innerHTML = '';
            if (this.value) {
                search( client, this.value, tab );
                if ( tab == 'quantity' ) {
                    search( client, this.value, 'constant' );
                }
            } else {
                render(tab);
            }
        })
    }
})

function search( client, query, tab ) {
    let index = client.initIndex( tab[0].toUpperCase() + tab.substring(1) );
    index.search( query, ( err, content ) => {
        if (content.hits.length > 0) {
            console.log(content.hits);
            render(tab);
        } else {
            render( tab, content.hits );
        }
    });
}
function render( tab, content = null ) {
    $.get( '/app/search', { tab: tab, content: content }, (data) => {
        $('.myg-grid').append(data);
    });
}
<|endoftext|>