<commit_before>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Definitions for W3C's XML related specifications.
 *  This file depends on w3c_dom2.js.
 *  The whole file has been fully type annotated.
 *
 *  Provides the XML standards from W3C.
 *   Includes:
 *    XPath          - Fully type annotated
 *    XMLHttpRequest - Fully type annotated
 *
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html
 * @see http://www.w3.org/TR/XMLHttpRequest/
 * @see http://www.w3.org/TR/XMLHttpRequest2/
 *
 * @externs
 */

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathException
 */
function XPathException() {}

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#INVALID_EXPRESSION_ERR
 */
XPathException.INVALID_EXPRESSION_ERR = 52;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#TYPE_ERR
 */
XPathException.TYPE_ERR = 52;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#
 */
XPathException.prototype.code;

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator
 */
function XPathEvaluator() {}

/**
 * @param {string} expr
 * @param {?XPathNSResolver=} opt_resolver
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-createExpression
 * @throws XPathException
 * @throws DOMException
 */
XPathEvaluator.prototype.createExpression = function(expr, opt_resolver) {};

/**
 * @param {Node} nodeResolver
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-createNSResolver
 */
XPathEvaluator.prototype.createNSResolver = function(nodeResolver) {};

/**
 * @param {string} expr
 * @param {Node} contextNode
 * @param {?XPathNSResolver=} opt_resolver
 * @param {?number=} opt_type
 * @param {*=} opt_result
 * @return {XPathResult}
 * @throws XPathException
 * @throws DOMException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-evaluate
 */
XPathEvaluator.prototype.evaluate = function(expr, contextNode, opt_resolver,
    opt_type, opt_result) {};

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathExpression
 */
function XPathExpression() {}

/**
 * @param {Node} contextNode
 * @param {number=} opt_type
 * @param {*=} opt_result
 * @return {*}
 * @throws XPathException
 * @throws DOMException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathExpression-evaluate
 */
XPathExpression.prototype.evaluate = function(contextNode, opt_type,
    opt_result) {};

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver
 */
function XPathNSResolver() {}

/**
 * @param {string} prefix
 * @return {?string}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver-lookupNamespaceURI
 */
XPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {};

/**
 * From http://www.w3.org/TR/xpath
 *
 * XPath is a language for addressing parts of an XML document, designed to be
 * used by both XSLT and XPointer.
 *
 * @noalias
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult
 */
function XPathResult() {}

/**
 * @type {boolean} {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-booleanValue
 */
XPathResult.prototype.booleanValue;

/**
 * @type {boolean} {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-invalid-iterator-state
 */
XPathResult.prototype.invalidInteratorState;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-numberValue
 */
XPathResult.prototype.numberValue;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-resultType
 */
XPathResult.prototype.resultType;

/**
 * @type {Node}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-singleNodeValue
 */
XPathResult.prototype.singleNodeValue;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshot-length
 */
XPathResult.prototype.snapshotLength;

/**
 * @type {string}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-stringValue
 */
XPathResult.prototype.stringValue;

/**
 * @return {Node}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @throws DOMException {@see DOMException.INVALID_STATE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-iterateNext
 */
XPathResult.prototype.iterateNext = function() {};

/**
 * @param {number} index
 * @return {Node}
 * @throws XPathException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshotItem
 */
XPathResult.prototype.snapshotItem = function(index) {};

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ANY-TYPE
 */
XPathResult.ANY_TYPE = 0;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-NUMBER-TYPE
 */
XPathResult.NUMBER_TYPE = 1;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-STRING-TYPE
 */
XPathResult.STRING_TYPE = 2;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-BOOLEAN-TYPE
 */
XPathResult.BOOLEAN_TYPE = 3;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-UNORDERED-NODE-ITERATOR-TYPE
 */
XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ORDERED-NODE-ITERATOR-TYPE
 */
XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-UNORDERED-NODE-SNAPSHOT-TYPE
 */
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ORDERED-NODE-SNAPSHOT-TYPE
 */
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ANY-UNORDERED-NODE-TYPE
 */
XPathResult.ANY_UNORDERED_NODE_TYPE = 8;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-FIRST-ORDERED-NODE-TYPE
 */
XPathResult.FIRST_ORDERED_NODE_TYPE = 9;

/**
 * @constructor
 * @extends {Node}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNamespace
 */
function XPathNamespace() {}

/**
 * @type {Element}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNamespace-ownerElement
 */
XPathNamespace.prototype.ownerElement;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPATH_NAMESPACE_NODE
 */
XPathNamespace.XPATH_NAMESPACE_NODE = 13;

/**
 * From http://www.w3.org/TR/XMLHttpRequest/
 *
 * (Draft)
 *
 * The XMLHttpRequest Object specification defines an API that provides
 * scripted client functionality for transferring data between a client and a
 * server.
 *
 * @constructor
 * @see http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object
 */
function XMLHttpRequest() {}

/**
 * @param {string} method
 * @param {string} url
 * @param {?boolean=} opt_async
 * @param {?string=} opt_user
 * @param {?string=} opt_password
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#open
 */
XMLHttpRequest.prototype.open = function(method, url, opt_async, opt_user,
    opt_password) {};

/**
 * @param {string} header
 * @param {string} value
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#setrequestheader
 */
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {};

/**
 * @param {ArrayBuffer|Blob|Document|FormData|string=} opt_data
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#send
 * @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-send-method
 */
XMLHttpRequest.prototype.send = function(opt_data) {};

/**
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#abort
 */
XMLHttpRequest.prototype.abort = function() {};

/**
 * @return {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#getallresponseheaders
 */
XMLHttpRequest.prototype.getAllResponseHeaders = function() {};

/**
 * @param {string} header
 * @return {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#getresponseheader
 */
XMLHttpRequest.prototype.getResponseHeader = function(header) {};

/**
 * @type {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#responsetext
 */
XMLHttpRequest.prototype.responseText;

/**
 * @type {Document}
 * @see http://www.w3.org/TR/XMLHttpRequest/#responsexml
 */
XMLHttpRequest.prototype.responseXML;

/**
 * @type {number}
 * @see http://www.w3.org/TR/XMLHttpRequest/#readystate
 */
XMLHttpRequest.prototype.readyState;

/**
 * @type {number}
 * @see http://www.w3.org/TR/XMLHttpRequest/#status
 */
XMLHttpRequest.prototype.status;

/**
 * @type {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#statustext
 */
XMLHttpRequest.prototype.statusText;

/**
 * @type {Function}
 * @see http://www.w3.org/TR/XMLHttpRequest/#onreadystatechange
 */
XMLHttpRequest.prototype.onreadystatechange;

/**
 * The FormData object represents an ordered collection of entries. Each entry
 * has a name and value.
 *
 * @constructor
 * @see http://www.w3.org/TR/XMLHttpRequest2/#the-formdata-interface
 */
function FormData() {}

/**
 * @param {string} name
 * @param {string} value
 */
FormData.prototype.append = function(name, value) {};
<commit_msg><commit_after>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Definitions for W3C's XML related specifications.
 *  This file depends on w3c_dom2.js.
 *  The whole file has been fully type annotated.
 *
 *  Provides the XML standards from W3C.
 *   Includes:
 *    XPath          - Fully type annotated
 *    XMLHttpRequest - Fully type annotated
 *
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html
 * @see http://www.w3.org/TR/XMLHttpRequest/
 * @see http://www.w3.org/TR/XMLHttpRequest2/
 *
 * @externs
 */

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathException
 */
function XPathException() {}

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#INVALID_EXPRESSION_ERR
 */
XPathException.INVALID_EXPRESSION_ERR = 52;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#TYPE_ERR
 */
XPathException.TYPE_ERR = 52;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#
 */
XPathException.prototype.code;

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator
 */
function XPathEvaluator() {}

/**
 * @param {string} expr
 * @param {?XPathNSResolver=} opt_resolver
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-createExpression
 * @throws XPathException
 * @throws DOMException
 */
XPathEvaluator.prototype.createExpression = function(expr, opt_resolver) {};

/**
 * @param {Node} nodeResolver
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-createNSResolver
 */
XPathEvaluator.prototype.createNSResolver = function(nodeResolver) {};

/**
 * @param {string} expr
 * @param {Node} contextNode
 * @param {?XPathNSResolver=} opt_resolver
 * @param {?number=} opt_type
 * @param {*=} opt_result
 * @return {XPathResult}
 * @throws XPathException
 * @throws DOMException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-evaluate
 */
XPathEvaluator.prototype.evaluate = function(expr, contextNode, opt_resolver,
    opt_type, opt_result) {};

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathExpression
 */
function XPathExpression() {}

/**
 * @param {Node} contextNode
 * @param {number=} opt_type
 * @param {*=} opt_result
 * @return {*}
 * @throws XPathException
 * @throws DOMException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathExpression-evaluate
 */
XPathExpression.prototype.evaluate = function(contextNode, opt_type,
    opt_result) {};

/**
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver
 */
function XPathNSResolver() {}

/**
 * @param {string} prefix
 * @return {?string}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver-lookupNamespaceURI
 */
XPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {};

/**
 * From http://www.w3.org/TR/xpath
 *
 * XPath is a language for addressing parts of an XML document, designed to be
 * used by both XSLT and XPointer.
 *
 * @noalias
 * @constructor
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult
 */
function XPathResult() {}

/**
 * @type {boolean} {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-booleanValue
 */
XPathResult.prototype.booleanValue;

/**
 * @type {boolean} {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-invalid-iterator-state
 */
XPathResult.prototype.invalidInteratorState;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-numberValue
 */
XPathResult.prototype.numberValue;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-resultType
 */
XPathResult.prototype.resultType;

/**
 * @type {Node}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-singleNodeValue
 */
XPathResult.prototype.singleNodeValue;

/**
 * @type {number}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshot-length
 */
XPathResult.prototype.snapshotLength;

/**
 * @type {string}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-stringValue
 */
XPathResult.prototype.stringValue;

/**
 * @return {Node}
 * @throws XPathException {@see XPathException.TYPE_ERR}
 * @throws DOMException {@see DOMException.INVALID_STATE_ERR}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-iterateNext
 */
XPathResult.prototype.iterateNext = function() {};

/**
 * @param {number} index
 * @return {Node}
 * @throws XPathException
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshotItem
 */
XPathResult.prototype.snapshotItem = function(index) {};

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ANY-TYPE
 */
XPathResult.ANY_TYPE = 0;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-NUMBER-TYPE
 */
XPathResult.NUMBER_TYPE = 1;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-STRING-TYPE
 */
XPathResult.STRING_TYPE = 2;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-BOOLEAN-TYPE
 */
XPathResult.BOOLEAN_TYPE = 3;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-UNORDERED-NODE-ITERATOR-TYPE
 */
XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ORDERED-NODE-ITERATOR-TYPE
 */
XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-UNORDERED-NODE-SNAPSHOT-TYPE
 */
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ORDERED-NODE-SNAPSHOT-TYPE
 */
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-ANY-UNORDERED-NODE-TYPE
 */
XPathResult.ANY_UNORDERED_NODE_TYPE = 8;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-FIRST-ORDERED-NODE-TYPE
 */
XPathResult.FIRST_ORDERED_NODE_TYPE = 9;

/**
 * @constructor
 * @extends {Node}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNamespace
 */
function XPathNamespace() {}

/**
 * @type {Element}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNamespace-ownerElement
 */
XPathNamespace.prototype.ownerElement;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPATH_NAMESPACE_NODE
 */
XPathNamespace.XPATH_NAMESPACE_NODE = 13;

/**
 * From http://www.w3.org/TR/XMLHttpRequest/
 *
 * (Draft)
 *
 * The XMLHttpRequest Object specification defines an API that provides
 * scripted client functionality for transferring data between a client and a
 * server.
 *
 * @constructor
 * @see http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object
 */
function XMLHttpRequest() {}

/**
 * @param {string} method
 * @param {string} url
 * @param {?boolean=} opt_async
 * @param {?string=} opt_user
 * @param {?string=} opt_password
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#open
 */
XMLHttpRequest.prototype.open = function(method, url, opt_async, opt_user,
    opt_password) {};

/**
 * @param {string} header
 * @param {string} value
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#setrequestheader
 */
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {};

/**
 * @param {ArrayBuffer|Blob|Document|FormData|string=} opt_data
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#send
 * @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-send-method
 */
XMLHttpRequest.prototype.send = function(opt_data) {};

/**
 * @return {undefined}
 * @see http://www.w3.org/TR/XMLHttpRequest/#abort
 */
XMLHttpRequest.prototype.abort = function() {};

/**
 * @return {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#getallresponseheaders
 */
XMLHttpRequest.prototype.getAllResponseHeaders = function() {};

/**
 * @param {string} header
 * @return {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#getresponseheader
 */
XMLHttpRequest.prototype.getResponseHeader = function(header) {};

/**
 * @type {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#responsetext
 */
XMLHttpRequest.prototype.responseText;

/**
 * @type {Document}
 * @see http://www.w3.org/TR/XMLHttpRequest/#responsexml
 */
XMLHttpRequest.prototype.responseXML;

/**
 * @type {number}
 * @see http://www.w3.org/TR/XMLHttpRequest/#readystate
 */
XMLHttpRequest.prototype.readyState;

/**
 * @type {number}
 * @see http://www.w3.org/TR/XMLHttpRequest/#status
 */
XMLHttpRequest.prototype.status;

/**
 * @type {string}
 * @see http://www.w3.org/TR/XMLHttpRequest/#statustext
 */
XMLHttpRequest.prototype.statusText;

/**
 * @type {Function}
 * @see http://www.w3.org/TR/XMLHttpRequest/#onreadystatechange
 */
XMLHttpRequest.prototype.onreadystatechange;

/**
 * The FormData object represents an ordered collection of entries. Each entry
 * has a name and value.
 *
 * @constructor
 * @see http://www.w3.org/TR/XMLHttpRequest2/#the-formdata-interface
 */
function FormData() {}

/**
 * @param {string} name
 * @param {Blob|string} value
 */
FormData.prototype.append = function(name, value) {};
<|endoftext|>


<commit_before>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software inkscape-web, consisting of custom
 * code for the Inkscape project's django-based website.
 *
 * inkscape-web is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * inkscape-web is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with inkscape-web.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
  var svg = 'svg.lineages';
  var chart = initialiseLineageChart(svg);
  $('#lineage-store').data('json-signal', function(data) {
    console.log("Lineage ahoy!");
    chartLineageData(svg, chart, data.data);
  });
});

function chartLineageData(svg, chart, data) {
    var svg_n = chartData(svg, chart, data);

    svg_n.transition().duration(0);
    // Select the first category by "clicking" on it
    var evt = new MouseEvent("click");
    var node = d3.select(svg).selectAll('.nv-series')
        .filter(function(d, i){return i == 0;}).node().dispatchEvent(evt);

    svg_n.transition().duration(1200);
}

function initialiseLineageChart(svg) {
    var chart = nv.models.multiBarChart()
      .stacked(true)
      .reduceXTicks(false);

    var width = 1000;
    var height = 600;

    chart.margin({top: 20, right: 0, bottom: 120, left: 80});
    chart.height(height);
    chart.width(width);
    chart.yAxis.scale(100).orient("left")
        .axisLabel('Number of strains')
        .tickFormat(d3.format("d"));

    // Single click selection of chart type
    chart.legend.radioButtonMode(true);
    // Disable the stacked/unstacked option
    chart.showControls(false);

    chart.xAxis
        .rotateLabels(-20);

    chart.showLegend(true);

    var svg = d3.select(svg)
          .attr('perserveAspectRatio', 'xMinYMid')
          .attr('width', width)
          .attr('height', height)
          .attr('viewBox', '0 0 ' + width + ' ' + height)
          .datum([])
          .call(chart);

    chart.multibar.dispatch.on("elementClick", function(e) {
        setTabData('lineage', e.data.x, e.data.x, 'ok-circle')
    });

    $('#lineages').parent().click(function(e) {
      unsetTabData('lineage');
    });
    return chart;
}

<commit_msg>Do not stack lineage chart, it makes no sense<commit_after>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software inkscape-web, consisting of custom
 * code for the Inkscape project's django-based website.
 *
 * inkscape-web is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * inkscape-web is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with inkscape-web.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
  var svg = 'svg.lineages';
  var chart = initialiseLineageChart(svg);
  $('#lineage-store').data('json-signal', function(data) {
    console.log("Lineage ahoy!");
    chartLineageData(svg, chart, data.data);
  });
});

function chartLineageData(svg, chart, data) {
    var svg_n = chartData(svg, chart, data);

    svg_n.transition().duration(0);
    // Select the first category by "clicking" on it
    var evt = new MouseEvent("click");
    var node = d3.select(svg).selectAll('.nv-series')
        .filter(function(d, i){return i == 0;}).node().dispatchEvent(evt);

    svg_n.transition().duration(1200);
}

function initialiseLineageChart(svg) {
    var chart = nv.models.multiBarChart()
      .stacked(false) // Do not stack!
      .reduceXTicks(false);

    var width = 1000;
    var height = 600;

    chart.margin({top: 20, right: 0, bottom: 120, left: 80});
    chart.height(height);
    chart.width(width);
    chart.yAxis.scale(100).orient("left")
        .axisLabel('Number of strains')
        .tickFormat(d3.format("d"));

    // Single click selection of chart type
    chart.legend.radioButtonMode(true);
    // Disable the stacked/unstacked option
    chart.showControls(false);

    chart.xAxis
        .rotateLabels(-20);

    chart.showLegend(true);

    var svg = d3.select(svg)
          .attr('perserveAspectRatio', 'xMinYMid')
          .attr('width', width)
          .attr('height', height)
          .attr('viewBox', '0 0 ' + width + ' ' + height);

    chart.multibar.dispatch.on("elementClick", function(e) {
        setTabData('lineage', e.data.x, e.data.x, 'ok-circle')
    });

    $('#lineages').parent().click(function(e) {
      unsetTabData('lineage');
    });
    return chart;
}

<|endoftext|>


<commit_before>var STK = STK || {};

STK.RefineBy = (function () {

    var currentState = [];

    var closeFilters = function (link) {
        $('.link', '#event-listing-refine-bar').each(function () {
            if (this !== link && $(this).closest('.refine').hasClass('open')) {
                reApplyStateAndClose(this);
            }
        });
    };

    var openFilter = function (link) {
        var parent = $(link).parent();

        if ($(parent).hasClass('open')) {
            reApplyStateAndClose(link);
        }
        else {
            $(parent).addClass('open')
        }

        currentState = [];
        $('input[type=checkbox]', parent).each(function () {
            currentState.push($(this).prop('checked'));
        });
    };

    var reApplyStateAndClose = function (link) {
        var parent = $(link).closest('.refine');

        $('input[type=checkbox]', $(parent)).each(function (index) {
            $(this).prop('checked', currentState[index]);
        });

        $(parent).removeClass('open');
        setBadges();
    };

    var setBadges = function () {
        $('.badge', '#event-listing-refine-bar').css('visibility', 'hidden');

        var allcount = 0;
        $('.refine', '#event-listing-refine-bar').each(function () {
            var count = 0;
            $('input[type=checkbox]', $(this)).each(function () {
                if ($(this).prop('checked')) {
                    count++;
                    allcount++;
                }
            });

            var $lat = $('input[name=latitude]', $(this));
            if ($lat.length == 1 && $lat.val() !== '' && $lat.val() !== '0') {
                count++;
                allcount++;
            }

            if (count > 0) {
                $('.badge', $(this)).html('' + count + '').css('visibility', 'visible');
                if ($('.none-selected-error', this).length) {
                    $('.none-selected-error', this).hide();
                    $('.apply', this).removeClass('disabled').off('click').on('click', function () { applyFilter(); });
                    $('.update-button', '#event-listing-refine-bar').removeClass('disabled').prop('disabled', '');
                }
            }
            else if ($('.none-selected-error', this).length) {
                $('.none-selected-error', this).show();
                $('.apply', this).addClass('disabled').off('click');
                $('.update-button', '#event-listing-refine-bar').addClass('disabled').prop('disabled', 'disabled');
            }
        });

        if (allcount > 0) {
            $('.refine-all .badge', '#event-listing-refine-bar').html('' + allcount + '').css('visibility', 'visible');
        }
    };

    var applyFilter = function () {
        var href = window.location.href;

        href = STK.Utils.StripParamFromQueryString(href, 'keeptag');
        href = STK.Utils.StripParamFromQueryString(href, 'fromsearch');
        href = STK.Utils.StripParamFromQueryString(href, 'tag');
        href = STK.Utils.StripParamFromQueryString(href, 'price');
        href = STK.Utils.StripParamFromQueryString(href, 'longitude');
        href = STK.Utils.StripParamFromQueryString(href, 'latitude');
        href = STK.Utils.StripParamFromQueryString(href, 'location');

        var tag = getTag();
        if (typeof (tag) == 'undefined') { tag = ''; }
        if (href.indexOf('?') < 0) {
            href += '?keeptag=' + tag + '&fromsearch=true';
        }
        else {
            href += '&keeptag=' + tag + '&fromsearch=true';
        }

        $('input:checked', '#event-listing-refine-bar').each(function () {
            href += '&' + $(this).prop('name') + '=' + $(this).val();
        });

        $('input[name=longitude]', '#event-listing-refine-bar').each(function () {
            href += '&longitude=' + $(this).val();
        });

        $('input[name=latitude]', '#event-listing-refine-bar').each(function () {
            href += '&latitude=' + $(this).val();
        });

        $('input[name=location]', '#event-listing-refine-bar').each(function () {
            href += '&location=' + $(this).val();
        });

        window.location.href = href;
    };

    var getTag = function () {
        return $('input[name=tag]', '#event-listing-refine-bar').val();
    };

    var initialiseSlider = function () {
        var width = $(window).width();
        $('#refine-slider').css('left', width);

        var location = $('#location').val();
        if (location !== '') {
            $('.location-search-input').val(location);
            $('.search-all', '#event-listing-refine-bar').show();
        }
        else {
            $('.search-all', '#event-listing-refine-bar').hide();
        }
    };

    var searchAll = function () {
        $('#location').val('');
        $('#longitude').val('0');
        $('#latitude').val('0');
        $('.location-search-input').val('All locations');
        setBadges();
    };

    var revealSlider = function () {
        var top = $(document).scrollTop();
        $('#refine-slider').css('top', top).removeClass('hide-on-mobile').animate({ 'left': 0 }, 250);
        var height = $('#refine-slider').height() - $('.update-cancel-bar', '#event-listing-refine-bar').height();
        $('.scroller', '#refine-slider').height(height);
        $('body').css('overflow', 'hidden');

        currentState = [];
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function () {
            currentState.push($(this).prop('checked'));
        });
    };

    var clearHeight = function () {
        $('.scroller', '#refine-slider').height('');
    };

    var hideSlider = function () {
        var width = $(window).width();
        $('#refine-slider').animate({ 'left': width }, 250, 'swing', function () { $('#refine-slider').addClass('hide-on-mobile'); });
        $('body').css('overflow', 'scroll');
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function (index) {
            $(this).prop('checked', currentState[index]);
        });
        setBadges();
    };

    var clearAllFilters = function () {
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function () {
            $(this).prop('checked', false);
        });

        searchAll();
    };

    var applyLocation = function () {
        setBadges();
        applyFilter();
    }

    return {
        Init: function () {
            setBadges();
            initialiseSlider();

            $('#event-listing-refine-bar').show();

            $('.link', '#event-listing-refine-bar').on('click', function () {
                closeFilters(this);
                openFilter(this);
            });

            $('.cancel', '#event-listing-refine-bar').on('click', function () {
                reApplyStateAndClose(this);
            });

            $('.apply', '#event-listing-refine-bar').on('click', function () {
                applyFilter();
            });

            $('input[type=checkbox]', '#event-listing-refine-bar').on('click', function () {
                setBadges();
            });

            $('#reveal-refine-by').click(function () {
                revealSlider();
            });

            $('.update-cancel-bar .cancel', '#event-listing-refine-bar').on('click', function () {
                hideSlider();
            });

            $('.update-cancel-bar .apply', '#event-listing-refine-bar').on('click', function () {
                applyFilter();
            });

            $('.clear-all-filters a', '#event-listing-refine-bar').on('click', function () {
                clearAllFilters();
                setBadges();
            });

            $('.search-all', '#event-listing-refine-bar').on('click', function () {
                searchAll();
            });

            $(window).on('resize', function () {
                clearHeight();
                hideSlider();
            });
        },
        ApplyLocation: applyLocation
    };
})();

STK.RefineBy.Init();

<commit_msg>Change overflow to overflow-y<commit_after>var STK = STK || {};

STK.RefineBy = (function () {

    var currentState = [];

    var closeFilters = function (link) {
        $('.link', '#event-listing-refine-bar').each(function () {
            if (this !== link && $(this).closest('.refine').hasClass('open')) {
                reApplyStateAndClose(this);
            }
        });
    };

    var openFilter = function (link) {
        var parent = $(link).parent();

        if ($(parent).hasClass('open')) {
            reApplyStateAndClose(link);
        }
        else {
            $(parent).addClass('open')
        }

        currentState = [];
        $('input[type=checkbox]', parent).each(function () {
            currentState.push($(this).prop('checked'));
        });
    };

    var reApplyStateAndClose = function (link) {
        var parent = $(link).closest('.refine');

        $('input[type=checkbox]', $(parent)).each(function (index) {
            $(this).prop('checked', currentState[index]);
        });

        $(parent).removeClass('open');
        setBadges();
    };

    var setBadges = function () {
        $('.badge', '#event-listing-refine-bar').css('visibility', 'hidden');

        var allcount = 0;
        $('.refine', '#event-listing-refine-bar').each(function () {
            var count = 0;
            $('input[type=checkbox]', $(this)).each(function () {
                if ($(this).prop('checked')) {
                    count++;
                    allcount++;
                }
            });

            var $lat = $('input[name=latitude]', $(this));
            if ($lat.length == 1 && $lat.val() !== '' && $lat.val() !== '0') {
                count++;
                allcount++;
            }

            if (count > 0) {
                $('.badge', $(this)).html('' + count + '').css('visibility', 'visible');
                if ($('.none-selected-error', this).length) {
                    $('.none-selected-error', this).hide();
                    $('.apply', this).removeClass('disabled').off('click').on('click', function () { applyFilter(); });
                    $('.update-button', '#event-listing-refine-bar').removeClass('disabled').prop('disabled', '');
                }
            }
            else if ($('.none-selected-error', this).length) {
                $('.none-selected-error', this).show();
                $('.apply', this).addClass('disabled').off('click');
                $('.update-button', '#event-listing-refine-bar').addClass('disabled').prop('disabled', 'disabled');
            }
        });

        if (allcount > 0) {
            $('.refine-all .badge', '#event-listing-refine-bar').html('' + allcount + '').css('visibility', 'visible');
        }
    };

    var applyFilter = function () {
        var href = window.location.href;

        href = STK.Utils.StripParamFromQueryString(href, 'keeptag');
        href = STK.Utils.StripParamFromQueryString(href, 'fromsearch');
        href = STK.Utils.StripParamFromQueryString(href, 'tag');
        href = STK.Utils.StripParamFromQueryString(href, 'price');
        href = STK.Utils.StripParamFromQueryString(href, 'longitude');
        href = STK.Utils.StripParamFromQueryString(href, 'latitude');
        href = STK.Utils.StripParamFromQueryString(href, 'location');

        var tag = getTag();
        if (typeof (tag) == 'undefined') { tag = ''; }
        if (href.indexOf('?') < 0) {
            href += '?keeptag=' + tag + '&fromsearch=true';
        }
        else {
            href += '&keeptag=' + tag + '&fromsearch=true';
        }

        $('input:checked', '#event-listing-refine-bar').each(function () {
            href += '&' + $(this).prop('name') + '=' + $(this).val();
        });

        $('input[name=longitude]', '#event-listing-refine-bar').each(function () {
            href += '&longitude=' + $(this).val();
        });

        $('input[name=latitude]', '#event-listing-refine-bar').each(function () {
            href += '&latitude=' + $(this).val();
        });

        $('input[name=location]', '#event-listing-refine-bar').each(function () {
            href += '&location=' + $(this).val();
        });

        window.location.href = href;
    };

    var getTag = function () {
        return $('input[name=tag]', '#event-listing-refine-bar').val();
    };

    var initialiseSlider = function () {
        var width = $(window).width();
        $('#refine-slider').css('left', width);

        var location = $('#location').val();
        if (location !== '') {
            $('.location-search-input').val(location);
            $('.search-all', '#event-listing-refine-bar').show();
        }
        else {
            $('.search-all', '#event-listing-refine-bar').hide();
        }
    };

    var searchAll = function () {
        $('#location').val('');
        $('#longitude').val('0');
        $('#latitude').val('0');
        $('.location-search-input').val('All locations');
        setBadges();
    };

    var revealSlider = function () {
        var top = $(document).scrollTop();
        $('#refine-slider').css('top', top).removeClass('hide-on-mobile').animate({ 'left': 0 }, 250);
        var height = $('#refine-slider').height() - $('.update-cancel-bar', '#event-listing-refine-bar').height();
        $('.scroller', '#refine-slider').height(height);
        $('body').css('overflow-y', 'hidden');

        currentState = [];
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function () {
            currentState.push($(this).prop('checked'));
        });
    };

    var clearHeight = function () {
        $('.scroller', '#refine-slider').height('');
    };

    var hideSlider = function () {
        var width = $(window).width();
        $('#refine-slider').animate({ 'left': width }, 250, 'swing', function () { $('#refine-slider').addClass('hide-on-mobile'); });
        $('body').css('overflow-y', 'scroll');
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function (index) {
            $(this).prop('checked', currentState[index]);
        });
        setBadges();
    };

    var clearAllFilters = function () {
        $('input[type=checkbox]', '#event-listing-refine-bar').each(function () {
            $(this).prop('checked', false);
        });

        searchAll();
    };

    var applyLocation = function () {
        setBadges();
        applyFilter();
    }

    return {
        Init: function () {
            setBadges();
            initialiseSlider();

            $('#event-listing-refine-bar').show();

            $('.link', '#event-listing-refine-bar').on('click', function () {
                closeFilters(this);
                openFilter(this);
            });

            $('.cancel', '#event-listing-refine-bar').on('click', function () {
                reApplyStateAndClose(this);
            });

            $('.apply', '#event-listing-refine-bar').on('click', function () {
                applyFilter();
            });

            $('input[type=checkbox]', '#event-listing-refine-bar').on('click', function () {
                setBadges();
            });

            $('#reveal-refine-by').click(function () {
                revealSlider();
            });

            $('.update-cancel-bar .cancel', '#event-listing-refine-bar').on('click', function () {
                hideSlider();
            });

            $('.update-cancel-bar .apply', '#event-listing-refine-bar').on('click', function () {
                applyFilter();
            });

            $('.clear-all-filters a', '#event-listing-refine-bar').on('click', function () {
                clearAllFilters();
                setBadges();
            });

            $('.search-all', '#event-listing-refine-bar').on('click', function () {
                searchAll();
            });

            $(window).on('resize', function () {
                clearHeight();
                hideSlider();
            });
        },
        ApplyLocation: applyLocation
    };
})();

STK.RefineBy.Init();

<|endoftext|>


<commit_before>FOAModel({
  name: 'QIssueCreateView',
  extendsModel: 'DetailView',

  properties: [
    {
      name: 'model',
      factory: function() { return QIssue; }
    },
    {
      model_: 'BooleanProperty',
      name: 'saving',
      defaultValue: false
    },
    { name: 'errorView', factory: function() { return TextFieldView.create({ mode: 'read-only' }); } },
  ],

  actions: [
    {
      name: 'save',
      label: 'Create',
      isEnabled: function() { return ! this.saving },
      action: function() {
        var self = this;
        this.saving = true;
        this.errorView.data = "";
        this.X.IssueDAO.put(this.data, {
          put: function(obj) {
            self.saving = false;
            self.X.browser.location.id = obj.id;
          },
          error: function() {
            self.saving = false;
            self.errorView.data = "Error creating issue.";
          }
        });
      }
    },
    {
      name: 'discard',
      label: 'Discard',
      isEnabled: function() { return ! this.saving },
      action: function() {
        this.X.browser.location.createMode = false;
      }
    },
  ],

  templates: [
    function toHTML() {/*
      <div class="issueCreateView" id="<%= this.id %>">

      Create Issue

Summary:	$$summary

Description:	$$description

Status:
        <% var Y = this.X.sub(); Y.registerModel(StatusAutocompleteView, 'AutocompleteView'); %>
        $$status{ X: Y }

Cc:	$$cc

Labels:
        <% Y = this.X.sub(); Y.registerModel(LabelAutocompleteView, 'AutocompleteView'); %>
        $$labels{ X: Y, model_: 'GriddedStringArrayView' }

      <%= ActionButton.create({ action: this.model_.SAVE, value: SimpleValue.create(this) }) %>
      <%= ActionButton.create({ action: this.model_.DISCARD, value: SimpleValue.create(this) }) %>
      %%errorView

    */}
  ]
});
<commit_msg>Add owner field to create view.  Fix navigation to issue after creation.<commit_after>FOAModel({
  name: 'QIssueCreateView',
  extendsModel: 'DetailView',

  properties: [
    {
      name: 'model',
      factory: function() { return QIssue; }
    },
    {
      model_: 'BooleanProperty',
      name: 'saving',
      defaultValue: false
    },
    { name: 'errorView', factory: function() { return TextFieldView.create({ mode: 'read-only' }); } },
  ],

  actions: [
    {
      name: 'save',
      label: 'Create',
      isEnabled: function() { return ! this.saving },
      action: function() {
        var self = this;
        this.saving = true;
        this.errorView.data = "";
        this.X.IssueDAO.put(this.data, {
          put: function(obj) {
            self.saving = false;
            self.X.browser.location.createMode = false;
            self.X.browser.location.id = obj.id;
          },
          error: function() {
            self.saving = false;
            self.errorView.data = "Error creating issue.";
          }
        });
      }
    },
    {
      name: 'discard',
      label: 'Discard',
      isEnabled: function() { return ! this.saving },
      action: function() {
        this.X.browser.location.createMode = false;
      }
    },
  ],

  templates: [
    function toHTML() {/*
      <div class="issueCreateView" id="<%= this.id %>">

      Create Issue

Summary:	$$summary

Description:	$$description

Status:
        <% var Y = this.X.sub(); Y.registerModel(StatusAutocompleteView, 'AutocompleteView'); %>
        $$status{ X: Y }

Owner:	$$owner

Cc:	$$cc

Labels:
        <% Y = this.X.sub(); Y.registerModel(LabelAutocompleteView, 'AutocompleteView'); %>
        $$labels{ X: Y, model_: 'GriddedStringArrayView' }

      <%= ActionButton.create({ action: this.model_.SAVE, value: SimpleValue.create(this) }) %>
      <%= ActionButton.create({ action: this.model_.DISCARD, value: SimpleValue.create(this) }) %>
      %%errorView

    */}
  ]
});
<|endoftext|>


<commit_before>var Ripple = require('ripple-lib')
var request = require('request')
var RippleAddress = require('../app/models/ripple_address.js');
var RippleTransaction = require('../app/models/ripple_transaction.js');

var address = null;
var lastTxId = null;

function getNextNotification() {
  base = 'http://ripple-simple-api.herokuapp.com/api/v1/';
  url = base + 'address/' + address + '/next_notification';
  if (lastTxId) { url = (url + '/' + lastTxId) };
  request.get({ url: url, json: true }, function(err, resp, body) {
    if (body.notification) {
      lastTxId = body.notification.txHash;
      handleNewNotification(body.notification);
    } else {
      setTimeout(getNextNotification, 2000);
    }
  });
}

function getHotWallet(fn) {
  RippleAddress.find({ where: { type: 'hot' }}).complete(function(err, address) {
    fn(address);
  });
}

function handleNewNotification(notification) {
  // Inbound
  // -- Create ripple transaction

  // Outbound
  // -- Find and update ripple transaction
  console.log(notification);

  var base = 'http://ripple-simple-api.herokuapp.com/api/v1/';
  url = base + 'address/'+notification.address+'/tx/'+notification.txHash;
  request.get({ url: url, json: true }, function(err, resp, body) {
    getHotWallet(function(address) {
      address.previous_transaction_hash = body.tx.hash;
      address.save().complete(function(err, add) {
        console.log('updated the last transaction hash for the hot wallet address');
        if (notification.direction == 'incoming') {
          console.log('received an incoming payment');
          console.log('TODO: create a new ripple transaction record');
          console.log(body.tx);
        } else {
          console.log('received confirmation of an outgoing payment');
          RippleTransaction.find({ where: { transaction_hash: body.tx.hash } }).complete(function(err, transaction) {
            console.log("trying to match a ripple transaction from the database...");
            if (transaction) {
              console.log('a transaction in the database matches!');
              console.log(transaction);
            } else {
              console.log('no transaction record found in the databse.');
            }
            getNextNotification();
          });
        }
      });
    });
  });
}

getHotWallet(function(wallet){
  lastTxId = wallet.previous_transaction_hash;
  address = wallet.address;
  console.log('listening for transactions on', address);
  getNextNotification();
});

<commit_msg>[FEATURE] Refactor listener worker to use client library.<commit_after>var Ripple = require('ripple-lib')
var request = require('request')
var RippleAddress = require('../app/models/ripple_address.js');
var RippleTransaction = require('../app/models/ripple_transaction.js');
var RippleSimpleClient = require('../lib/ripple_simple_client.js');

var client = new RippleSimpleClient({
  apiUrl: process.env.RIPPLE_SIMPLE_API
});

getHotWallet(function(wallet){
  address = wallet.address;
  client.address = wallet.address;
  getNextNotification();
});

function getNextNotification() {
  client.getNextNotification(function(err, notification){
    if (notification) {
      handleNewNotification(notification);
    } else {
      setTimeout(getNextNotification, 2000);
    }
  });
}

function getHotWallet(fn) {
  RippleAddress.find({ where: { type: 'hot' }}).complete(function(err, address) {
    fn(address);
  });
}

function lookupTransaction(transactionHash, fn){
  RippleTransaction.find({ where: {
    transaction_hash: transactionHash
  }}).complete(fn);
}

function handleNewNotification(notification) {
  if (notification.type == 'payment') {
    console.log(notification.tx_hash);
    lookupTransaction(notification.tx_hash, function(err, transaction) {
      console.log(err);
      console.log(transaction);
      if (transaction) {
        transaction.transaction_state = notification.tx_result;
        transaction.save().complete(function(err, transaction){
          console.log(transaction);
        });
      } else if (notification.tx_direction == 'inbound') {
        console.log('inbound transaction');
      }
    });
  }
}
<|endoftext|>


<commit_before>
module.exports = function (conf) {

	var fs = require('fs');
	var Promise = require('bluebird');
	var _ = require("underscore");
	var spawn = require('child_process').spawn;
	var path = require('path');
	var Joi = require('joi');

	var executionmethods = require('./executionserver.methods')(conf);
	var joijob = require('./joi.job')(Joi);

	var handler = {};

	handler.submitJob = function(doc, cwd){

		Joi.assert(doc, joijob.job);

		return new Promise(function(resolve, reject){
			var command = 'bsub';
			var parameters = doc.parameters;

			var params = [];

			if(doc.jobparameters){
				params = doc.jobparameters;
			}

			params.push("-cwd");
			params.push(cwd);
			params.push("-e");
			params.push(path.join(cwd, "stderr.err"));
			params.push("-o");
			params.push(path.join(cwd, "stdout.out"));
			params.push("-u");
			params.push(doc.userEmail);
			params.push("-J");
			params.push(doc.userEmail);

			params.push(doc.executable);
			if(parameters){
				for(var i = 0; i < parameters.length; i++){
					var param = parameters[i];
					if(param.flag){
						params.push(param.flag);
					}
					if(param.name){
						params.push(param.name);
					}
				}
			}

			try{
				const runcommand = spawn(command, params);

				var allerror = "";
				runcommand.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				runcommand.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample: Job <898104> is submitted to default queue <day>"
				runcommand.on('close', function(code){
					if(code){
						resolve({
							status: 'FAIL',
							error: allerror + alldata
						});
					}

					var ind = alldata.indexOf('<') + 1;
                    var jobid = alldata.substr(ind, alldata.indexOf('>') - ind);

					resolve({
						jobid : Number.parseInt(jobid),
						status: 'RUN'
					});
				});

			}catch(e){
				reject({
					status: "FAIL",
					error: e
				});
			}

		});

	}

	handler.getJobStatus = function(doc){

		Joi.assert(doc.jobstatus, joijob.jobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const ps = spawn('bjobs', params);

				var allerror = "";
				ps.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				ps.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample success: 898104  jprieto DONE  day        killdevil-l donor_pool2 *gmail.com Feb 14 11:16"
				//"sample fail: Job <8981> is not found"

				ps.on('close', function(code){

					if(alldata && alldata.indexOf('DONE') !== -1 || allerror && allerror.indexOf('is not found') !== -1){
						resolve({
							status: 'DONE',
							stat: alldata
						});
					}else if(alldata && alldata.indexOf('EXIT') !== -1){
						resolve({
							status: 'EXIT',
							stat: alldata
						});
					}else if(code || allerror){
						resolve({
							status: 'FAIL',
							error: allerror
						});
					}else{
						resolve({
							status: 'RUN',
							stat: alldata
						});
					}

				});

			}catch(e){
				reject(e);
			}

		});
	}

	handler.killJob = function(doc){

		Joi.assert(doc.jobstatus, joijob.jobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const kill = spawn('bkill', params);

				var allerror = "";
				kill.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				kill.stdout.on('data', function(data){
					alldata += data;
				});

				kill.on('close', function(code){
					resolve({
						status: 'KILL',
						stat: allerror + alldata
					});
				});

			}catch(e){
				reject(e);
			}

		});

	}

	return handler;
}<commit_msg>BUG: Job parameters expansion<commit_after>
module.exports = function (conf) {

	var fs = require('fs');
	var Promise = require('bluebird');
	var _ = require("underscore");
	var spawn = require('child_process').spawn;
	var path = require('path');
	var Joi = require('joi');

	var executionmethods = require('./executionserver.methods')(conf);
	var joijob = require('./joi.job')(Joi);

	var handler = {};

	handler.submitJob = function(doc, cwd){

		Joi.assert(doc, joijob.job);

		return new Promise(function(resolve, reject){
			var command = 'bsub';
			var parameters = doc.parameters;

			var params = [];

			if(doc.jobparameters){
				for(var i = 0; i < doc.jobparameters.length; i++){
                                        var param = doc.jobparameters[i];
                                        if(param.flag){
                                                params.push(param.flag);
                                        }
                                        if(param.name){
                                                params.push(param.name);
                                        }
                                }

			}

			params.push("-cwd");
			params.push(cwd);
			params.push("-e");
			params.push(path.join(cwd, "stderr.err"));
			params.push("-o");
			params.push(path.join(cwd, "stdout.out"));
			params.push("-u");
			params.push(doc.userEmail);
			params.push("-J");
			params.push(doc.userEmail);

			params.push(doc.executable);
			if(parameters){
				for(var i = 0; i < parameters.length; i++){
					var param = parameters[i];
					if(param.flag){
						params.push(param.flag);
					}
					if(param.name){
						params.push(param.name);
					}
				}
			}

			console.log(params);

			try{
				const runcommand = spawn(command, params);

				var allerror = "";
				runcommand.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				runcommand.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample: Job <898104> is submitted to default queue <day>"
				runcommand.on('close', function(code){
					if(code){
						resolve({
							status: 'FAIL',
							error: allerror + alldata
						});
					}

					var ind = alldata.indexOf('<') + 1;
                    var jobid = alldata.substr(ind, alldata.indexOf('>') - ind);

					resolve({
						jobid : Number.parseInt(jobid),
						status: 'RUN'
					});
				});

			}catch(e){
				reject({
					status: "FAIL",
					error: e
				});
			}

		});

	}

	handler.getJobStatus = function(doc){

		Joi.assert(doc.jobstatus, joijob.jobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const ps = spawn('bjobs', params);

				var allerror = "";
				ps.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				ps.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample success: 898104  jprieto DONE  day        killdevil-l donor_pool2 *gmail.com Feb 14 11:16"
				//"sample fail: Job <8981> is not found"

				ps.on('close', function(code){

					if(alldata && alldata.indexOf('DONE') !== -1 || allerror && allerror.indexOf('is not found') !== -1){
						resolve({
							status: 'DONE',
							stat: alldata
						});
					}else if(alldata && alldata.indexOf('EXIT') !== -1){
						resolve({
							status: 'EXIT',
							stat: alldata
						});
					}else if(code || allerror){
						resolve({
							status: 'FAIL',
							error: allerror
						});
					}else{
						resolve({
							status: 'RUN',
							stat: alldata
						});
					}

				});

			}catch(e){
				reject(e);
			}

		});
	}

	handler.killJob = function(doc){

		Joi.assert(doc.jobstatus, joijob.jobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const kill = spawn('bkill', params);

				var allerror = "";
				kill.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				kill.stdout.on('data', function(data){
					alldata += data;
				});

				kill.on('close', function(code){
					resolve({
						status: 'KILL',
						stat: allerror + alldata
					});
				});

			}catch(e){
				reject(e);
			}

		});

	}

	return handler;
}
<|endoftext|>


<commit_before><commit_msg>more tests<commit_after><|endoftext|>


<commit_before>define(["dojo/_base/array", "dojo/_base/declare", "./NeutralColorModel"],
	function(arr, declare, NeutralColorModel){

	return declare("dojox.color.MeanColorModel", NeutralColorModel, {
		// summary:
		//		A color model that returns a color from a data value
		//		using an interpolation between two extremum colors around the mean value.

		constructor: function(startColor, endColor){
		},

		computeNeutral: function(min, max, sum, values){
			//	summary:
			//		Return the neutral value in this case the maean value of the data values.
			//	min: Number
			//		The minimal value.
			//	max: Number
			//		The maximum value.
			//	sum: Number
			//		The sum of all values.
			//	values: Number[]
			//		The sorted array of values used to compute colors.
			var median = min;
			if(values.length != 0){
				if(values.length < 3){
					median = sum / values.length;
				}else if((values.length & 1) == 0){
					median = (values[values.length / 2 - 1] + values[values.length / 2]) / 2;
				}else{
					median = values[Math.floor(values.length / 2)];
				}
			}
			return median;
		}
	});
});
<commit_msg>fix spelling<commit_after>define(["dojo/_base/array", "dojo/_base/declare", "./NeutralColorModel"],
	function(arr, declare, NeutralColorModel){

	return declare("dojox.color.MeanColorModel", NeutralColorModel, {
		// summary:
		//		A color model that returns a color from a data value
		//		using an interpolation between two extremum colors around the mean value.

		constructor: function(startColor, endColor){
		},

		computeNeutral: function(min, max, sum, values){
			//	summary:
			//		Return the neutral value in this case the mean value of the data values.
			//	min: Number
			//		The minimal value.
			//	max: Number
			//		The maximum value.
			//	sum: Number
			//		The sum of all values.
			//	values: Number[]
			//		The sorted array of values used to compute colors.
			var median = min;
			if(values.length != 0){
				if(values.length < 3){
					median = sum / values.length;
				}else if((values.length & 1) == 0){
					median = (values[values.length / 2 - 1] + values[values.length / 2]) / 2;
				}else{
					median = values[Math.floor(values.length / 2)];
				}
			}
			return median;
		}
	});
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import MenuItem from 'material-ui/MenuItem';
import { fetchQuerySplitStoryCount, fetchDemoQuerySplitStoryCount, resetSentenceCounts, setSentenceDataPoint, resetSentenceDataPoint } from '../../../actions/explorerActions';
import composeAsyncContainer from '../../common/AsyncContainer';
import composeSummarizedVisualization from './SummarizedVizualization';
import AttentionOverTimeChart from '../../vis/AttentionOverTimeChart';
import { DownloadButton } from '../../common/IconButton';
import ActionMenu from '../../common/ActionMenu';
import { oneDayLater, solrFormat } from '../../../lib/dateUtil';
import { queryChangedEnoughToUpdate, postToDownloadUrl } from '../../../lib/explorerUtil';
import messages from '../../../resources/messages';
import { FETCH_INVALID } from '../../../lib/fetchConstants';

const localMessages = {
  overallSeries: { id: 'explorer.attention.series.overall', defaultMessage: 'Whole Query' },
  lineChartTitle: { id: 'explorer.attention.lineChart.title', defaultMessage: 'Attention Over Time' },
  descriptionIntro: { id: 'explorer.attention.lineChart.intro', defaultMessage: '
Compare the attention paid to your queries over time to understand how they are covered. This chart shows the number of stories that match each of your queries. Spikes in attention can reveal key events. Plateaus can reveal stable, "normal", attention levels. Click a point to see words and headlines for those dates.
' },
  descriptionDetail: { id: 'explorer.attention.lineChart.detail', defaultMessage: '
This chart includes one line for each query in your search. Each line charts the number of stories that matched your query per day in the sources and collections you have specified.

Roll over the line chart to see the stories per day in that period of time. Click the download button in the top right to download the raw counts in a CSV spreadsheet. Click the three lines in the top right of the chart to export the chart as an image file.
' },
};

class QueryAttentionOverTimeResultsContainer extends React.Component {
  state = {
    isDrillDownVisible: false,
    dateRange: null,
    clickedQuery: null,
  }
  componentWillReceiveProps(nextProps) {
    const { lastSearchTime, fetchData } = this.props;
    if (nextProps.lastSearchTime !== lastSearchTime) {
      fetchData(nextProps.queries);
    }
  }
  shouldComponentUpdate(nextProps) {
    const { results, queries } = this.props;
    return queryChangedEnoughToUpdate(queries, nextProps.queries, results, nextProps.results);
  }
  handleDataPointClick = (date0, date1, evt, origin) => {
    const { selectDataPoint, queries } = this.props;
    const name = origin.series.name;
    const currentQueryOfInterest = queries.filter(qry => qry.label === name)[0];
    const dayGap = 1; // TODO: harcoded for now because we are always showing daily results
    // date calculations for span/range
    const clickedQuery = {
      q: currentQueryOfInterest.q,
      start_date: solrFormat(date1),
      color: origin.series.color,
      dayGap,
    };
    clickedQuery.end_date = solrFormat(oneDayLater(date1), true);
    this.setState({ clickedQuery });
    selectDataPoint(clickedQuery);
  }
  downloadCsv = (query) => {
    postToDownloadUrl('/api/explorer/stories/split-count.csv', query);
  }
  render() {
    const { results, queries } = this.props;
    const { formatMessage } = this.props.intl;
    // stich together bubble chart data

    // because these results are indexed, we can merge these two arrays
    // we may have more results than queries b/c queries can be deleted but not executed
    // so we have to do the following
    const safeResults = results.map((r, idx) => Object.assign({}, r, queries[idx]));

    // stich together line chart data
    let series = [];
    if (safeResults && safeResults.length > 0) {
      series = [
        ...safeResults.map((query, idx) => {    // add series for all the results
          if (query.counts) {
            return {
              id: idx,
              name: query.label,
              data: query.counts.map(d => [d.date, d.count]),
              color: query.color,
            };
          } return {};
        }),
      ];
    }
    return (

        <AttentionOverTimeChart
          series={series}
          height={300}
          backgroundColor="#f5f5f5"
          onDataPointClick={this.handleDataPointClick}
        />

          <ActionMenu actionTextMsg={messages.downloadOptions}>
            {safeResults.map((q, idx) =>
              <MenuItem
                key={idx}
                className="action-icon-menu-item"
                primaryText={formatMessage(messages.downloadDataCsv, { name: q.label })}
                rightIcon={<DownloadButton />}
                onTouchTap={() => this.downloadCsv(q)}
              />
            )}
          </ActionMenu>

    );
  }
}

QueryAttentionOverTimeResultsContainer.propTypes = {
  // from parent
  lastSearchTime: PropTypes.number.isRequired,
  queries: PropTypes.array.isRequired,
  isLoggedIn: PropTypes.bool.isRequired,
  // from composition
  intl: PropTypes.object.isRequired,
  // from dispatch
  fetchData: PropTypes.func.isRequired,
  results: PropTypes.array.isRequired,
  daySpread: PropTypes.bool,
  // from mergeProps
  asyncFetch: PropTypes.func.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  selectDataPoint: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  lastSearchTime: state.explorer.lastSearchTime.time,
  fetchStatus: state.explorer.storySplitCount.fetchStatus || FETCH_INVALID,
  results: state.explorer.storySplitCount.results,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (queries) => {
    // this should trigger when the user clicks the Search button or changes the URL
    // for n queries, run the dispatch with each parsed query
    dispatch(resetSentenceCounts()); // necessary if a query deletion has occurred
    if (ownProps.isLoggedIn) {
      const runTheseQueries = queries || ownProps.queries;
      runTheseQueries.map((q) => {
        const infoToQuery = {
          start_date: q.startDate,
          end_date: q.endDate,
          q: q.q,
          index: q.index,
          sources: q.sources.map(s => s.id),
          collections: q.collections.map(c => c.id),
        };
        return dispatch(fetchQuerySplitStoryCount(infoToQuery));
      });
    } else if (queries || ownProps.queries) { // else assume DEMO mode, but assume the queries have been loaded
      const runTheseQueries = queries || ownProps.queries;
      runTheseQueries.map((q, index) => {
        const demoInfo = {
          index, // should be same as q.index btw
          search_id: q.searchId, // may or may not have these
          query_id: q.id, // could be undefined
          q: q.q, // only if no query id, means demo user added a keyword
        };
        return dispatch(fetchDemoQuerySplitStoryCount(demoInfo));
      });
    }
  },
  selectDataPoint: (clickedDataPoint) => {
    dispatch(resetSentenceDataPoint());
    dispatch(setSentenceDataPoint(clickedDataPoint));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps.queries);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      composeSummarizedVisualization(localMessages.lineChartTitle, localMessages.descriptionIntro, localMessages.descriptionDetail)(
        composeAsyncContainer(
          QueryAttentionOverTimeResultsContainer
        )
      )
    )
  );
<commit_msg>#936 UI widget for normalization<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import MenuItem from 'material-ui/MenuItem';
import { fetchQuerySplitStoryCount, fetchDemoQuerySplitStoryCount, resetSentenceCounts, setSentenceDataPoint, resetSentenceDataPoint } from '../../../actions/explorerActions';
import composeAsyncContainer from '../../common/AsyncContainer';
import composeSummarizedVisualization from './SummarizedVizualization';
import AttentionOverTimeChart from '../../vis/AttentionOverTimeChart';
import { DownloadButton } from '../../common/IconButton';
import ActionMenu from '../../common/ActionMenu';
import { oneDayLater, solrFormat } from '../../../lib/dateUtil';
import { queryChangedEnoughToUpdate, postToDownloadUrl } from '../../../lib/explorerUtil';
import messages from '../../../resources/messages';
import { FETCH_INVALID } from '../../../lib/fetchConstants';

const localMessages = {
  overallSeries: { id: 'explorer.attention.series.overall', defaultMessage: 'Whole Query' },
  lineChartTitle: { id: 'explorer.attention.lineChart.title', defaultMessage: 'Attention Over Time' },
  descriptionIntro: { id: 'explorer.attention.lineChart.intro', defaultMessage: '
Compare the attention paid to your queries over time to understand how they are covered. This chart shows the number of stories that match each of your queries. Spikes in attention can reveal key events. Plateaus can reveal stable, "normal", attention levels. Click a point to see words and headlines for those dates.
' },
  descriptionDetail: { id: 'explorer.attention.lineChart.detail', defaultMessage: '
This chart includes one line for each query in your search. Each line charts the number of stories that matched your query per day in the sources and collections you have specified.

Roll over the line chart to see the stories per day in that period of time. Click the download button in the top right to download the raw counts in a CSV spreadsheet. Click the three lines in the top right of the chart to export the chart as an image file.
' },
  withKeywords: { id: 'explorer.attention.mode.withkeywords', defaultMessage: 'View Story Count (default)' },
  withoutKeywords: { id: 'explorer.attention.mode.withoutkeywords', defaultMessage: 'View Normalized Story Count' },

};

const VIEW_NORMALIZED = 'VIEW_NORMALIZED';
const VIEW_REGULAR = 'VIEW_REGULAR';

class QueryAttentionOverTimeResultsContainer extends React.Component {
  state = {
    isDrillDownVisible: false,
    dateRange: null,
    clickedQuery: null,
    view: VIEW_REGULAR, // which view to show (see view constants above)
  }

  componentWillReceiveProps(nextProps) {
    const { lastSearchTime, fetchData } = this.props;
    if (nextProps.lastSearchTime !== lastSearchTime) {
      fetchData(nextProps.queries);
    }
  }
  shouldComponentUpdate(nextProps) {
    const { results, queries } = this.props;
    return queryChangedEnoughToUpdate(queries, nextProps.queries, results, nextProps.results);
  }

  setView = (nextView) => {
    this.setState({ view: nextView });
  }

  handleDataPointClick = (date0, date1, evt, origin) => {
    const { selectDataPoint, queries } = this.props;
    const name = origin.series.name;
    const currentQueryOfInterest = queries.filter(qry => qry.label === name)[0];
    const dayGap = 1; // TODO: harcoded for now because we are always showing daily results
    // date calculations for span/range
    const clickedQuery = {
      q: currentQueryOfInterest.q,
      start_date: solrFormat(date1),
      color: origin.series.color,
      dayGap,
    };
    clickedQuery.end_date = solrFormat(oneDayLater(date1), true);
    this.setState({ clickedQuery });
    selectDataPoint(clickedQuery);
  }
  downloadCsv = (query) => {
    postToDownloadUrl('/api/explorer/stories/split-count.csv', query);
  }
  render() {
    const { results, queries } = this.props;
    const { formatMessage } = this.props.intl;
    // stich together bubble chart data

    // because these results are indexed, we can merge these two arrays
    // we may have more results than queries b/c queries can be deleted but not executed
    // so we have to do the following
    const safeResults = results.map((r, idx) => Object.assign({}, r, queries[idx]));
    // stich together line chart data
    let series = [];
    if (safeResults && safeResults.length > 0) {
      series = [
        ...safeResults.map((query, idx) => {    // add series for all the results
          if (query.counts || query.normalizedCounts) {
            return {
              id: idx,
              name: query.label,
              data: this.state.view === VIEW_NORMALIZED ? query.normalizedCounts.map(d => [d.date, d.count]) : query.counts.map(d => [d.date, d.count]),
              color: query.color,
            };
          } return {};
        }),
      ];
    }
    const viewOptions = [

        <MenuItem
          className="action-icon-menu-item"
          primaryText={formatMessage(localMessages.withoutKeywords)}
          disabled={this.state.view === VIEW_NORMALIZED}
          onTouchTap={() => this.setView(VIEW_NORMALIZED)}
        />
        <MenuItem
          className="action-icon-menu-item"
          primaryText={formatMessage(localMessages.withKeywords)}
          disabled={this.state.view === VIEW_REGULAR}
          onTouchTap={() => this.setView(VIEW_REGULAR)}
        />
      ,
    ];
    return (

        <AttentionOverTimeChart
          series={series}
          height={300}
          backgroundColor="#f5f5f5"
          onDataPointClick={this.handleDataPointClick}
        />

          <ActionMenu actionTextMsg={messages.downloadOptions}>
            {safeResults.map((q, idx) =>
              <MenuItem
                key={idx}
                className="action-icon-menu-item"
                primaryText={formatMessage(messages.downloadDataCsv, { name: q.label })}
                rightIcon={<DownloadButton />}
                onTouchTap={() => this.downloadCsv(q)}
              />
            )}
          </ActionMenu>
          <ActionMenu actionTextMsg={messages.viewOptions}>
            {viewOptions}
          </ActionMenu>

    );
  }
}

QueryAttentionOverTimeResultsContainer.propTypes = {
  // from parent
  lastSearchTime: PropTypes.number.isRequired,
  queries: PropTypes.array.isRequired,
  isLoggedIn: PropTypes.bool.isRequired,
  // from composition
  intl: PropTypes.object.isRequired,
  // from dispatch
  fetchData: PropTypes.func.isRequired,
  results: PropTypes.array.isRequired,
  daySpread: PropTypes.bool,
  // from mergeProps
  asyncFetch: PropTypes.func.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  selectDataPoint: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  lastSearchTime: state.explorer.lastSearchTime.time,
  fetchStatus: state.explorer.storySplitCount.fetchStatus || FETCH_INVALID,
  results: state.explorer.storySplitCount.results,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (queries) => {
    // this should trigger when the user clicks the Search button or changes the URL
    // for n queries, run the dispatch with each parsed query
    dispatch(resetSentenceCounts()); // necessary if a query deletion has occurred
    if (ownProps.isLoggedIn) {
      const runTheseQueries = queries || ownProps.queries;
      runTheseQueries.map((q) => {
        const infoToQuery = {
          start_date: q.startDate,
          end_date: q.endDate,
          q: q.q,
          index: q.index,
          sources: q.sources.map(s => s.id),
          collections: q.collections.map(c => c.id),
        };
        return dispatch(fetchQuerySplitStoryCount(infoToQuery));
      });
    } else if (queries || ownProps.queries) { // else assume DEMO mode, but assume the queries have been loaded
      const runTheseQueries = queries || ownProps.queries;
      runTheseQueries.map((q, index) => {
        const demoInfo = {
          index, // should be same as q.index btw
          search_id: q.searchId, // may or may not have these
          query_id: q.id, // could be undefined
          q: q.q, // only if no query id, means demo user added a keyword
        };
        return dispatch(fetchDemoQuerySplitStoryCount(demoInfo));
      });
    }
  },
  selectDataPoint: (clickedDataPoint) => {
    dispatch(resetSentenceDataPoint());
    dispatch(setSentenceDataPoint(clickedDataPoint));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps.queries);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      composeSummarizedVisualization(localMessages.lineChartTitle, localMessages.descriptionIntro, localMessages.descriptionDetail)(
        composeAsyncContainer(
          QueryAttentionOverTimeResultsContainer
        )
      )
    )
  );
<|endoftext|>


<commit_before>require([
    'jquery',
    'underscore',
    'knockout',
    'views/page-view',
    'views/graph-manager/graph',
    'views/graph-manager/branch-list',
    'views/graph-manager/node-list',
    'views/graph-manager/permissions-list',
    'views/graph-manager/node-form',
    'views/graph-manager/permissions-form',
    'views/graph-manager/branch-info',
    'models/node',
    'models/graph',
    'bootstrap-nifty'
], function($, _, ko, PageView, GraphView, BranchListView, NodeListView, PermissionsListView, NodeFormView, PermissionsFormView, BranchInfoView, NodeModel, GraphModel) {
    var graphData = JSON.parse($('#graph-data').val());
    var branches = JSON.parse($('#branches').val());
    var datatypes = JSON.parse($('#datatypes').val());
    // var datatypelookup = {}
    // _.each(datatypes, function(datatype){
    //     datatypelookup[datatype.datatype] = datatype.iconclass;
    // }, this)

    // graphData.nodes.forEach(function (node, i) {
    //     graphData.nodes[i] = new NodeModel({
    //         source: node,
    //         datatypelookup: datatypelookup
    //     });
    // });

    branches.forEach(function(branch){
        branch.selected = ko.observable(false);
        branch.filtered = ko.observable(false);
    }, this);

    var graphModel = new GraphModel({
        nodes: graphData.nodes,
        edges: graphData.edges,
        datatypes: datatypes
    });

    graphModel.on('changed', function(model, options){
        console.log('changed');
    })

    var viewModel = {
        nodes: ko.observableArray(graphData.nodes),
        edges: ko.observableArray(graphData.edges),
        branches: ko.observableArray(branches)
    };

    viewModel.editNode = ko.computed(function() {
        var editNode = _.find(viewModel.nodes(), function(node){
            return node.editing();
        }, this);
        return editNode;
    });

    viewModel.selectedNodes = ko.computed(function() {
        var selectedNodes = _.filter(viewModel.nodes(), function(node){
            return node.selected();
        }, this);
        return selectedNodes;
    });

    viewModel.graph = new GraphView({
        el: $('#graph'),
        nodes: viewModel.nodes,
        edges: viewModel.edges,
        editNode: viewModel.editNode
    });

    ko.computed(function() {
        graphModel.get('editNode')();
        graphModel.get('selectedNodes')();
        viewModel.graph.render();
    });

    viewModel.nodeForm = new NodeFormView({
        el: $('#nodeCrud'),
        node: graphModel.get('editNode')
    });

    viewModel.nodeForm.on('node-updated', function(res) {
        var nodes = viewModel.nodes();
        res.group_nodes.forEach(function(nodeJSON) {
            var node = _.find(nodes, function (node) {
                return node.nodeid === nodeJSON.nodeid;
            });
            node.parse(nodeJSON);
        });
    });

    viewModel.nodeForm.on('node-deleted', function (node) {
        graphModel.deleteNode(node);
    });

    viewModel.graph.on('node-clicked', function (node) {
        if (viewModel.editNode() && viewModel.editNode().dirty()) {
            viewModel.nodeForm.closeClicked(true);
            return;
        }
        viewModel.nodes().forEach(function (node) {
            node.editing(false);
        });
        node.editing(true);
    });

    viewModel.branchList = new BranchListView({
        el: $('#branch-library'),
        branches: viewModel.branches,
        graphModel: graphModel
    });

    viewModel.nodeList = new NodeListView({
        el: $('#node-listing'),
        graphModel: graphModel
    });

    viewModel.permissionsList = new PermissionsListView({
        el: $('#node-permissions')
    });

    viewModel.permissionsForm = new PermissionsFormView({
        el: $('#permissions-panel')
    });

    new PageView({
        viewModel: viewModel
    });

    var resize = function(){
        $('#graph').height($(window).height()-200);
        $('.tab-content').height($(window).height()-259);
        $('.grid-container').height($(window).height()-360);
        viewModel.graph.resize();
    }

    $( window ).resize(resize);

    resize();
});
<commit_msg>rename graph to graphView<commit_after>require([
    'jquery',
    'underscore',
    'knockout',
    'views/page-view',
    'views/graph-manager/graph',
    'views/graph-manager/branch-list',
    'views/graph-manager/node-list',
    'views/graph-manager/permissions-list',
    'views/graph-manager/node-form',
    'views/graph-manager/permissions-form',
    'views/graph-manager/branch-info',
    'models/node',
    'models/graph',
    'bootstrap-nifty'
], function($, _, ko, PageView, GraphView, BranchListView, NodeListView, PermissionsListView, NodeFormView, PermissionsFormView, BranchInfoView, NodeModel, GraphModel) {
    var graphData = JSON.parse($('#graph-data').val());
    var branches = JSON.parse($('#branches').val());
    var datatypes = JSON.parse($('#datatypes').val());
    // var datatypelookup = {}
    // _.each(datatypes, function(datatype){
    //     datatypelookup[datatype.datatype] = datatype.iconclass;
    // }, this)

    // graphData.nodes.forEach(function (node, i) {
    //     graphData.nodes[i] = new NodeModel({
    //         source: node,
    //         datatypelookup: datatypelookup
    //     });
    // });

    branches.forEach(function(branch){
        branch.selected = ko.observable(false);
        branch.filtered = ko.observable(false);
    }, this);

    var graphModel = new GraphModel({
        nodes: graphData.nodes,
        edges: graphData.edges,
        datatypes: datatypes
    });

    graphModel.on('changed', function(model, options){
        console.log('changed');
    })

    var viewModel = {
        nodes: ko.observableArray(graphData.nodes),
        edges: ko.observableArray(graphData.edges),
        branches: ko.observableArray(branches)
    };

    viewModel.editNode = ko.computed(function() {
        var editNode = _.find(viewModel.nodes(), function(node){
            return node.editing();
        }, this);
        return editNode;
    });

    viewModel.selectedNodes = ko.computed(function() {
        var selectedNodes = _.filter(viewModel.nodes(), function(node){
            return node.selected();
        }, this);
        return selectedNodes;
    });

    viewModel.graphView = new GraphView({
        el: $('#graph'),
        nodes: viewModel.nodes,
        edges: viewModel.edges,
        editNode: viewModel.editNode
    });

    ko.computed(function() {
        graphModel.get('editNode')();
        graphModel.get('selectedNodes')();
        viewModel.graphView.render();
    });

    viewModel.nodeForm = new NodeFormView({
        el: $('#nodeCrud'),
        node: graphModel.get('editNode')
    });

    viewModel.nodeForm.on('node-updated', function(res) {
        var nodes = viewModel.nodes();
        res.group_nodes.forEach(function(nodeJSON) {
            var node = _.find(nodes, function (node) {
                return node.nodeid === nodeJSON.nodeid;
            });
            node.parse(nodeJSON);
        });
    });

    viewModel.nodeForm.on('node-deleted', function (node) {
        graphModel.deleteNode(node);
    });

    viewModel.graphView.on('node-clicked', function (node) {
        if (viewModel.editNode() && viewModel.editNode().dirty()) {
            viewModel.nodeForm.closeClicked(true);
            return;
        }
        viewModel.nodes().forEach(function (node) {
            node.editing(false);
        });
        node.editing(true);
    });

    viewModel.branchList = new BranchListView({
        el: $('#branch-library'),
        branches: viewModel.branches,
        graphModel: graphModel
    });

    viewModel.nodeList = new NodeListView({
        el: $('#node-listing'),
        graphModel: graphModel
    });

    viewModel.permissionsList = new PermissionsListView({
        el: $('#node-permissions')
    });

    viewModel.permissionsForm = new PermissionsFormView({
        el: $('#permissions-panel')
    });

    new PageView({
        viewModel: viewModel
    });

    var resize = function(){
        $('#graph').height($(window).height()-200);
        $('.tab-content').height($(window).height()-259);
        $('.grid-container').height($(window).height()-360);
        viewModel.graphView.resize();
    }

    $( window ).resize(resize);

    resize();
});
<|endoftext|>