<commit_before>/*
 * This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on
 * the page have a hint marker displayed containing a sequence of letters. Typing those letters will select
 * a link.
 *
 * The characters we use to show link hints are a user-configurable option. By default they're the home row.
 * The CSS which is used on the link hints is also a configurable option.
 */

var hintMarkers = [];
var hintMarkerContainingDiv = null;
// The characters that were typed in while in "link hints" mode.
var hintKeystrokeQueue = [];
var linkHintsModeActivated = false;
var shouldOpenLinkHintInNewTab = false;
// Whether we have added to the page the CSS needed to display link hints.
var linkHintsCssAdded = false;

// An XPath describing what a clickable element is. We could also look for images with an onclick
// attribute, but let's wait to see if that really is necessary.
var clickableElementsXPath = "//a | //textarea | //button | //select | //input[not(@type='hidden')] | //*[@onclick]";

// We need this as a top-level function because our command system doesn't yet support arguments.
function activateLinkHintsModeToOpenInNewTab() { activateLinkHintsMode(true); }

function activateLinkHintsMode(openInNewTab) {
  if (!linkHintsCssAdded)
    addCssToPage(linkHintCss); // linkHintCss is declared by vimiumFrontend.js
  linkHintCssAdded = true;
  linkHintsModeActivated = true;
  shouldOpenLinkHintInNewTab = openInNewTab
  buildLinkHints();
  document.addEventListener("keydown", onKeyDownInLinkHintsMode, true);
}

/*
 * Builds and displays link hints for every visible clickable item on the page.
 */
function buildLinkHints() {
  var visibleElements = getVisibleClickableElements();

  // Initialize the number used to generate the character hints to be as many digits as we need to
  // highlight all the links on the page; we don't want some link hints to have more chars than others.
  var digitsNeeded = Math.ceil(logXOfBase(visibleElements.length, settings.linkHintCharacters.length));
  var linkHintNumber = 0;
  for (var i = 0; i < visibleElements.length; i++) {
    hintMarkers.push(createMarkerFor(visibleElements[i], linkHintNumber, digitsNeeded));
    linkHintNumber++;
  }
  // Note(philc): Append these markers as top level children instead of as child nodes to the link itself,
  // because some clickable elements cannot contain children, e.g. submit buttons. This has the caveat
  // that if you scroll the page and the link has position=fixed, the marker will not stay fixed.
  // Also note that adding these nodes to document.body all at once is significantly faster than one-by-one.
  hintMarkerContainingDiv = document.createElement("div");
  hintMarkerContainingDiv.className = "internalVimiumHintMarker";
  for (var i = 0; i < hintMarkers.length; i++)
    hintMarkerContainingDiv.appendChild(hintMarkers[i]);
  document.body.appendChild(hintMarkerContainingDiv);
}

function logXOfBase(x, base) { return Math.log(x) / Math.log(base); }

/*
 * Returns all clickable elements that are not hidden and are in the current viewport.
 * We prune invisible elements partly for performance reasons, but moreso it's to decrease the number
 * of digits needed to enumerate all of the links on screen.
 */
function getVisibleClickableElements() {
  var resultSet = document.evaluate(clickableElementsXPath, document.body, null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var visibleElements = [];

  // Prune all invisible clickable elements.
  for (var i = 0; i < resultSet.snapshotLength; i++) {
    var element = resultSet.snapshotItem(i);

    // Note that getBoundingClientRect() is relative to the viewport
    var boundingRect = element.getBoundingClientRect();
    // Exclude links which have just a few pixels on screen, because the link hints won't show for them anyway.
    if (boundingRect.bottom <= 4 || boundingRect.top >= window.innerHeight - 4 ||
        boundingRect.left <= 0 || boundingRect.left >= window.innerWidth - 4)
      continue;

    if (boundingRect.width < 3 || boundingRect.height < 3)
      continue;

    // eliminate invisible elements (see test_harnesses/visibility_test.html)
    var computedStyle = window.getComputedStyle(element, null);
    if (computedStyle.getPropertyValue('visibility') != 'visible' ||
        computedStyle.getPropertyValue('display') == 'none')
      continue;

    var clientRect = element.getClientRects()[0];
    if (!clientRect)
        continue;

    visibleElements.push(element);
  }
  return visibleElements;
}

function onKeyDownInLinkHintsMode(event) {
  var keyChar = getKeyChar(event);
  if (!keyChar)
    return;

  // TODO(philc): Ignore keys that have modifiers.
  if (isEscape(event)) {
    deactivateLinkHintsMode();
  } else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey) {
    if (hintKeystrokeQueue.length == 0) {
      deactivateLinkHintsMode();
    } else {
      hintKeystrokeQueue.pop();
      updateLinkHints();
    }
  } else if (settings.linkHintCharacters.indexOf(keyChar) >= 0) {
    hintKeystrokeQueue.push(keyChar);
    updateLinkHints();
  } else {
    return;
  }

  event.stopPropagation();
  event.preventDefault();
}

/*
 * Updates the visibility of link hints on screen based on the keystrokes typed thus far. If only one
 * link hint remains, click on that link and exit link hints mode.
 */
function updateLinkHints() {
  var matchString = hintKeystrokeQueue.join("");
  var linksMatched = highlightLinkMatches(matchString);
  if (linksMatched.length == 0)
    deactivateLinkHintsMode();
  else if (linksMatched.length == 1) {
    var matchedLink = linksMatched[0];
    if (isSelectable(matchedLink)) {
      matchedLink.focus();
      // When focusing a textbox, put the selection caret at the end of the textbox's contents.
      matchedLink.setSelectionRange(matchedLink.value.length, matchedLink.value.length);
    } else {
      // When we're opening the link in the current tab, don't navigate to the selected link immediately;
      // we want to give the user some feedback depicting which link they've selected by focusing it.
      if (!shouldOpenLinkHintInNewTab)
        setTimeout(function() { simulateClick(matchedLink); }, 400);
      else
        simulateClick(matchedLink);
      matchedLink.focus();
    }
    deactivateLinkHintsMode();
  }
}

/*
 * Selectable means the element has a text caret; this is not the same as "focusable".
 */
function isSelectable(element) {
  var selectableTypes = ["search", "text", "password"];
  return (element.tagName == "INPUT" && selectableTypes.indexOf(element.type) >= 0) ||
      element.tagName == "TEXTAREA";
}

/*
 * Hides link hints which do not match the given search string. To allow the backspace key to work, this
 * will also show link hints which do match but were previously hidden.
 */
function highlightLinkMatches(searchString) {
  var linksMatched = [];
  for (var i = 0; i < hintMarkers.length; i++) {
    var linkMarker = hintMarkers[i];
    if (linkMarker.getAttribute("hintString").indexOf(searchString) == 0) {
      if (linkMarker.style.display == "none")
        linkMarker.style.display = "";
      for (var j = 0; j < linkMarker.childNodes.length; j++)
        linkMarker.childNodes[j].className = (j >= searchString.length) ? "" : "matchingCharacter";
      linksMatched.push(linkMarker.clickableItem);
    } else {
      linkMarker.style.display = "none";
    }
  }
  return linksMatched;
}

/*
 * Converts a number like "8" into a hint string like "JK". This is used to sequentially generate all of
 * the hint text. The hint string will be "padded with zeroes" to ensure its length is equal to numHintDigits.
 */
function numberToHintString(number, numHintDigits) {
  var base = settings.linkHintCharacters.length;
  var hintString = [];
  var remainder = 0;
  do {
    remainder = number % base;
    hintString.unshift(settings.linkHintCharacters[remainder]);
    number -= remainder;
    number /= Math.floor(base);
  } while (number > 0);

  // Pad the hint string we're returning so that it matches numHintDigits.
  var hintStringLength = hintString.length;
  for (var i = 0; i < numHintDigits - hintStringLength; i++)
    hintString.unshift(settings.linkHintCharacters[0]);
  return hintString.join("");
}

function simulateClick(link) {
  var event = document.createEvent("MouseEvents");
  // When "clicking" on a link, dispatch the event with the appropriate meta key (CMD on Mac, CTRL on windows)
  // to open it in a new tab if necessary.
  var metaKey = (platform == "Mac" && shouldOpenLinkHintInNewTab);
  var ctrlKey = (platform != "Mac" && shouldOpenLinkHintInNewTab);
  event.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, ctrlKey, false, false, metaKey, 0, null);

  // Debugging note: Firefox will not execute the link's default action if we dispatch this click event,
  // but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
  link.dispatchEvent(event);
}

function deactivateLinkHintsMode() {
  if (hintMarkerContainingDiv)
    hintMarkerContainingDiv.parentNode.removeChild(hintMarkerContainingDiv);
  hintMarkerContainingDiv = null;
  hintMarkers = [];
  hintKeystrokeQueue = [];
  document.removeEventListener("keydown", onKeyDownInLinkHintsMode, true);
  linkHintsModeActivated = false;
}

/*
 * Creates a link marker for the given link.
 */
function createMarkerFor(link, linkHintNumber, linkHintDigits) {
  var hintString = numberToHintString(linkHintNumber, linkHintDigits);
  var marker = document.createElement("div");
  marker.className = "internalVimiumHintMarker vimiumHintMarker";
  var innerHTML = [];
  // Make each hint character a span, so that we can highlight the typed characters as you type them.
  for (var i = 0; i < hintString.length; i++)
    innerHTML.push("<span>" + hintString[i].toUpperCase() + "</span>");
  marker.innerHTML = innerHTML.join("");
  marker.setAttribute("hintString", hintString);

  // Note: this call will be expensive if we modify the DOM in between calls.
  var clientRect = link.getClientRects()[0];
  // The coordinates given by the window do not have the zoom factor included since the zoom is set only on
  // the document node.
  var zoomFactor = currentZoomLevel / 100.0;
  marker.style.left = clientRect.left + window.scrollX / zoomFactor + "px";
  marker.style.top = clientRect.top  + window.scrollY / zoomFactor + "px";

  marker.clickableItem = link;
  return marker;
}
<commit_msg>Factor in zoom when eliminating offscreen links<commit_after>/*
 * This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on
 * the page have a hint marker displayed containing a sequence of letters. Typing those letters will select
 * a link.
 *
 * The characters we use to show link hints are a user-configurable option. By default they're the home row.
 * The CSS which is used on the link hints is also a configurable option.
 */

var hintMarkers = [];
var hintMarkerContainingDiv = null;
// The characters that were typed in while in "link hints" mode.
var hintKeystrokeQueue = [];
var linkHintsModeActivated = false;
var shouldOpenLinkHintInNewTab = false;
// Whether we have added to the page the CSS needed to display link hints.
var linkHintsCssAdded = false;

// An XPath describing what a clickable element is. We could also look for images with an onclick
// attribute, but let's wait to see if that really is necessary.
var clickableElementsXPath = "//a | //textarea | //button | //select | //input[not(@type='hidden')] | //*[@onclick]";

// We need this as a top-level function because our command system doesn't yet support arguments.
function activateLinkHintsModeToOpenInNewTab() { activateLinkHintsMode(true); }

function activateLinkHintsMode(openInNewTab) {
  if (!linkHintsCssAdded)
    addCssToPage(linkHintCss); // linkHintCss is declared by vimiumFrontend.js
  linkHintCssAdded = true;
  linkHintsModeActivated = true;
  shouldOpenLinkHintInNewTab = openInNewTab
  buildLinkHints();
  document.addEventListener("keydown", onKeyDownInLinkHintsMode, true);
}

/*
 * Builds and displays link hints for every visible clickable item on the page.
 */
function buildLinkHints() {
  var visibleElements = getVisibleClickableElements();

  // Initialize the number used to generate the character hints to be as many digits as we need to
  // highlight all the links on the page; we don't want some link hints to have more chars than others.
  var digitsNeeded = Math.ceil(logXOfBase(visibleElements.length, settings.linkHintCharacters.length));
  var linkHintNumber = 0;
  for (var i = 0; i < visibleElements.length; i++) {
    hintMarkers.push(createMarkerFor(visibleElements[i], linkHintNumber, digitsNeeded));
    linkHintNumber++;
  }
  // Note(philc): Append these markers as top level children instead of as child nodes to the link itself,
  // because some clickable elements cannot contain children, e.g. submit buttons. This has the caveat
  // that if you scroll the page and the link has position=fixed, the marker will not stay fixed.
  // Also note that adding these nodes to document.body all at once is significantly faster than one-by-one.
  hintMarkerContainingDiv = document.createElement("div");
  hintMarkerContainingDiv.className = "internalVimiumHintMarker";
  for (var i = 0; i < hintMarkers.length; i++)
    hintMarkerContainingDiv.appendChild(hintMarkers[i]);
  document.body.appendChild(hintMarkerContainingDiv);
}

function logXOfBase(x, base) { return Math.log(x) / Math.log(base); }

/*
 * Returns all clickable elements that are not hidden and are in the current viewport.
 * We prune invisible elements partly for performance reasons, but moreso it's to decrease the number
 * of digits needed to enumerate all of the links on screen.
 */
function getVisibleClickableElements() {
  var resultSet = document.evaluate(clickableElementsXPath, document.body, null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var visibleElements = [];

  // Prune all invisible clickable elements.
  for (var i = 0; i < resultSet.snapshotLength; i++) {
    var element = resultSet.snapshotItem(i);

    // Note that getBoundingClientRect() is relative to the viewport
    var boundingRect = element.getBoundingClientRect();
    // Exclude links which have just a few pixels on screen, because the link hints won't show for them anyway.
    var zoomFactor = currentZoomLevel / 100.0;
    if (boundingRect.bottom <= 4 || boundingRect.top * zoomFactor >= window.innerHeight - 4 ||
        boundingRect.left <= 0 || boundingRect.left * zoomFactor >= window.innerWidth - 4)
      continue;

    if (boundingRect.width < 3 || boundingRect.height < 3)
      continue;

    // eliminate invisible elements (see test_harnesses/visibility_test.html)
    var computedStyle = window.getComputedStyle(element, null);
    if (computedStyle.getPropertyValue('visibility') != 'visible' ||
        computedStyle.getPropertyValue('display') == 'none')
      continue;

    var clientRect = element.getClientRects()[0];
    if (!clientRect)
        continue;

    visibleElements.push(element);
  }
  return visibleElements;
}

function onKeyDownInLinkHintsMode(event) {
  var keyChar = getKeyChar(event);
  if (!keyChar)
    return;

  // TODO(philc): Ignore keys that have modifiers.
  if (isEscape(event)) {
    deactivateLinkHintsMode();
  } else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey) {
    if (hintKeystrokeQueue.length == 0) {
      deactivateLinkHintsMode();
    } else {
      hintKeystrokeQueue.pop();
      updateLinkHints();
    }
  } else if (settings.linkHintCharacters.indexOf(keyChar) >= 0) {
    hintKeystrokeQueue.push(keyChar);
    updateLinkHints();
  } else {
    return;
  }

  event.stopPropagation();
  event.preventDefault();
}

/*
 * Updates the visibility of link hints on screen based on the keystrokes typed thus far. If only one
 * link hint remains, click on that link and exit link hints mode.
 */
function updateLinkHints() {
  var matchString = hintKeystrokeQueue.join("");
  var linksMatched = highlightLinkMatches(matchString);
  if (linksMatched.length == 0)
    deactivateLinkHintsMode();
  else if (linksMatched.length == 1) {
    var matchedLink = linksMatched[0];
    if (isSelectable(matchedLink)) {
      matchedLink.focus();
      // When focusing a textbox, put the selection caret at the end of the textbox's contents.
      matchedLink.setSelectionRange(matchedLink.value.length, matchedLink.value.length);
    } else {
      // When we're opening the link in the current tab, don't navigate to the selected link immediately;
      // we want to give the user some feedback depicting which link they've selected by focusing it.
      if (!shouldOpenLinkHintInNewTab)
        setTimeout(function() { simulateClick(matchedLink); }, 400);
      else
        simulateClick(matchedLink);
      matchedLink.focus();
    }
    deactivateLinkHintsMode();
  }
}

/*
 * Selectable means the element has a text caret; this is not the same as "focusable".
 */
function isSelectable(element) {
  var selectableTypes = ["search", "text", "password"];
  return (element.tagName == "INPUT" && selectableTypes.indexOf(element.type) >= 0) ||
      element.tagName == "TEXTAREA";
}

/*
 * Hides link hints which do not match the given search string. To allow the backspace key to work, this
 * will also show link hints which do match but were previously hidden.
 */
function highlightLinkMatches(searchString) {
  var linksMatched = [];
  for (var i = 0; i < hintMarkers.length; i++) {
    var linkMarker = hintMarkers[i];
    if (linkMarker.getAttribute("hintString").indexOf(searchString) == 0) {
      if (linkMarker.style.display == "none")
        linkMarker.style.display = "";
      for (var j = 0; j < linkMarker.childNodes.length; j++)
        linkMarker.childNodes[j].className = (j >= searchString.length) ? "" : "matchingCharacter";
      linksMatched.push(linkMarker.clickableItem);
    } else {
      linkMarker.style.display = "none";
    }
  }
  return linksMatched;
}

/*
 * Converts a number like "8" into a hint string like "JK". This is used to sequentially generate all of
 * the hint text. The hint string will be "padded with zeroes" to ensure its length is equal to numHintDigits.
 */
function numberToHintString(number, numHintDigits) {
  var base = settings.linkHintCharacters.length;
  var hintString = [];
  var remainder = 0;
  do {
    remainder = number % base;
    hintString.unshift(settings.linkHintCharacters[remainder]);
    number -= remainder;
    number /= Math.floor(base);
  } while (number > 0);

  // Pad the hint string we're returning so that it matches numHintDigits.
  var hintStringLength = hintString.length;
  for (var i = 0; i < numHintDigits - hintStringLength; i++)
    hintString.unshift(settings.linkHintCharacters[0]);
  return hintString.join("");
}

function simulateClick(link) {
  var event = document.createEvent("MouseEvents");
  // When "clicking" on a link, dispatch the event with the appropriate meta key (CMD on Mac, CTRL on windows)
  // to open it in a new tab if necessary.
  var metaKey = (platform == "Mac" && shouldOpenLinkHintInNewTab);
  var ctrlKey = (platform != "Mac" && shouldOpenLinkHintInNewTab);
  event.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, ctrlKey, false, false, metaKey, 0, null);

  // Debugging note: Firefox will not execute the link's default action if we dispatch this click event,
  // but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
  link.dispatchEvent(event);
}

function deactivateLinkHintsMode() {
  if (hintMarkerContainingDiv)
    hintMarkerContainingDiv.parentNode.removeChild(hintMarkerContainingDiv);
  hintMarkerContainingDiv = null;
  hintMarkers = [];
  hintKeystrokeQueue = [];
  document.removeEventListener("keydown", onKeyDownInLinkHintsMode, true);
  linkHintsModeActivated = false;
}

/*
 * Creates a link marker for the given link.
 */
function createMarkerFor(link, linkHintNumber, linkHintDigits) {
  var hintString = numberToHintString(linkHintNumber, linkHintDigits);
  var marker = document.createElement("div");
  marker.className = "internalVimiumHintMarker vimiumHintMarker";
  var innerHTML = [];
  // Make each hint character a span, so that we can highlight the typed characters as you type them.
  for (var i = 0; i < hintString.length; i++)
    innerHTML.push("<span>" + hintString[i].toUpperCase() + "</span>");
  marker.innerHTML = innerHTML.join("");
  marker.setAttribute("hintString", hintString);

  // Note: this call will be expensive if we modify the DOM in between calls.
  var clientRect = link.getClientRects()[0];
  // The coordinates given by the window do not have the zoom factor included since the zoom is set only on
  // the document node.
  var zoomFactor = currentZoomLevel / 100.0;
  marker.style.left = clientRect.left + window.scrollX / zoomFactor + "px";
  marker.style.top = clientRect.top  + window.scrollY / zoomFactor + "px";

  marker.clickableItem = link;
  return marker;
}
<|endoftext|>


<commit_before>import React from 'react'
import 'css/markdown-styles.css'
import Helmet from 'react-helmet'
import { config } from 'config'
import ReadTime from 'components/ReadTime'
import format from 'date-fns/format'
import parse from 'date-fns/parse'
import ShareButtons from 'components/ShareButtons'
import { Flex, Box } from 'reflexbox'
import ReadNext from 'components/ReadNext'
import ReactDisqusThread from 'components/DisqusThread'
import Subscribe from 'components/Subscribe'
import NProgress from 'components/NProgress'

module.exports = React.createClass({
  propTypes() {
    return {
      router: React.PropTypes.object,
    }
  },
  render() {
    const { route } = this.props
    const post = route.page.data
    const { title, description, tags } = post;

    const fullUrl = `https://www.ctheu.com${post.path}`

    return (

        <Helmet
          title={`${config.siteTitle} | ${post.title}`}
          meta={[
            { name: "description", content: description || title },
            { name: "twitter:card", value: "summary" },
            { name: "twitter:creator", content: "@ChtefiD" },
            { name: "twitter:site", content: "@ChtefiD" },
            { name: "twitter:title", content: title },
            { name: "twitter:description", content: description || title },
            { name: "twitter:image", content: "/m.jpg" },
            { property: "og:title", content: title },
            { property: "og:type", content: "article" },
            { property: "og:url", content: fullUrl },
            { property: "og:description", content: description || title },
            { property: "og:image", content: "/m.jpg" }
          ]}
        />
        {post.background &&

}

{post.title}

          <NProgress />

            <Flex>
              <Box>{format(post.date, 'DD MMM YYYY')} — <ReadTime text={post.body} /></Box>
              <Box flexAuto={true}></Box>
              <Box><ShareButtons url={fullUrl} title={title} /></Box>
            </Flex>
            {post.tags &&
➡ {post.tags.split(',').map(t => {t})}
}

          <ShareButtons url={fullUrl} title={title} />
          <ReadNext post={post} pages={route.pages} />

          <Subscribe />

          <ReactDisqusThread url={fullUrl} shortname="ctheu" title={title} />

    )
  },
})
<commit_msg>Fix image metadata<commit_after>import React from 'react'
import 'css/markdown-styles.css'
import Helmet from 'react-helmet'
import { config } from 'config'
import ReadTime from 'components/ReadTime'
import format from 'date-fns/format'
import parse from 'date-fns/parse'
import ShareButtons from 'components/ShareButtons'
import { Flex, Box } from 'reflexbox'
import ReadNext from 'components/ReadNext'
import ReactDisqusThread from 'components/DisqusThread'
import Subscribe from 'components/Subscribe'
import NProgress from 'components/NProgress'

module.exports = React.createClass({
  propTypes() {
    return {
      router: React.PropTypes.object,
    }
  },
  render() {
    const { route } = this.props
    const post = route.page.data
    const { title, description, tags } = post;

    const fullUrl = `https://www.ctheu.com${post.path}`

    return (

        <Helmet
          title={`${config.siteTitle} | ${post.title}`}
          meta={[
            { name: "description", content: description || title },
            { name: "twitter:card", value: "summary" },
            { name: "twitter:creator", content: "@ChtefiD" },
            { name: "twitter:site", content: "@ChtefiD" },
            { name: "twitter:title", content: title },
            { name: "twitter:description", content: description || title },
            { name: "twitter:image", content: fullUrl + post.background },
            { property: "og:title", content: title },
            { property: "og:type", content: "article" },
            { property: "og:url", content: fullUrl },
            { property: "og:description", content: description || title },
            { property: "og:image", content: fullUrl + post.background }
          ]}
        />
        {post.background &&

}

{post.title}

          <NProgress />

            <Flex>
              <Box>{format(post.date, 'DD MMM YYYY')} — <ReadTime text={post.body} /></Box>
              <Box flexAuto={true}></Box>
              <Box><ShareButtons url={fullUrl} title={title} /></Box>
            </Flex>
            {post.tags &&
➡ {post.tags.split(',').map(t => {t})}
}

          <ShareButtons url={fullUrl} title={title} />
          <ReadNext post={post} pages={route.pages} />

          <Subscribe />

          <ReactDisqusThread url={fullUrl} shortname="ctheu" title={title} />

    )
  },
})
<|endoftext|>


<commit_before>import React from 'react'
import 'css/markdown-styles.css'
import Helmet from 'react-helmet'
import { config } from 'config'
import AuthorMediaElement from '../components/AuthorMediaElement';

module.exports = React.createClass({
  propTypes () {
    return {
      router: React.PropTypes.object,
    }
  },
  render () {
    const post = this.props.route.page.data
    console.log(config);
    return (

        <Helmet
          title={`${config.siteTitle} | ${post.title}`}
        />

{post.title}

        {typeof(post.author) !== 'undefined' && (
          <AuthorMediaElement {...config.authors[post.author]}/>
        )}

    )
  },
})
<commit_msg>Remove log<commit_after>import React from 'react'
import 'css/markdown-styles.css'
import Helmet from 'react-helmet'
import { config } from 'config'
import AuthorMediaElement from '../components/AuthorMediaElement';

module.exports = React.createClass({
  propTypes () {
    return {
      router: React.PropTypes.object,
    }
  },
  render () {
    const post = this.props.route.page.data
    return (

        <Helmet
          title={`${config.siteTitle} | ${post.title}`}
        />

{post.title}

        {typeof(post.author) !== 'undefined' && (
          <AuthorMediaElement {...config.authors[post.author]}/>
        )}

    )
  },
})
<|endoftext|>


<commit_before>locale.en = {
    modes: {
        add_area: {
            title: "Area",
            description: "Add parks, buildings, lakes, or other areas to the map.",
            tail: "Click on the map to start drawing an area, like a park, lake, or building.",
            key: "A"
        },
        add_line: {
            title: "Line",
            description: "Lines can be highways, streets, pedestrian paths, or even canals.",
            tail: "Click on the map to start drawing an road, path, or route.",
            key: "L"
        },
        add_point: {
            title: "Point",
            description: "Restaurants, monuments, and postal boxes are points.",
            tail: "Click on the map to add a point.",
            key: "P"
        },
        browse: {
            title: "Browse",
            description: "Pan and zoom the map.",
            key: "B"
        },
        draw_area: {
            tail: "Click to add points to your area. Click the first point to finish the area."
        },
        draw_line: {
            tail: "Click to add more points to the line. Click on other lines to connect to them, and double-click to end the line."
        }
    },

    operations: {
        add: {
            annotation: {
                point: "Added a point.",
                vertex: "Added a node to a way."
            }
        },
        start: {
            annotation: {
                line: "Started a line.",
                area: "Started an area."
            }
        },
        'continue': {
            annotation: {
                line: "Continued a line.",
                area: "Continued an area."
            }
        },
        cancel_draw: {
            annotation: "Cancelled drawing."
        },
        change_tags: {
            annotation: "Changed tags."
        },
        circularize: {
            title: "Circularize",
            description: "Make this round.",
            key: "O",
            annotation: {
                line: "Made a line circular.",
                area: "Made an area circular."
            }
        },
        orthogonalize: {
            title: "Orthogonalize",
            description: "Square these corners.",
            key: "Q",
            annotation: {
                line: "Squared the corners of a line.",
                area: "Squared the corners of an area."
            }
        },
        'delete': {
            title: "Delete",
            description: "Remove this from the map.",
            key: "⌫",
            annotation: {
                point: "Deleted a point.",
                vertex: "Deleted a node from a way.",
                line: "Deleted a line.",
                area: "Deleted an area.",
                relation: "Deleted a relation.",
                multiple: "Deleted {n} objects."
            }
        },
        connect: {
            annotation: {
                point: "Connected a way to a point.",
                vertex: "Connected a way to another.",
                line: "Connected a way to a line.",
                area: "Connected a way to an area."
            }
        },
        disconnect: {
            title: "Disconnect",
            description: "Disconnect these ways from each other.",
            key: "D",
            annotation: "Disconnected ways."
        },
        merge: {
            title: "Merge",
            description: "Merge these lines.",
            key: "C",
            annotation: "Merged {n} lines."
        },
        move: {
            title: "Move",
            description: "Move this to a different location.",
            key: "M",
            annotation: {
                point: "Moved a point.",
                vertex: "Moved a node in a way.",
                line: "Moved a line.",
                area: "Moved an area."
            }
        },
        reverse: {
            title: "Reverse",
            description: "Make this line go in the opposite direction.",
            key: "V",
            annotation: "Reversed a line."
        },
        split: {
            title: "Split",
            description: "Split this into two ways at this point.",
            key: "X",
            annotation: "Split a way."
        }
    },

    validations: {
        untagged_point: "Untagged point which is not part of a line or area",
        untagged_line: "Untagged line",
        untagged_area: "Untagged area",
        tag_suggests_area: "The tag {tag} suggests line should be area, but it is not an area",
        deprecated_tags: "Deprecated tags: {tags}"
    },

    "save": "Save",
    "save_help": "Save changes to OpenStreetMap, making them visible to other users",
    "no_changes": "You don't have any changes to save.",
    "save_error": "An error occurred while trying to save",
    "uploading_changes": "Uploading changes to OpenStreetMap.",
    "just_edited": "You Just Edited OpenStreetMap!",
    "okay": "Okay",

    "zoom-in": "Zoom In",
    "zoom-out": "Zoom Out",

    nothing_to_undo: "Nothing to undo.",
    nothing_to_redo: "Nothing to redo.",

    "browser_notice": "This editor is supported in Firefox, Chrome, Safari, Opera, and Internet Explorer 9 and above. Please upgrade your browser or use Potlatch 2 to edit the map.",

    inspector: {
        no_documentation_combination:  "This is no documentation available for this tag combination",
        no_documentation_key: "This is no documentation available for this key",
        new_tag: "New Tag"
    },

    "view_on_osm": "View on OSM",

    "zoom_in_edit": "zoom in to edit the map",

    "edit_tags": "Edit tags",

    geocoder: {
        "find_location": "Find A Location",
        "find_a_place": "find a place"
    },

    "description": "Description",

    "logout": "logout",

    layerswitcher: {
        title: "Background",
        description: "Background Settings",
        percent_brightness: "{opacity}% brightness",
        fix_misalignment: "Fix misalignment",
        reset: "reset"
    }
};
<commit_msg>Make all non-dashed keys into keys<commit_after>locale.en = {
    modes: {
        add_area: {
            title: "Area",
            description: "Add parks, buildings, lakes, or other areas to the map.",
            tail: "Click on the map to start drawing an area, like a park, lake, or building.",
            key: "A"
        },
        add_line: {
            title: "Line",
            description: "Lines can be highways, streets, pedestrian paths, or even canals.",
            tail: "Click on the map to start drawing an road, path, or route.",
            key: "L"
        },
        add_point: {
            title: "Point",
            description: "Restaurants, monuments, and postal boxes are points.",
            tail: "Click on the map to add a point.",
            key: "P"
        },
        browse: {
            title: "Browse",
            description: "Pan and zoom the map.",
            key: "B"
        },
        draw_area: {
            tail: "Click to add points to your area. Click the first point to finish the area."
        },
        draw_line: {
            tail: "Click to add more points to the line. Click on other lines to connect to them, and double-click to end the line."
        }
    },

    operations: {
        add: {
            annotation: {
                point: "Added a point.",
                vertex: "Added a node to a way."
            }
        },
        start: {
            annotation: {
                line: "Started a line.",
                area: "Started an area."
            }
        },
        'continue': {
            annotation: {
                line: "Continued a line.",
                area: "Continued an area."
            }
        },
        cancel_draw: {
            annotation: "Cancelled drawing."
        },
        change_tags: {
            annotation: "Changed tags."
        },
        circularize: {
            title: "Circularize",
            description: "Make this round.",
            key: "O",
            annotation: {
                line: "Made a line circular.",
                area: "Made an area circular."
            }
        },
        orthogonalize: {
            title: "Orthogonalize",
            description: "Square these corners.",
            key: "Q",
            annotation: {
                line: "Squared the corners of a line.",
                area: "Squared the corners of an area."
            }
        },
        'delete': {
            title: "Delete",
            description: "Remove this from the map.",
            key: "⌫",
            annotation: {
                point: "Deleted a point.",
                vertex: "Deleted a node from a way.",
                line: "Deleted a line.",
                area: "Deleted an area.",
                relation: "Deleted a relation.",
                multiple: "Deleted {n} objects."
            }
        },
        connect: {
            annotation: {
                point: "Connected a way to a point.",
                vertex: "Connected a way to another.",
                line: "Connected a way to a line.",
                area: "Connected a way to an area."
            }
        },
        disconnect: {
            title: "Disconnect",
            description: "Disconnect these ways from each other.",
            key: "D",
            annotation: "Disconnected ways."
        },
        merge: {
            title: "Merge",
            description: "Merge these lines.",
            key: "C",
            annotation: "Merged {n} lines."
        },
        move: {
            title: "Move",
            description: "Move this to a different location.",
            key: "M",
            annotation: {
                point: "Moved a point.",
                vertex: "Moved a node in a way.",
                line: "Moved a line.",
                area: "Moved an area."
            }
        },
        reverse: {
            title: "Reverse",
            description: "Make this line go in the opposite direction.",
            key: "V",
            annotation: "Reversed a line."
        },
        split: {
            title: "Split",
            description: "Split this into two ways at this point.",
            key: "X",
            annotation: "Split a way."
        }
    },

    validations: {
        untagged_point: "Untagged point which is not part of a line or area",
        untagged_line: "Untagged line",
        untagged_area: "Untagged area",
        tag_suggests_area: "The tag {tag} suggests line should be area, but it is not an area",
        deprecated_tags: "Deprecated tags: {tags}"
    },

    save: "Save",
    save_help: "Save changes to OpenStreetMap, making them visible to other users",
    no_changes: "You don't have any changes to save.",
    save_error: "An error occurred while trying to save",
    uploading_changes: "Uploading changes to OpenStreetMap.",
    just_edited: "You Just Edited OpenStreetMap!",
    okay: "Okay",

    "zoom-in": "Zoom In",
    "zoom-out": "Zoom Out",

    nothing_to_undo: "Nothing to undo.",
    nothing_to_redo: "Nothing to redo.",

    browser_notice: "This editor is supported in Firefox, Chrome, Safari, Opera, and Internet Explorer 9 and above. Please upgrade your browser or use Potlatch 2 to edit the map.",

    inspector: {
        no_documentation_combination:  "This is no documentation available for this tag combination",
        no_documentation_key: "This is no documentation available for this key",
        new_tag: "New Tag"
    },

    view_on_osm: "View on OSM",

    zoom_in_edit: "zoom in to edit the map",

    edit_tags: "Edit tags",

    geocoder: {
        "find_location": "Find A Location",
        "find_a_place": "find a place"
    },

    description: "Description",

    logout: "logout",

    layerswitcher: {
        title: "Background",
        description: "Background Settings",
        percent_brightness: "{opacity}% brightness",
        fix_misalignment: "Fix misalignment",
        reset: "reset"
    }
};
<|endoftext|>


<commit_before>import { formatFileSize, isDefinedGlobally } from './utils';

const messages = {
  _default: (field) => `El campo ${field} no es válido.`,
  after: (field, [target, inclusion]) => `El campo ${field} debe ser posterior ${inclusion ? 'o igual ' : ''}a ${target}.`,
  alpha_dash: (field) => `El campo ${field} solo debe contener letras, números y guiones.`,
  alpha_num: (field) => `El campo ${field} solo debe contener letras y números.`,
  alpha_spaces: (field) => `El campo ${field} solo debe contener letras y espacios.`,
  alpha: (field) => `El campo ${field} solo debe contener letras.`,
  before: (field, [target, inclusion]) => `El campo ${field} debe ser anterior ${inclusion ? 'o igual ' : ''}a ${target}.`,
  between: (field, [min, max]) => `El campo ${field} debe estar entre ${min} y ${max}.`,
  confirmed: (field) => `El campo ${field} no coincide.`,
  credit_card: (field) => `El campo ${field} es inválido.`,
  date_between: (field, [min, max]) => `El campo ${field} debe estar entre ${min} y ${max}.`,
  date_format: (field, [format]) => `El campo ${field} debe tener formato formato ${format}.`,
  decimal: (field, [decimals = '*'] = []) => `El campo ${field} debe ser númerico y contener ${decimals === '*' ? '' : decimals} puntos decimales.`,
  digits: (field, [length]) => `El campo ${field} debe ser númerico y contener exactamente ${length} dígitos.`,
  dimensions: (field, [width, height]) => `El campo ${field} debe ser de ${width} pixeles por ${height} pixeles.`,
  email: (field) => `El campo ${field} debe ser un correo electrónico válido.`,
  ext: (field) => `El campo ${field} debe ser un archivo válido.`,
  image: (field) => `El campo ${field} debe ser una imagen.`,
  included: (field) => `El campo ${field} debe ser un valor válido.`,
  integer: (field) => `El campo ${field} debe ser un entero.`,
  ip: (field) => `El campo ${field} debe ser una dirección ip válida.`,
  length: (field, [length, max]) => {
    if (max) {
      return `El largo del campo ${field} debe estar entre ${length} y ${max}.`;
    }

    return `El largo del campo ${field} debe ser ${length}.`;
  },
  max: (field, [length]) => `El campo ${field} no debe ser mayor a ${length} caracteres.`,
  max_value: (field, [max]) => `El campo ${field} debe de ser ${max} o menor.`,
  mimes: (field) => `El campo ${field} debe ser un tipo de archivo válido.`,
  min: (field, [length]) => `El campo ${field} debe tener al menos ${length} caracteres.`,
  min_value: (field, [min]) => `El campo ${field} debe ser ${min} o superior.`,
  excluded: (field) => `El campo ${field} debe ser un valor válido.`,
  numeric: (field) => `El campo ${field} debe contener solo caracteres númericos.`,
  regex: (field) => `El formato del campo ${field} no es válido.`,
  required: (field) => `El campo ${field} es obligatorio.`,
  size: (field, [size]) => `El campo ${field} debe ser menor a ${formatFileSize(size)}.`,
  url: (field) => `El campo ${field} no es una URL válida.`
};

const locale = {
  name: 'es',
  messages,
  attributes: {}
};

if (isDefinedGlobally()) {
  // eslint-disable-next-line
  VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;
<commit_msg>fix typos in spanish locales<commit_after>import { formatFileSize, isDefinedGlobally } from './utils';

const messages = {
  _default: (field) => `El campo ${field} no es válido.`,
  after: (field, [target, inclusion]) => `El campo ${field} debe ser posterior ${inclusion ? 'o igual ' : ''}a ${target}.`,
  alpha_dash: (field) => `El campo ${field} solo debe contener letras, números y guiones.`,
  alpha_num: (field) => `El campo ${field} solo debe contener letras y números.`,
  alpha_spaces: (field) => `El campo ${field} solo debe contener letras y espacios.`,
  alpha: (field) => `El campo ${field} solo debe contener letras.`,
  before: (field, [target, inclusion]) => `El campo ${field} debe ser anterior ${inclusion ? 'o igual ' : ''}a ${target}.`,
  between: (field, [min, max]) => `El campo ${field} debe estar entre ${min} y ${max}.`,
  confirmed: (field) => `El campo ${field} no coincide.`,
  credit_card: (field) => `El campo ${field} es inválido.`,
  date_between: (field, [min, max]) => `El campo ${field} debe estar entre ${min} y ${max}.`,
  date_format: (field, [format]) => `El campo ${field} debe tener formato formato ${format}.`,
  decimal: (field, [decimals = '*'] = []) => `El campo ${field} debe ser númerico y contener ${decimals === '*' ? '' : decimals} puntos decimales.`,
  digits: (field, [length]) => `El campo ${field} debe ser númerico y contener exactamente ${length} dígitos.`,
  dimensions: (field, [width, height]) => `El campo ${field} debe ser de ${width} píxeles por ${height} píxeles.`,
  email: (field) => `El campo ${field} debe ser un correo electrónico válido.`,
  ext: (field) => `El campo ${field} debe ser un archivo válido.`,
  image: (field) => `El campo ${field} debe ser una imagen.`,
  included: (field) => `El campo ${field} debe ser un valor válido.`,
  integer: (field) => `El campo ${field} debe ser un entero.`,
  ip: (field) => `El campo ${field} debe ser una dirección ip válida.`,
  length: (field, [length, max]) => {
    if (max) {
      return `El largo del campo ${field} debe estar entre ${length} y ${max}.`;
    }

    return `El largo del campo ${field} debe ser ${length}.`;
  },
  max: (field, [length]) => `El campo ${field} no debe ser mayor a ${length} caracteres.`,
  max_value: (field, [max]) => `El campo ${field} debe de ser ${max} o menor.`,
  mimes: (field) => `El campo ${field} debe ser un tipo de archivo válido.`,
  min: (field, [length]) => `El campo ${field} debe tener al menos ${length} caracteres.`,
  min_value: (field, [min]) => `El campo ${field} debe ser ${min} o superior.`,
  excluded: (field) => `El campo ${field} debe ser un valor válido.`,
  numeric: (field) => `El campo ${field} debe contener solo caracteres numéricos.`,
  regex: (field) => `El formato del campo ${field} no es válido.`,
  required: (field) => `El campo ${field} es obligatorio.`,
  size: (field, [size]) => `El campo ${field} debe ser menor a ${formatFileSize(size)}.`,
  url: (field) => `El campo ${field} no es una URL válida.`
};

const locale = {
  name: 'es',
  messages,
  attributes: {}
};

if (isDefinedGlobally()) {
  // eslint-disable-next-line
  VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartModelSpec.js
* Module : UnitTest
* Location : /test/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Samuele Zanella    Initial code
* =========================================================
*/

var BarChartModel = require('../../../lib/dataTier/graph/barChartModel.js');
var LegendModel = require('../../../lib/dataTier/graph/legendModel.js');
var BarChartFlowModel = require('../../../lib/dataTier/flow/barChartFlowModel.js');
var AxisModel = require('../../../lib/dataTier/graph/axisModel.js');
var assert = require('assert');

describe('barChartModel', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new BarChartModel()).hasOwnProperty('_title'), false);
    });

    it('returns null when there is no valid ID in params', function() {
        assert.strictEqual((new BarChartModel({})).hasOwnProperty('_title'), false);
    });

    it('returns null when there is a empty ID in params', function() {
        assert.strictEqual((new BarChartModel({ID:' '})).hasOwnProperty('_title'), false);
    });

    var defaultLegend = new LegendModel();
    var defaultAxis = new AxisModel();
    it('set default values to property not specified', function() {
        var graph1=new BarChartModel({ID:'graph1'});
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, '');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 400);
        assert.strictEqual(graph1._width, 500);
        assert.strictEqual(graph1._enableLegend, false);
        assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
        assert.strictEqual(graph1._legendOnPoint, false);
        assert.strictEqual(graph1._headers.length, 0);
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, false);
    });

    it('set default values to wrong properties', function() {
        var graph1=new BarChartModel({
            ID: 'graph1',
            title: 1,
            height: 'a',
            width: 'b',
            enableLegend: 'abc',
            legend: 'def',
            xAxis: true,
            yAxis: true,
            backgroundColor: 222,
            legendOnPoint: 'abc',
            headers: 'zzz',
            barOrientation: 2,
            sortable: 'abc'
        });
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, '');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 400);
        assert.strictEqual(graph1._width, 500);
        assert.strictEqual(graph1._enableLegend, false);
        assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
        assert.strictEqual(graph1._legendOnPoint, false);
        assert.strictEqual(graph1._headers.length, 0);
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, false);
    });

    var legend1 = new LegendModel();
    var xAxis1 = new AxisModel();
    var yAxis1 = new AxisModel();
    it('set param values to properties', function() {
        var graph1=new BarChartModel({
            ID: 'graph1',
            title: 'graph one',
            height: 200,
            width: 350,
            enableLegend: true,
            legend: legend1.getProperties(),
            xAxis: xAxis1.getProperties(),
            yAxis: yAxis1.getProperties(),
            backgroundColor: '#EEEEEE',
            legendOnPoint: true,
            headers: ['h1', 'h2'],
            barOrientation: 'V',
            sortable: true
        });
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, 'graph one');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 200);
        assert.strictEqual(graph1._width, 350);
        assert.strictEqual(graph1._enableLegend, true);
        assert.deepEqual(graph1._legend.getProperties(), legend1.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), xAxis1.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), yAxis1.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#EEEEEE');
        assert.strictEqual(graph1._legendOnPoint, true);
        assert.strictEqual(graph1._headers[0], 'h1');
        assert.strictEqual(graph1._headers[1], 'h2');
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, true);
    });

    describe('#getProperties', function() {
        it('returns the JSON with the properties', function() {
            var properties={
                ID: 'graph1',
                title: 'graph one',
                height: 200,
                width: 350,
                enableLegend: true,
                legend: legend1.getProperties(),
                xAxis: xAxis1.getProperties(),
                yAxis: yAxis1.getProperties(),
                backgroundColor: '#EEEEEE',
                legendOnPoint: true,
                headers: ['h1', 'h2'],
                barOrientation: 'V',
                sortable: true
            };
            var graph1=new BarChartModel(properties);
            var prop=graph1.getProperties();
            assert.strictEqual(prop.ID, 'graph1');
            assert.strictEqual(prop.title, 'graph one');
            assert.strictEqual(prop.type, 'BarChart');
            assert.strictEqual(prop.height, 200);
            assert.strictEqual(prop.width, 350);
            assert.strictEqual(prop.enableLegend, true);
            assert.deepEqual(prop.legend, legend1.getProperties());
            assert.deepEqual(prop.xAxis, xAxis1.getProperties());
            assert.deepEqual(prop.yAxis, yAxis1.getProperties());
            assert.strictEqual(prop.backgroundColor, '#EEEEEE');
            assert.strictEqual(prop.legendOnPoint, true);
            assert.strictEqual(prop.headers[0], 'h1');
            assert.strictEqual(prop.headers[1], 'h2');
            assert.strictEqual(prop.barOrientation, 'V');
            assert.strictEqual(prop.sortable, true);
        });
    });
    describe('#updateProperties', function() {
        it('updates the properties passed as param', function() {
            var properties={
                ID: 'graph1',
                title: 'graph one',
                height: 200,
                width: 350,
                enableLegend: true,
                legend: legend1.getProperties(),
                xAxis: xAxis1.getProperties(),
                yAxis: yAxis1.getProperties(),
                backgroundColor: '#EEEEEE',
                legendOnPoint: true,
                headers: ['h1', 'h2'],
                barOrientation: 'V',
                sortable: true
            };
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.updateProperties(properties);
            assert.strictEqual(graph1._ID, 'graph1');
            assert.strictEqual(graph1._title, 'graph one');
            assert.strictEqual(graph1._type, 'BarChart');
            assert.strictEqual(graph1._height, 200);
            assert.strictEqual(graph1._width, 350);
            assert.strictEqual(graph1._enableLegend, true);
            assert.deepEqual(graph1._legend.getProperties(), legend1.getProperties());
            assert.deepEqual(graph1._xAxis.getProperties(), xAxis1.getProperties());
            assert.deepEqual(graph1._yAxis.getProperties(), yAxis1.getProperties());
            assert.strictEqual(graph1._backgroundColor, '#EEEEEE');
            assert.strictEqual(graph1._legendOnPoint, true);
            assert.strictEqual(graph1._headers[0], 'h1');
            assert.strictEqual(graph1._headers[1], 'h2');
            assert.strictEqual(graph1._barOrientation, 'V');
            assert.strictEqual(graph1._sortable, true);
        });
        it('does not update the properties with wrong param', function() {
            var properties={
                ID: 'graph1',
                title: 1,
                height: 'a',
                width: 'b',
                enableLegend: 'abc',
                legend: 'def',
                xAxis: true,
                yAxis: true,
                backgroundColor: 222,
                legendOnPoint: 'abc',
                headers: 'zzz',
                barOrientation: 2,
                sortable: 'abc'
            };
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.updateProperties(properties);
            assert.strictEqual(graph1._ID, 'graph1');
            assert.strictEqual(graph1._title, '');
            assert.strictEqual(graph1._type, 'BarChart');
            assert.strictEqual(graph1._height, 400);
            assert.strictEqual(graph1._width, 500);
            assert.strictEqual(graph1._enableLegend, false);
            assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
            assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
            assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
            assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
            assert.strictEqual(graph1._legendOnPoint, false);
            assert.strictEqual(graph1._headers.length, 0);
            assert.strictEqual(graph1._barOrientation, 'V');
            assert.strictEqual(graph1._sortable, false);
        });
    });
    describe('#addFlow', function() {
        var flow1 = new BarChartFlowModel({ID: 'flow1'});
        it('adds flow to the flows array', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.addFlow(flow1);
            assert.strictEqual(graph1._flows.length, 1);
        });
        it('does not add an invalid flow to the flows array', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.addFlow({});
            assert.strictEqual(graph1._flows.length, 0);
        });
    });
    function BCFMMock(ID) {
        this._ID = ID;
    }
    BCFMMock.prototype.getProperties = function() {
        return {ID: this._ID};
    };
    describe('#deleteFlow', function() {
        it('deletes the flow with the given ID', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1.deleteFlow('flow1');
            assert.strictEqual(graph1._flows.length, 0);
        });
        it('does not delete anything if the ID is not found', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1.deleteFlow('flow2');
            assert.strictEqual(graph1._flows.length, 1);
        });
    });
    describe('#deleteAllFlows', function() {
        it('deletes all the flows', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1._flows[1] = new BCFMMock('flow2');
            graph1.deleteAllFlows();
            assert.strictEqual(graph1._flows.length, 0);
        });
    });
    describe('#updateRecord', function() {
        it('returns 211 if it doesn\'t find the wanted flow', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel('flow1');
            assert.strictEqual(graph1.updateRecord('flow4', 0, {temperature: 2}), 211);
        });
        it('returns 112 if it doesn\'t find the wanted record', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel('flow1');
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 1, {temperature: 2}), 112);
        });
        it('returns 111 if no valid record is passed', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel('flow1');
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 0, null), 111);
        });
        it('returns true if passed valid parameters', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel('flow1');
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 0, {temperature: 2}), true);
        });
    });
});<commit_msg>fix barchartmodel test<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartModelSpec.js
* Module : UnitTest
* Location : /test/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Samuele Zanella    Initial code
* =========================================================
*/

var BarChartModel = require('../../../lib/dataTier/graph/barChartModel.js');
var LegendModel = require('../../../lib/dataTier/graph/legendModel.js');
var BarChartFlowModel = require('../../../lib/dataTier/flow/barChartFlowModel.js');
var AxisModel = require('../../../lib/dataTier/graph/axisModel.js');
var assert = require('assert');

describe('barChartModel', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new BarChartModel()).hasOwnProperty('_title'), false);
    });

    it('returns null when there is no valid ID in params', function() {
        assert.strictEqual((new BarChartModel({})).hasOwnProperty('_title'), false);
    });

    it('returns null when there is a empty ID in params', function() {
        assert.strictEqual((new BarChartModel({ID:' '})).hasOwnProperty('_title'), false);
    });

    var defaultLegend = new LegendModel();
    var defaultAxis = new AxisModel();
    it('set default values to property not specified', function() {
        var graph1=new BarChartModel({ID:'graph1'});
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, '');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 400);
        assert.strictEqual(graph1._width, 500);
        assert.strictEqual(graph1._enableLegend, false);
        assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
        assert.strictEqual(graph1._legendOnPoint, false);
        assert.strictEqual(graph1._headers.length, 0);
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, false);
    });

    it('set default values to wrong properties', function() {
        var graph1=new BarChartModel({
            ID: 'graph1',
            title: 1,
            height: 'a',
            width: 'b',
            enableLegend: 'abc',
            legend: 'def',
            xAxis: true,
            yAxis: true,
            backgroundColor: 222,
            legendOnPoint: 'abc',
            headers: 'zzz',
            barOrientation: 2,
            sortable: 'abc'
        });
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, '');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 400);
        assert.strictEqual(graph1._width, 500);
        assert.strictEqual(graph1._enableLegend, false);
        assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
        assert.strictEqual(graph1._legendOnPoint, false);
        assert.strictEqual(graph1._headers.length, 0);
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, false);
    });

    var legend1 = new LegendModel();
    var xAxis1 = new AxisModel();
    var yAxis1 = new AxisModel();
    it('set param values to properties', function() {
        var graph1=new BarChartModel({
            ID: 'graph1',
            title: 'graph one',
            height: 200,
            width: 350,
            enableLegend: true,
            legend: legend1.getProperties(),
            xAxis: xAxis1.getProperties(),
            yAxis: yAxis1.getProperties(),
            backgroundColor: '#EEEEEE',
            legendOnPoint: true,
            headers: ['h1', 'h2'],
            barOrientation: 'V',
            sortable: true
        });
        assert.strictEqual(graph1._ID, 'graph1');
        assert.strictEqual(graph1._title, 'graph one');
        assert.strictEqual(graph1._type, 'BarChart');
        assert.strictEqual(graph1._height, 200);
        assert.strictEqual(graph1._width, 350);
        assert.strictEqual(graph1._enableLegend, true);
        assert.deepEqual(graph1._legend.getProperties(), legend1.getProperties());
        assert.deepEqual(graph1._xAxis.getProperties(), xAxis1.getProperties());
        assert.deepEqual(graph1._yAxis.getProperties(), yAxis1.getProperties());
        assert.strictEqual(graph1._backgroundColor, '#EEEEEE');
        assert.strictEqual(graph1._legendOnPoint, true);
        assert.strictEqual(graph1._headers[0], 'h1');
        assert.strictEqual(graph1._headers[1], 'h2');
        assert.strictEqual(graph1._barOrientation, 'V');
        assert.strictEqual(graph1._sortable, true);
    });

    describe('#getProperties', function() {
        it('returns the JSON with the properties', function() {
            var properties={
                ID: 'graph1',
                title: 'graph one',
                height: 200,
                width: 350,
                enableLegend: true,
                legend: legend1.getProperties(),
                xAxis: xAxis1.getProperties(),
                yAxis: yAxis1.getProperties(),
                backgroundColor: '#EEEEEE',
                legendOnPoint: true,
                headers: ['h1', 'h2'],
                barOrientation: 'V',
                sortable: true
            };
            var graph1=new BarChartModel(properties);
            var prop=graph1.getProperties();
            assert.strictEqual(prop.ID, 'graph1');
            assert.strictEqual(prop.title, 'graph one');
            assert.strictEqual(prop.type, 'BarChart');
            assert.strictEqual(prop.height, 200);
            assert.strictEqual(prop.width, 350);
            assert.strictEqual(prop.enableLegend, true);
            assert.deepEqual(prop.legend, legend1.getProperties());
            assert.deepEqual(prop.xAxis, xAxis1.getProperties());
            assert.deepEqual(prop.yAxis, yAxis1.getProperties());
            assert.strictEqual(prop.backgroundColor, '#EEEEEE');
            assert.strictEqual(prop.legendOnPoint, true);
            assert.strictEqual(prop.headers[0], 'h1');
            assert.strictEqual(prop.headers[1], 'h2');
            assert.strictEqual(prop.barOrientation, 'V');
            assert.strictEqual(prop.sortable, true);
        });
    });
    describe('#updateProperties', function() {
        it('updates the properties passed as param', function() {
            var properties={
                ID: 'graph1',
                title: 'graph one',
                height: 200,
                width: 350,
                enableLegend: true,
                legend: legend1.getProperties(),
                xAxis: xAxis1.getProperties(),
                yAxis: yAxis1.getProperties(),
                backgroundColor: '#EEEEEE',
                legendOnPoint: true,
                headers: ['h1', 'h2'],
                barOrientation: 'V',
                sortable: true
            };
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.updateProperties(properties);
            assert.strictEqual(graph1._ID, 'graph1');
            assert.strictEqual(graph1._title, 'graph one');
            assert.strictEqual(graph1._type, 'BarChart');
            assert.strictEqual(graph1._height, 200);
            assert.strictEqual(graph1._width, 350);
            assert.strictEqual(graph1._enableLegend, true);
            assert.deepEqual(graph1._legend.getProperties(), legend1.getProperties());
            assert.deepEqual(graph1._xAxis.getProperties(), xAxis1.getProperties());
            assert.deepEqual(graph1._yAxis.getProperties(), yAxis1.getProperties());
            assert.strictEqual(graph1._backgroundColor, '#EEEEEE');
            assert.strictEqual(graph1._legendOnPoint, true);
            assert.strictEqual(graph1._headers[0], 'h1');
            assert.strictEqual(graph1._headers[1], 'h2');
            assert.strictEqual(graph1._barOrientation, 'V');
            assert.strictEqual(graph1._sortable, true);
        });
        it('does not update the properties with wrong param', function() {
            var properties={
                ID: 'graph1',
                title: 1,
                height: 'a',
                width: 'b',
                enableLegend: 'abc',
                legend: 'def',
                xAxis: true,
                yAxis: true,
                backgroundColor: 222,
                legendOnPoint: 'abc',
                headers: 'zzz',
                barOrientation: 2,
                sortable: 'abc'
            };
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.updateProperties(properties);
            assert.strictEqual(graph1._ID, 'graph1');
            assert.strictEqual(graph1._title, '');
            assert.strictEqual(graph1._type, 'BarChart');
            assert.strictEqual(graph1._height, 400);
            assert.strictEqual(graph1._width, 500);
            assert.strictEqual(graph1._enableLegend, false);
            assert.deepEqual(graph1._legend.getProperties(), defaultLegend.getProperties());
            assert.deepEqual(graph1._xAxis.getProperties(), defaultAxis.getProperties());
            assert.deepEqual(graph1._yAxis.getProperties(), defaultAxis.getProperties());
            assert.strictEqual(graph1._backgroundColor, '#FFFFFF');
            assert.strictEqual(graph1._legendOnPoint, false);
            assert.strictEqual(graph1._headers.length, 0);
            assert.strictEqual(graph1._barOrientation, 'V');
            assert.strictEqual(graph1._sortable, false);
        });
    });
    describe('#addFlow', function() {
        var flow1 = new BarChartFlowModel({ID: 'flow1'});
        it('adds flow to the flows array', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.addFlow(flow1);
            assert.strictEqual(graph1._flows.length, 1);
        });
        it('does not add an invalid flow to the flows array', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1.addFlow({});
            assert.strictEqual(graph1._flows.length, 0);
        });
    });
    function BCFMMock(ID) {
        this._ID = ID;
    }
    BCFMMock.prototype.getProperties = function() {
        return {ID: this._ID};
    };
    describe('#deleteFlow', function() {
        it('deletes the flow with the given ID', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1.deleteFlow('flow1');
            assert.strictEqual(graph1._flows.length, 0);
        });
        it('does not delete anything if the ID is not found', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1.deleteFlow('flow2');
            assert.strictEqual(graph1._flows.length, 1);
        });
    });
    describe('#deleteAllFlows', function() {
        it('deletes all the flows', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BCFMMock('flow1');
            graph1._flows[1] = new BCFMMock('flow2');
            graph1.deleteAllFlows();
            assert.strictEqual(graph1._flows.length, 0);
        });
    });
    describe('#updateRecord', function() {
        it('returns 211 if it doesn\'t find the wanted flow', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel({ID: 'flow1'});
            assert.strictEqual(graph1.updateRecord('flow4', 0, {temperature: 2}), 211);
        });
        it('returns 112 if it doesn\'t find the wanted record', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel({ID: 'flow1'});
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 1, {temperature: 2}), 112);
        });
        it('returns 111 if no valid record is passed', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel({ID: 'flow1'});
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 0, null), 111);
        });
        it('returns true if passed valid parameters', function() {
            var graph1=new BarChartModel({ID: 'graph1'});
            graph1._flows[0] = new BarChartFlowModel({ID: 'flow1'});
            graph1._flows[0]._records[0] = {temperature: 3};
            assert.strictEqual(graph1.updateRecord('flow4', 0, {temperature: 2}), true);
        });
    });
});<|endoftext|>


<commit_before>var editor = document.getElementById('editor');
var viewer = document.getElementById('viewer');

function updateViewer() {
    viewer.innerHTML = marked(editor.innerText);
    viewer.scrollTop = viewer.scrollHeight;
}
editor.onkeyup = updateViewer;
updateViewer();

function saveFile() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", document.URL + '/save', false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("data=" + editor.innerText);
    window.alert(xhr.responseText);
}

function renameFile() {
    if (!window.confirm('Be sure you have saved your work!')) {
        return false;
    }
    var newpad = window.prompt('Enter the name of the new pad:', '');
    if (newpad == null || newpad.length == 0) {
        return false;
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", document.URL + '/rename/' + newpad, false)
    xhr.send();
    if (xhr.responseText == "The operation succeeded!") {
        window.location = "/p/" + newpad;
    } else {
        window.alert(xhr.responseText);
    }
}

function publishFile() {
    var xhr = new XMLHttpRequest();
    if (published) {
        xhr.open("POST", document.URL + '/unpublish', false);
        xhr.send();
        if (xhr.responseText == "This pad is no longer available for viewing!") {
            document.getElementById("publishbutton").value = "Publish";
            published = false;
        }
        window.alert(xhr.responseText);
    } else {
        xhr.open("POST", document.URL + '/publish', false);
        xhr.send();
        if (xhr.responseText == "This pad is now available for viewing!") {
            document.getElementById("publishbutton").value = "Unpublish";
            published = true;
        }
        window.alert(xhr.responseText);
    }
}

function deleteFile() {
    window.location = document.URL + "/delete";
}

document.addEventListener("keydown", function(e) {
  if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    saveFile();
  }
}, false);<commit_msg>Fixed URI error with semicolons<commit_after>var editor = document.getElementById('editor');
var viewer = document.getElementById('viewer');

function updateViewer() {
    viewer.innerHTML = marked(editor.innerText);
    viewer.scrollTop = viewer.scrollHeight;
}
editor.onkeyup = updateViewer;
updateViewer();

function saveFile() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", document.URL + '/save', false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("data=" + window.encodeURIComponent(editor.innerText));
    window.alert(xhr.responseText);
}

function renameFile() {
    if (!window.confirm('Be sure you have saved your work!')) {
        return false;
    }
    var newpad = window.prompt('Enter the name of the new pad:', '');
    if (newpad == null || newpad.length == 0) {
        return false;
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", document.URL + '/rename/' + newpad, false)
    xhr.send();
    if (xhr.responseText == "The operation succeeded!") {
        window.location = "/p/" + newpad;
    } else {
        window.alert(xhr.responseText);
    }
}

function publishFile() {
    var xhr = new XMLHttpRequest();
    if (published) {
        xhr.open("POST", document.URL + '/unpublish', false);
        xhr.send();
        if (xhr.responseText == "This pad is no longer available for viewing!") {
            document.getElementById("publishbutton").value = "Publish";
            published = false;
        }
        window.alert(xhr.responseText);
    } else {
        xhr.open("POST", document.URL + '/publish', false);
        xhr.send();
        if (xhr.responseText == "This pad is now available for viewing!") {
            document.getElementById("publishbutton").value = "Unpublish";
            published = true;
        }
        window.alert(xhr.responseText);
    }
}

function deleteFile() {
    window.location = document.URL + "/delete";
}

document.addEventListener("keydown", function(e) {
  if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    saveFile();
  }
}, false);
<|endoftext|>


<commit_before>/* eslint no-console: off, import/no-extraneous-dependencies: off */

import 'util/catchUnhandledRejection';
import Progress from 'progress';
import client, { processMeta } from 'util/client';
import getIn from 'util/getInFactory';
import GraphQL from '../util/GraphQL';

async function main() {
  // Get all rummors with answer specified.
  //
  const allRumors = getIn(await client.search({
    index: 'rumors',
    body: {
      size: 10000,

      // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-query.html
      //
      query: { bool: { must: { script: { script: {
        lang: 'painless',
        inline: "doc['answerIds'].length > 0",
      } } } } },
    },
  }))(['hits', 'hits'], []).map(processMeta);

  console.log('Querying rumors in DB...');
  const progress = new Progress('[:bar] :current/:total :etas', { total: allRumors.length });

  const allResults = await Promise.all(allRumors.map(({ text }) => GraphQL({
    query: `
      query ($text: String) {
        Search(text: $text, findInCrawled: false) {
          rumors {
            score
            doc {
              id
              text
              answers {
                versions {
                  text
                }
              }
            }
          }
          suggestedResult {
            __typename
            ... on Rumor {
              id
              text
            }
          }
        }
      }
    `,
    variables: {
      text,
    },
  }).then((data) => {
    progress.tick();
    return data;
  })));

  let invalidCount = 0;
  allResults.forEach(({ data }, i) => {
    const rumor = allRumors[i];
    if (data.Search.suggestedResult === null || data.Search.suggestedResult.id !== rumor.id) {
      invalidCount += 1;
      console.log(rumor.id, data.Search.suggestedResult && data.Search.suggestedResult.id);
    }
  });

  console.log('---- Summary ----');
  console.log(`${allRumors.length - invalidCount}/${allRumors.length} correct`);
  console.log(`${(100 * ((allRumors.length - invalidCount) / allRumors.length)).toFixed(2)} % correct.`);
}

main();
<commit_msg>More informative summary report<commit_after>/* eslint no-console: off, import/no-extraneous-dependencies: off */

import 'util/catchUnhandledRejection';
import Progress from 'progress';
import client, { processMeta } from 'util/client';
import getIn from 'util/getInFactory';
import GraphQL from '../util/GraphQL';

function truncate(text, size = 25) {
  text = JSON.stringify(text);
  if (text.length > size - 3) return `${text.slice(0, size - 3)}...`;
  return text;
}

async function main() {
  // Get all rummors with answer specified.
  //
  const allRumors = getIn(await client.search({
    index: 'rumors',
    body: {
      size: 10000,

      // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-query.html
      //
      query: { bool: { must: { script: { script: {
        lang: 'painless',
        inline: "doc['answerIds'].length > 0",
      } } } } },
    },
  }))(['hits', 'hits'], []).map(processMeta);

  console.log('Querying rumors in DB...');
  const progress = new Progress('[:bar] :current/:total :etas', { total: allRumors.length });

  const allResults = await Promise.all(allRumors.map(({ text }) => GraphQL({
    query: `
      query ($text: String) {
        Search(text: $text, findInCrawled: false) {
          rumors {
            score
            doc {
              id
              text
            }
          }
          suggestedResult {
            __typename
            ... on Rumor {
              id
              text
            }
          }
        }
      }
    `,
    variables: {
      text,
    },
  }).then((data) => {
    progress.tick();
    return data;
  })));

  let invalidCount = 0;
  allResults.forEach(({ data }, i) => {
    const rumor = allRumors[i];
    if (data.Search.suggestedResult && data.Search.suggestedResult.id === rumor.id) {
      return; // continue
    }
    invalidCount += 1;

    if (data.Search.suggestedResult === null) {
      console.log(`\n[NOT FOUND] ${rumor.id} ------`);
    } else {
      console.log(`\n[WRONG DOC] ${rumor.id} ------`);
    }

    console.log(truncate(rumor.text, 50));
    console.log('Search result:');
    console.log(data.Search.rumors.map((r, idx) => `\t#${idx + 1} (score=${r.score} / id=${r.doc.id}) ${truncate(r.doc.text)}`).join('\n'));
  });

  console.log('---- Summary ----');
  console.log(`${allRumors.length - invalidCount}/${allRumors.length} correct`);
  console.log(`${(100 * ((allRumors.length - invalidCount) / allRumors.length)).toFixed(2)} % correct.`);
}

main();
<|endoftext|>


<commit_before>TcpClient = function() {
    this.notificationId = 0;
    this.queryId=0;
    this._setConfig();
}

TcpClient.prototype = {
    connect: function() {
        var that = this;
        this.socket = new WebSocket(this.uri);
        this.socket.onopen = function() {
            that._onOpenCallback();
        };
        this.socket.onmessage = function(msg) {
            that._onMessageCallback(msg);
        };
        this.socket.onclose = function() {
            that._onCloseCallback();
        };
        this.socket.onerror = function(event) {
            that._onErrorCallback(event);
        };
    },
    notify: function(type, value) {
        this.socket.send("<notify type='"+type+"' value='"+value+"'/>");
    },
    request: function(type) {
        this._incrementQueryId();
        this.socket.send("<request type='"+type+"' id='"+this.queryId+"'/>");
    },
    _setConfig: function() {
        var that = this;
        chrome.storage.local.get("uri",function(item){
            if(item.uri) {
                that.uri = item.uri;
            }
            that.connect();
        });
    },
    _onOpenCallback : function() {
        //Hide the socket connect window
        clearTimeout(this.timeout);
        $(".splashscreen").hide();
    },
    _onMessageCallback : function(msg) {
        notification = new Notification(msg.data+" "+this.notificationId++);
        notification.message();
    },
    _onCloseCallback : function() {
        //Show the socket connect window
<<<<<<< HEAD
        //$(".splashscreen").show();
=======
        var that = this;
        $(".splashscreen").show();
>>>>>>> b310fe11f052ce6bfc5139f6bf57e636fb909236
        this.timeout = setTimeout(function(){
            tcpClient = that.connect();
        },3000);
    },
    _onErrorCallback : function(event) {

    },
<<<<<<< HEAD
    incrementQueryId: function() {
        this.queryId++;
    },
    notify: function(type, value) {
        this.socket.send("<notify type='"+type+"' value='"+value+"'/>");
    },
    request: function(type) {
        this.incrementQueryId();
        this.socket.send("<request type='"+type+"' id='"+this.queryId+"'/>");
=======
    _incrementQueryId: function() {
        this.queryId++;
>>>>>>> b310fe11f052ce6bfc5139f6bf57e636fb909236
    }

}<commit_msg>splashscreen<commit_after>TcpClient = function() {
    this.notificationId = 0;
    this.queryId=0;
    this._setConfig();
}

TcpClient.prototype = {
    connect: function() {
        var that = this;
        this.socket = new WebSocket(this.uri);
        this.socket.onopen = function() {
            that._onOpenCallback();
        };
        this.socket.onmessage = function(msg) {
            that._onMessageCallback(msg);
        };
        this.socket.onclose = function() {
            that._onCloseCallback();
        };
        this.socket.onerror = function(event) {
            that._onErrorCallback(event);
        };
    },
    notify: function(type, value) {
        this.socket.send("<notify type='"+type+"' value='"+value+"'/>");
    },
    request: function(type) {
        this._incrementQueryId();
        this.socket.send("<request type='"+type+"' id='"+this.queryId+"'/>");
    },
    _setConfig: function() {
        var that = this;
        chrome.storage.local.get("uri",function(item){
            if(item.uri) {
                that.uri = item.uri;
            }
            that.connect();
        });
    },
    _onOpenCallback : function() {
        //Hide the socket connect window
        clearTimeout(this.timeout);
        $(".splashscreen").hide();
    },
    _onMessageCallback : function(msg) {
        notification = new Notification(msg.data+" "+this.notificationId++);
        notification.message();
    },
    _onCloseCallback : function() {
        //Show the socket connect window
        $(".splashscreen").show();
        var that = this;
        this.timeout = setTimeout(function(){
            tcpClient = that.connect();
        },3000);
    },
    _onErrorCallback : function(event) {

    },
    incrementQueryId: function() {
        this.queryId++;
    },
    notify: function(type, value) {
        this.socket.send("<notify type='"+type+"' value='"+value+"'/>");
    },
    request: function(type) {
        this.incrementQueryId();
        this.socket.send("<request type='"+type+"' id='"+this.queryId+"'/>");
    },
    _incrementQueryId: function() {
        this.queryId++;
    }
}<|endoftext|>


<commit_before>/* eslint no-console: 0 */

import fs from 'fs';
import recursiveReadSync from 'recursive-readdir-sync';
import minimatch from 'minimatch'

class WebpackCleanupPlugin {

  constructor(options = {}) {
    this.options = options;
  }

  apply(compiler) {
    const outputPath = compiler.options.output.path;

    compiler.plugin('done', (stats) => {
      if (compiler.outputFileSystem.constructor.name !== 'NodeOutputFileSystem') {
        return;
      }

      const { exclude = [], quiet = false } = this.options;
      // recursiveReadSync returns prefix of outputPath + "/"
      const offset = outputPath.length + 1;
      const assets = stats.toJson().assets.map(asset => asset.name);
      const files = recursiveReadSync(outputPath)
        .map(path => path.substr(offset))
        .filter(file => {
            for (var i = 0; i < exclude.length; i++) {
                if (minimatch(file, exclude[i], {dot: true})) {
                    return false
                }
            }
            return assets.indexOf(file) === -1
        })
        .map(file => `${outputPath}/${file}`);

      files.forEach(fs.unlinkSync);

      if (!quiet) {
        console.log('\nWebpackCleanupPlugin: %s file(s) deleted.', files.length);
      }
    });
  }

}

module.exports = WebpackCleanupPlugin;
<commit_msg>Lint file<commit_after>/* eslint no-console: 0 */

import fs from 'fs';
import recursiveReadSync from 'recursive-readdir-sync';
import minimatch from 'minimatch';

class WebpackCleanupPlugin {

  constructor(options = {}) {
    this.options = options;
  }

  apply(compiler) {
    const outputPath = compiler.options.output.path;

    compiler.plugin('done', (stats) => {
      if (compiler.outputFileSystem.constructor.name !== 'NodeOutputFileSystem') {
        return;
      }

      const {
        exclude = [],
        quiet = false,
      } = this.options;

      const offset = outputPath.length + 1; // recursiveReadSync returns prefix of outputPath + "/"
      const assets = stats.toJson().assets.map(asset => asset.name);
      const files = recursiveReadSync(outputPath)
        .map(path => path.substr(offset))
        .filter((file) => {
          for (let i = 0; i < exclude.length; i += 1) {
            if (minimatch(file, exclude[i], { dot: true })) {
              return false;
            }
          }
          return assets.indexOf(file) === -1;
        })
        .map(file => `${outputPath}/${file}`);

      files.forEach(fs.unlinkSync);

      if (!quiet) {
        console.log('\nWebpackCleanupPlugin: %s file(s) deleted.', files.length);
      }
    });
  }

}

module.exports = WebpackCleanupPlugin;
<|endoftext|>