{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); ');\nglobal.window = global.document.defaultView;\nglobal.navigator = global.window.navigator;\nconst $ = _$(window);\n\nchaiJquery(chai, chai.util, $);\n\nfunction renderComponent(ComponentClass, props = {}, state = {}) {\n const componentInstance = TestUtils.renderIntoDocument(\n \n \n \n );\n\n return $(ReactDOM.findDOMNode(componentInstance));\n}\n\n$.fn.simulate = function(eventName, value) {\n if (value) {\n this.val(value);\n }\n TestUtils.Simulate[eventName](this[0]);\n};\n\nexport {renderComponent, expect};\n"}}},{"rowIdx":353,"cells":{"target":{"kind":"string","value":"playground/topic/react/redux/counter/src/containers/Root.prod.js"},"feat_repo_name":{"kind":"string","value":"yardfarmer/bone"},"text":{"kind":"string","value":"import React, { Component } from 'react';\nimport { Provider } from 'react-redux';\nimport CounterApp from './CounterApp';\n\nexport default class Root extends Component {\n render() {\n const { store } = this.props;\n return (\n \n \n \n );\n }\n}\n"}}},{"rowIdx":354,"cells":{"target":{"kind":"string","value":"src/store/auth/reducer.spec.js"},"feat_repo_name":{"kind":"string","value":"asndev/webpack2-react-auth-starter"},"text":{"kind":"string","value":"import React from 'react'; // eslint-disable-line no-unused-vars\nimport { authReducer, AuthState } from './reducer';\nimport { authActions } from './actions';\n\ndescribe('store', () => {\n describe('AuthReducer', () => {\n it('should have the correct inital state', () => {\n const state = authReducer(undefined, { type: 'foobar' });\n expect(state.authenticated).toBe(false);\n expect(state.uid).toBe(null);\n expect(state.user).toBe(null);\n });\n\n it('should correctly handle successful login', () => {\n const state = authReducer(undefined, {\n payload: {\n uid: '1234567',\n name: 'Batman'\n },\n type: authActions.LOGIN_SUCCEEDED\n });\n\n expect(state.authenticated).toBe(true);\n expect(state.uid).toBe('1234567');\n expect(state.user.get('name')).toBe('Batman');\n });\n\n it('should correctly handle logout', () => {\n const loggedIn = new AuthState().merge({\n authenticated: true,\n uid: '1234',\n user: {}\n });\n\n const state = authReducer(loggedIn, {\n type: authActions.LOGOUT_SUCCEEDED\n });\n\n expect(state.authenticated).toBe(false);\n expect(state.uid).toBe(null);\n expect(state.user).toBe(null);\n });\n });\n});\n"}}},{"rowIdx":355,"cells":{"target":{"kind":"string","value":"src/scenes/App/components/Footer/index.js"},"feat_repo_name":{"kind":"string","value":"jsza/tempus-website"},"text":{"kind":"string","value":"import React from 'react'\n\nimport './styles.styl'\n\n\nconst Footer = ({ className, ...props }) =>\n \n \n \n\n\nexport default Footer\n"}}},{"rowIdx":356,"cells":{"target":{"kind":"string","value":"ajax/libs/reactstrap/5.0.0/reactstrap.min.js"},"feat_repo_name":{"kind":"string","value":"joeyparrish/cdnjs"},"text":{"kind":"string","value":"(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports,require('react'),require('react-dom'),require('react-popper'),require('react-transition-group/Transition')):'function'==typeof define&&define.amd?define(['exports','react','react-dom','react-popper','react-transition-group/Transition'],t):t(e.Reactstrap=e.Reactstrap||{},e.React,e.ReactDOM,e.ReactPopper || undefined,e.ReactTransitionGroup && e.ReactTransitionGroup.Transition || undefined)})(this,function(e,t,o,a,s){'use strict';function n(e,t){return t={exports:{}},e(t,t.exports),t.exports}function l(e){return function(){return e}}function r(e){if(null===e||e===void 0)throw new TypeError('Object.assign cannot be called with null or undefined');return Object(e)}function i(e){return null==e?void 0===e?te:ee:de&&de in Object(e)?d(e):c(e)}function d(e){var t=le.call(e,de),o=e[de];try{e[de]=void 0}catch(t){}var a=re.call(e);return t?e[de]=o:delete e[de],a}function c(e){return re.call(e)}function p(e){var t='undefined'==typeof e?'undefined':U(e);return null!=e&&('object'==t||'function'==t)}function u(){var e=document.createElement('div');e.style.position='absolute',e.style.top='-9999px',e.style.width='50px',e.style.height='50px',e.style.overflow='scroll',document.body.appendChild(e);var t=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),t}function g(e){document.body.style.paddingRight=0o;o++)t['_'+String.fromCharCode(o)]=o;var a=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if('0123456789'!==a.join(''))return!1;var s={};return['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'].forEach(function(e){s[e]=e}),'abcdefghijklmnopqrst'===Object.keys(Object.assign({},s)).join('')}catch(e){return!1}}()?Object.assign:function(e){for(var t,o,a=r(e),n=1;nl&&(l=0),n[l].focus()}}}},{key:'handleProps',value:function(){this.props.isOpen?this.addEvents():this.removeEvents()}},{key:'toggle',value:function(t){return this.props.disabled?t&&t.preventDefault():this.props.toggle(t)}},{key:'render',value:function(){var e,t=v(this.props,['toggle','disabled','inNavbar','direction']),o=t.className,s=t.cssModule,n=t.dropup,l=t.isOpen,r=t.group,i=t.size,d=t.nav,c=t.active,p=t.addonType,u=J(t,['className','cssModule','dropup','isOpen','group','size','nav','active','addonType']),g='down'===this.props.direction&&n?'up':this.props.direction;u.tag=u.tag||(d?'li':'div');var m=y(Q(o,'down'!==g&&'drop'+g,d&&c&&'active',(e={},K(e,'input-group-'+p,p),K(e,'btn-group',r),K(e,'btn-group-'+i,!!i),K(e,'dropdown',!r&&!p),K(e,'show',l),K(e,'nav-item',d),e)),s);return R.createElement(a.Manager,X({},u,{className:m,onKeyDown:this.handleKeyDown}))}}]),t}(R.Component);We.propTypes=Ue,We.defaultProps={isOpen:!1,direction:'down',nav:!1,active:!1,addonType:!1,inNavbar:!1},We.childContextTypes=Fe;var Ke={tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),disabled:Z.bool,active:Z.bool,className:Z.string,cssModule:Z.object,onClick:Z.func,href:Z.any},Xe=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void('#'===this.props.href&&t.preventDefault(),this.props.onClick&&this.props.onClick(t))}},{key:'render',value:function(){var e=this.props,t=e.className,o=e.cssModule,a=e.active,s=e.tag,n=e.innerRef,l=J(e,['className','cssModule','active','tag','innerRef']),r=y(Q(t,'nav-link',{disabled:l.disabled,active:a}),o);return R.createElement(s,X({},l,{ref:n,onClick:this.onClick,className:r}))}}]),t}(R.Component);Xe.propTypes=Ke,Xe.defaultProps={tag:'a'};var Ve={tag:Z.string,className:Z.string,cssModule:Z.object},Je=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'breadcrumb'),o);return R.createElement(a,X({},s,{className:n}))};Je.propTypes=Ve,Je.defaultProps={tag:'ol'};var Ye={tag:Z.oneOfType([Z.func,Z.string]),active:Z.bool,className:Z.string,cssModule:Z.object},$e=function(e){var t=e.className,o=e.cssModule,a=e.active,s=e.tag,n=J(e,['className','cssModule','active','tag']),l=y(Q(t,!!a&&'active','breadcrumb-item'),o);return R.createElement(s,X({},n,{className:l}))};$e.propTypes=Ye,$e.defaultProps={tag:'li'};var Ze={active:Z.bool,block:Z.bool,color:Z.string,disabled:Z.bool,outline:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),onClick:Z.func,size:Z.string,children:Z.node,className:Z.string,cssModule:Z.object},Qe=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void(this.props.onClick&&this.props.onClick(t))}},{key:'render',value:function(){var e=this.props,t=e.active,o=e.block,a=e.className,s=e.cssModule,n=e.color,l=e.outline,r=e.size,i=e.tag,d=e.innerRef,c=J(e,['active','block','className','cssModule','color','outline','size','tag','innerRef']),p=y(Q(a,'btn','btn'+(l?'-outline':'')+'-'+n,!!r&&'btn-'+r,!!o&&'btn-block',{active:t,disabled:this.props.disabled}),s);return c.href&&'button'===i&&(i='a'),R.createElement(i,X({type:'button'===i&&c.onClick?'button':void 0},c,{className:p,ref:d,onClick:this.onClick}))}}]),t}(R.Component);Qe.propTypes=Ze,Qe.defaultProps={color:'secondary',tag:'button'};var et={children:Z.node},tt=function(e){return R.createElement(We,X({group:!0},e))};tt.propTypes=et;var ot={tag:Z.oneOfType([Z.func,Z.string]),\"aria-label\":Z.string,className:Z.string,cssModule:Z.object,role:Z.string,size:Z.string,vertical:Z.bool},at=function(e){var t=e.className,o=e.cssModule,a=e.size,s=e.vertical,n=e.tag,l=J(e,['className','cssModule','size','vertical','tag']),r=y(Q(t,!!a&&'btn-group-'+a,s?'btn-group-vertical':'btn-group'),o);return R.createElement(n,X({},l,{className:r}))};at.propTypes=ot,at.defaultProps={tag:'div',role:'group'};var st={tag:Z.oneOfType([Z.func,Z.string]),\"aria-label\":Z.string,className:Z.string,cssModule:Z.object,role:Z.string},nt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'btn-toolbar'),o);return R.createElement(a,X({},s,{className:n}))};nt.propTypes=st,nt.defaultProps={tag:'div',role:'toolbar'};var lt={children:Z.node,active:Z.bool,disabled:Z.bool,divider:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),header:Z.bool,onClick:Z.func,className:Z.string,cssModule:Z.object,toggle:Z.bool},rt={toggle:Z.func},it=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o.getTabIndex=o.getTabIndex.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled||this.props.header||this.props.divider?void t.preventDefault():void(this.props.onClick&&this.props.onClick(t),this.props.toggle&&this.context.toggle(t))}},{key:'getTabIndex',value:function(){return this.props.disabled||this.props.header||this.props.divider?'-1':'0'}},{key:'render',value:function(){var e=this.getTabIndex(),t=v(this.props,['toggle']),o=t.className,a=t.cssModule,s=t.divider,n=t.tag,l=t.header,r=t.active,i=J(t,['className','cssModule','divider','tag','header','active']),d=y(Q(o,{disabled:i.disabled,\"dropdown-item\":!s&&!l,active:r,\"dropdown-header\":l,\"dropdown-divider\":s}),a);return'button'===n&&(l?n='h6':s?n='div':i.href&&(n='a')),R.createElement(n,X({type:'button'===n&&(i.onClick||this.props.toggle)?'button':void 0},i,{tabIndex:e,className:d,onClick:this.onClick}))}}]),t}(R.Component);it.propTypes=lt,it.defaultProps={tag:'button',toggle:!0},it.contextTypes=rt;var dt={tag:Z.string,children:Z.node.isRequired,right:Z.bool,flip:Z.bool,className:Z.string,cssModule:Z.object},ct={isOpen:Z.bool.isRequired,direction:Z.oneOf(['up','down','left','right']).isRequired,inNavbar:Z.bool.isRequired},pt={flip:{enabled:!1}},ut={up:'top',left:'left',right:'right',down:'bottom'},gt=function(e,t){var o=e.className,s=e.cssModule,n=e.right,l=e.tag,r=e.flip,i=J(e,['className','cssModule','right','tag','flip']),d=y(Q(o,'dropdown-menu',{\"dropdown-menu-right\":n,show:t.isOpen}),s),c=l;if(t.isOpen&&!t.inNavbar){c=a.Popper;var p=ut[t.direction]||'bottom',u=n?'end':'start';i.placement=p+'-'+u,i.component=l,i.modifiers=r?void 0:pt}return R.createElement(c,X({tabIndex:'-1',role:'menu'},i,{\"aria-hidden\":!t.isOpen,className:d}))};gt.propTypes=dt,gt.defaultProps={tag:'div',flip:!0},gt.contextTypes=ct;var mt={caret:Z.bool,color:Z.string,children:Z.node,className:Z.string,cssModule:Z.object,disabled:Z.bool,onClick:Z.func,\"aria-haspopup\":Z.bool,split:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),nav:Z.bool},bt={isOpen:Z.bool.isRequired,toggle:Z.func.isRequired,inNavbar:Z.bool.isRequired},ft=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void(this.props.nav&&!this.props.tag&&t.preventDefault(),this.props.onClick&&this.props.onClick(t),this.context.toggle(t))}},{key:'render',value:function(){var e,t=this.props,o=t.className,s=t.color,n=t.cssModule,l=t.caret,r=t.split,i=t.nav,d=t.tag,c=J(t,['className','color','cssModule','caret','split','nav','tag']),p=c['aria-label']||'Toggle Dropdown',u=y(Q(o,{\"dropdown-toggle\":l||r,\"dropdown-toggle-split\":r,\"nav-link\":i}),n),g=c.children||R.createElement('span',{className:'sr-only'},p);return i&&!d?(e='a',c.href='#'):d?e=d:(e=Qe,c.color=s,c.cssModule=n),this.context.inNavbar?R.createElement(e,X({},c,{className:u,onClick:this.onClick,\"aria-expanded\":this.context.isOpen,children:g})):R.createElement(a.Target,X({},c,{className:u,component:e,onClick:this.onClick,\"aria-expanded\":this.context.isOpen,children:g}))}}]),t}(R.Component);ft.propTypes=mt,ft.defaultProps={\"aria-haspopup\":!0,color:'secondary'},ft.contextTypes=bt;var yt=X({},s.propTypes,{children:Z.oneOfType([Z.arrayOf(Z.node),Z.node]),tag:Z.oneOfType([Z.string,Z.func]),baseClass:Z.string,baseClassActive:Z.string,className:Z.string,cssModule:Z.object}),vt=X({},s.defaultProps,{tag:'div',baseClass:'fade',baseClassActive:'show',timeout:ue.Fade,appear:!0,enter:!0,exit:!0,in:!0});M.propTypes=yt,M.defaultProps=vt;var ht={color:Z.string,pill:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),children:Z.node,className:Z.string,cssModule:Z.object},Nt=function(e){var t=e.className,o=e.cssModule,a=e.color,s=e.pill,n=e.tag,l=J(e,['className','cssModule','color','pill','tag']),r=y(Q(t,'badge','badge-'+a,!!s&&'badge-pill'),o);return l.href&&'span'===n&&(n='a'),R.createElement(n,X({},l,{className:r}))};Nt.propTypes=ht,Nt.defaultProps={color:'secondary',pill:!1,tag:'span'};var Tt={tag:Z.oneOfType([Z.func,Z.string]),inverse:Z.bool,color:Z.string,block:T(Z.bool,'Please use the props \"body\"'),body:Z.bool,outline:Z.bool,className:Z.string,cssModule:Z.object},kt=function(e){var t=e.className,o=e.cssModule,a=e.color,s=e.block,n=e.body,l=e.inverse,r=e.outline,i=e.tag,d=J(e,['className','cssModule','color','block','body','inverse','outline','tag']),c=y(Q(t,'card',!!l&&'text-white',(s||n)&&'card-body',!!a&&(r?'border':'bg')+'-'+a),o);return R.createElement(i,X({},d,{className:c}))};kt.propTypes=Tt,kt.defaultProps={tag:'div'};var Et={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Mt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-group'),o);return R.createElement(a,X({},s,{className:n}))};Mt.propTypes=Et,Mt.defaultProps={tag:'div'};var Ot={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},xt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-deck'),o);return R.createElement(a,X({},s,{className:n}))};xt.propTypes=Ot,xt.defaultProps={tag:'div'};var Ct={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Pt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-columns'),o);return R.createElement(a,X({},s,{className:n}))};Pt.propTypes=Ct,Pt.defaultProps={tag:'div'};var _t={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},wt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-body'),o);return R.createElement(a,X({},s,{className:n}))};wt.propTypes=_t,wt.defaultProps={tag:'div'};var jt={tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},It=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.innerRef,n=J(e,['className','cssModule','tag','innerRef']),l=y(Q(t,'card-link'),o);return R.createElement(a,X({},n,{ref:s,className:l}))};It.propTypes=jt,It.defaultProps={tag:'a'};var Rt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Dt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-footer'),o);return R.createElement(a,X({},s,{className:n}))};Dt.propTypes=Rt,Dt.defaultProps={tag:'div'};var St={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},At=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-header'),o);return R.createElement(a,X({},s,{className:n}))};At.propTypes=St,At.defaultProps={tag:'div'};var zt={tag:Z.oneOfType([Z.func,Z.string]),top:Z.bool,bottom:Z.bool,className:Z.string,cssModule:Z.object},Lt=function(e){var t=e.className,o=e.cssModule,a=e.top,s=e.bottom,n=e.tag,l=J(e,['className','cssModule','top','bottom','tag']),r='card-img';a&&(r='card-img-top'),s&&(r='card-img-bottom');var i=y(Q(t,r),o);return R.createElement(n,X({},l,{className:i}))};Lt.propTypes=zt,Lt.defaultProps={tag:'img'};var qt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Ht=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-img-overlay'),o);return R.createElement(a,X({},s,{className:n}))};Ht.propTypes=qt,Ht.defaultProps={tag:'div'};var Bt=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={startAnimation:!1},o.onEnter=o.onEnter.bind(o),o.onEntering=o.onEntering.bind(o),o.onExit=o.onExit.bind(o),o.onExiting=o.onExiting.bind(o),o.onExited=o.onExited.bind(o),o}return V(t,e),W(t,[{key:'onEnter',value:function(e,t){this.setState({startAnimation:!1}),this.props.onEnter(e,t)}},{key:'onEntering',value:function(e,t){var o=e.offsetHeight;return this.setState({startAnimation:!0}),this.props.onEntering(e,t),o}},{key:'onExit',value:function(e){this.setState({startAnimation:!1}),this.props.onExit(e)}},{key:'onExiting',value:function(e){this.setState({startAnimation:!0}),e.dispatchEvent(new CustomEvent('slide.bs.carousel')),this.props.onExiting(e)}},{key:'onExited',value:function(e){e.dispatchEvent(new CustomEvent('slid.bs.carousel')),this.props.onExited(e)}},{key:'render',value:function(){var e=this,t=this.props,o=t.in,a=t.children,n=t.cssModule,l=t.slide,r=t.tag,i=t.className,d=J(t,['in','children','cssModule','slide','tag','className']);return R.createElement(s,X({},d,{enter:l,exit:l,in:o,onEnter:this.onEnter,onEntering:this.onEntering,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}),function(t){var o=e.context.direction,s=t===me.ENTERED||t===me.EXITING,l=(t===me.ENTERING||t===me.EXITING)&&e.state.startAnimation&&('right'===o?'carousel-item-left':'carousel-item-right'),d=t===me.ENTERING&&('right'===o?'carousel-item-next':'carousel-item-prev'),c=y(Q(i,'carousel-item',s&&'active',l,d),n);return R.createElement(r,{className:c},a)})}}]),t}(R.Component);Bt.propTypes=X({},s.propTypes,{tag:Z.oneOfType([Z.func,Z.string]),in:Z.bool,cssModule:Z.object,children:Z.node,slide:Z.bool,className:Z.string}),Bt.defaultProps=X({},s.defaultProps,{tag:'div',timeout:ue.Carousel,slide:!0}),Bt.contextTypes={direction:Z.string};var Gt=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.handleKeyPress=o.handleKeyPress.bind(o),o.renderItems=o.renderItems.bind(o),o.hoverStart=o.hoverStart.bind(o),o.hoverEnd=o.hoverEnd.bind(o),o.state={direction:'right',indicatorClicked:!1},o}return V(t,e),W(t,[{key:'getChildContext',value:function(){return{direction:this.state.direction}}},{key:'componentDidMount',value:function(){'carousel'===this.props.ride&&this.setInterval(),document.addEventListener('keyup',this.handleKeyPress)}},{key:'componentWillReceiveProps',value:function(e){this.setInterval(e),this.props.activeIndex+1===e.activeIndex?this.setState({direction:'right'}):this.props.activeIndex-1===e.activeIndex?this.setState({direction:'left'}):this.props.activeIndex>e.activeIndex?this.setState({direction:this.state.indicatorClicked?'left':'right'}):this.props.activeIndex!==e.activeIndex&&this.setState({direction:this.state.indicatorClicked?'right':'left'}),this.setState({indicatorClicked:!1})}},{key:'componentWillUnmount',value:function(){this.clearInterval(),document.removeEventListener('keyup',this.handleKeyPress)}},{key:'setInterval',value:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){var e=0=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc===\"root\"){return handle(\"end\")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,\"catchLoc\");var hasFinally=hasOwn.call(entry,\"finallyLoc\");if(hasCatch&&hasFinally){if(this.prev=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,\"finallyLoc\")&&(entry.finallyLoc===finallyLoc||this.prev=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;var thrown;if(record.type===\"throw\"){thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error(\"illegal catch attempt\")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}).call(this,typeof global!==\"undefined\"?global:typeof self!==\"undefined\"?self:typeof window!==\"undefined\"?window:{})},{}],3:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!==\"undefined\"&&window.setImmediate;var canMutationObserver=typeof window!==\"undefined\"&&window.MutationObserver;var canPost=typeof window!==\"undefined\"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement(\"div\");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute(\"yes\",\"no\")}queue.push(fn)}}if(canPost){window.addEventListener(\"message\",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data===\"process-tick\"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage(\"process-tick\",\"*\")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title=\"browser\";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error(\"process.binding is not supported\")};process.cwd=function(){return\"/\"};process.chdir=function(dir){throw new Error(\"process.chdir is not supported\")}},{}],4:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define===\"function\"&&define.amd){define(factory)}else if(typeof exports===\"object\"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){\"use strict\";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},\"x\",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{\"/a/\".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function(\"return this;\");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!==\"undefined\"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol===\"function\"&&Symbol.iterator||\"_es6shim_iterator_\";if(globals.Set&&typeof(new globals.Set)[\"@@iterator\"]===\"function\"){$iterator$=\"@@iterator\"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$===\"symbol\"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str===\"[object Arguments]\";if(!result){result=str!==\"[object Array]\"&&value!==null&&typeof value===\"object\"&&typeof value.length===\"number\"&&value.length>=0&&_toString.call(value.callee)===\"[object Function]\"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError(\"bad object\")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor[\"@@create\"])){o=o.constructor[\"@@create\"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||\"Cannot call method on \"+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x===\"function\"&&_toString.call(x)===\"[object Function]\"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!==\"undefined\"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,\"value\")}var itFn=o[$iterator$];if(!ES.IsCallable(itFn)){throw new TypeError(\"value is not an iterable\")}var it=itFn.call(o);if(!ES.TypeIsObject(it)){throw new TypeError(\"bad iterator\")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError(\"bad iterator\")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C[\"@@create\"])){obj=C[\"@@create\"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<>1}}bits.reverse();str=bits.join(\"\");bias=(1<0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!==\"undefined\"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i1114111){throw new RangeError(\"Invalid code point \"+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join(\"\")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,\"bad callSite\");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,\"bad raw value\");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return\"\"}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex=literalsegments){break}next=substitutions[nextKey];if(typeof next===\"undefined\"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join(\"\")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,\"fromCodePoint\",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return\"\"}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError(\"Invalid String#repeat value\")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)===\"[object RegExp]\"){throw new TypeError('Cannot call method \"startsWith\" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)===\"[object RegExp]\"){throw new TypeError('Cannot call method \"endsWith\" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg===\"undefined\"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug=\"…\".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[\"\t\\n\u000b\\f\\r   ᠎    \",\"          \\u2028\",\"\\u2029\"].join(\"\");var trimRegexp=new RegExp(\"(^[\"+ws+\"]+)|([\"+ws+\"]+$)\",\"g\");defineProperties(String.prototype,{trim:function(){if(typeof this===\"undefined\"||this===null){throw new TypeError(\"can't convert \"+this+\" to object\")}return String(this).replace(trimRegexp,\"\")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s===\"undefined\"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,\"bad iterable\");if(typeof mapFn!==\"undefined\"&&!ES.IsCallable(mapFn)){throw new TypeError(\"Array.from: when provided, the second argument must be a function\")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start===\"undefined\"?0:start);end=ES.ToInteger(typeof end===\"undefined\"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul\n}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status===\"undefined\"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError(\"bad promise constructor\")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError(\"bad promise constructor\")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError(\"bad promise constructor\")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!==\"undefined\"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName=\"zero-timeout-message\";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,\"*\")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener(\"message\",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process===\"object\"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError(\"self resolution\")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError(\"self resolution\"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError(\"bad promise\")}if(typeof promise._status!==\"undefined\"){throw new TypeError(\"promise already initialized\")}if(!ES.IsCallable(resolver)){throw new TypeError(\"not a valid resolver\")}promise._status=\"unresolved\";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!==\"unresolved\"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status=\"has-resolution\";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!==\"unresolved\"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status=\"has-rejection\";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{\"@@create\":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError(\"bad iterable\")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError(\"bad iterable\")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype[\"catch\"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError(\"not a promise\")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case\"unresolved\":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case\"has-resolution\":triggerPromiseReactions([resolveReaction],promise._result);break;case\"has-rejection\":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError(\"unexpected\")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(\":\")===b.join(\":\")};var preservesInsertionOrder=testOrder([\"z\",\"a\",\"bb\"]);var preservesNumericInsertionOrder=testOrder([\"z\",1,\"a\",\"3\",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type===\"string\"){return\"$\"+key}else if(type===\"number\"){if(!preservesNumericInsertionOrder){return\"n\"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty};function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i===\"undefined\"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind===\"key\"){result=i.key}else if(kind===\"value\"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;if(!ES.TypeIsObject(map)){throw new TypeError(\"Map does not accept arguments when called as a function\")}map=emulateES6construct(map);if(!map._es6map){throw new TypeError(\"bad map\")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!==\"undefined\"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError(\"bad map\")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError(\"expected iterable of pairs\")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{\"@@create\":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,\"size\",{configurable:true,enumerable:false,get:function(){if(typeof this._size===\"undefined\"){throw new TypeError(\"size method called on incompatible Map\")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!==\"undefined\"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!==\"undefined\"){this._storage[fkey].value=value;return this}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return this}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},\"delete\":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]===\"undefined\"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,\"key\")},values:function(){return new MapIterator(this,\"value\")},entries:function(){return new MapIterator(this,\"key+value\")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;if(!ES.TypeIsObject(set)){throw new TypeError(\"Set does not accept arguments when called as a function\")}set=emulateES6construct(set);if(!set._es6set){throw new TypeError(\"bad set\")}defineProperties(set,{\"[[SetData]]\":null,_storage:emptyObject()});if(typeof iterable!==\"undefined\"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError(\"bad set\")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{\"@@create\":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set[\"[[SetData]]\"]){var m=set[\"[[SetData]]\"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)===\"n\"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,\"size\",{configurable:true,enumerable:false,get:function(){if(typeof this._storage===\"undefined\"){throw new TypeError(\"size method called on incompatible Set\")}ensureMap(this);return this[\"[[SetData]]\"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this[\"[[SetData]]\"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return this}ensureMap(this);this[\"[[SetData]]\"].set(key,key);return this},\"delete\":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this[\"[[SetData]]\"][\"delete\"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this[\"[[SetData]]\"].clear()},keys:function(){ensureMap(this);return this[\"[[SetData]]\"].keys()},values:function(){ensureMap(this);return this[\"[[SetData]]\"].values()},entries:function(){ensureMap(this);return this[\"[[SetData]]\"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this[\"[[SetData]]\"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!==\"function\"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!==\"function\"||typeof globals.Set.prototype.keys!==\"function\"||typeof globals.Map.prototype.forEach!==\"function\"||typeof globals.Set.prototype.forEach!==\"function\"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require(\"_process\"))},{_process:3}],5:[function(require,module,exports){\"use strict\";if(!require(\"./is-implemented\")()){Object.defineProperty(require(\"es5-ext/global\"),\"Symbol\",{value:require(\"./polyfill\"),configurable:true,enumerable:false,writable:true})}},{\"./is-implemented\":6,\"./polyfill\":21,\"es5-ext/global\":8}],6:[function(require,module,exports){\"use strict\";module.exports=function(){var symbol;if(typeof Symbol!==\"function\")return false;symbol=Symbol(\"test symbol\");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator===\"symbol\")return true;if(typeof Symbol.isConcatSpreadable!==\"object\")return false;if(typeof Symbol.isRegExp!==\"object\")return false;if(typeof Symbol.iterator!==\"object\")return false;if(typeof Symbol.toPrimitive!==\"object\")return false;if(typeof Symbol.toStringTag!==\"object\")return false;if(typeof Symbol.unscopables!==\"object\")return false;return true}},{}],7:[function(require,module,exports){\"use strict\";var assign=require(\"es5-ext/object/assign\"),normalizeOpts=require(\"es5-ext/object/normalize-options\"),isCallable=require(\"es5-ext/object/is-callable\"),contains=require(\"es5-ext/string/#/contains\"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!==\"string\"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,\"c\");e=contains.call(dscr,\"e\");w=contains.call(dscr,\"w\")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!==\"string\"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,\"c\");e=contains.call(dscr,\"e\")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{\"es5-ext/object/assign\":9,\"es5-ext/object/is-callable\":12,\"es5-ext/object/normalize-options\":16,\"es5-ext/string/#/contains\":18}],8:[function(require,module,exports){\"use strict\";module.exports=new Function(\"return this\")()},{}],9:[function(require,module,exports){\"use strict\";module.exports=require(\"./is-implemented\")()?Object.assign:require(\"./shim\")},{\"./is-implemented\":10,\"./shim\":11}],10:[function(require,module,exports){\"use strict\";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!==\"function\")return false;obj={foo:\"raz\"};assign(obj,{bar:\"dwa\"},{trzy:\"trzy\"});return obj.foo+obj.bar+obj.trzy===\"razdwatrzy\"}},{}],11:[function(require,module,exports){\"use strict\";var keys=require(\"../keys\"),value=require(\"../valid-value\"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i-1}},{}],21:[function(require,module,exports){\"use strict\";var d=require(\"d\"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||\"\")])++postfix;desc+=postfix||\"\";created[desc]=true;return\"@@\"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError(\"TypeError: Symbol is not a constructor\")}symbol=create(Symbol.prototype);description=description===undefined?\"\":String(description);return defineProperties(symbol,{__description__:d(\"\",description),__name__:d(\"\",generateName(description))})};Object.defineProperties(Symbol,{create:d(\"\",Symbol(\"create\")),hasInstance:d(\"\",Symbol(\"hasInstance\")),isConcatSpreadable:d(\"\",Symbol(\"isConcatSpreadable\")),isRegExp:d(\"\",Symbol(\"isRegExp\")),iterator:d(\"\",Symbol(\"iterator\")),toPrimitive:d(\"\",Symbol(\"toPrimitive\")),toStringTag:d(\"\",Symbol(\"toStringTag\")),unscopables:d(\"\",Symbol(\"unscopables\"))});defineProperties(Symbol.prototype,{properToString:d(function(){return\"Symbol (\"+this.__description__+\")\"}),toString:d(\"\",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d(\"\",function(hint){throw new TypeError(\"Conversion of symbol objects is not allowed\")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d(\"c\",\"Symbol\"))},{d:7}]},{},[1]);"}}},{"rowIdx":358,"cells":{"target":{"kind":"string","value":"src/components/editor/editor-edges.js"},"feat_repo_name":{"kind":"string","value":"szymonkaliski/SDF-UI"},"text":{"kind":"string","value":"import React, { Component } from 'react';\nimport autobind from 'react-autobind';\nimport classNames from 'classnames';\nimport enhanceWithClickOutside from 'react-click-outside';\nimport { bindActionCreators } from 'redux';\nimport { connect } from 'react-redux';\n\nimport nodeSpecs from '../../engine/nodes';\n\nimport {\n deleteEdge\n} from '../../actions/graph';\n\nimport './editor-edges.css';\n\nconst prop = (key) => (obj) => obj[key];\n\nclass EditorEdges extends Component {\n constructor() {\n super();\n\n this.state = { selectedId: undefined };\n\n autobind(this);\n }\n\n componentDidMount() {\n window.addEventListener('keydown', this.onKeyDown);\n }\n\n componentWillUnmount() {\n window.removeEventListener('keydown', this.onKeyDown);\n }\n\n onClickEdge(id) {\n this.setState({ selectedId: id });\n }\n\n handleClickOutside() {\n this.setState({ selectedId: undefined });\n }\n\n onKeyDown(e) {\n const { key, target } = e;\n const { selectedId } = this.state;\n\n if (selectedId && key === 'Backspace' && target.localName === 'body') {\n this.props.deleteEdge(selectedId);\n this.setState({ selectedId: undefined });\n }\n }\n\n render() {\n const { selectedId } = this.state;\n const { width, height, edges, nodes } = this.props;\n\n return \n {\n edges.valueSeq().map(edge => {\n const id = edge.get('id');\n\n const fromNode = nodes.get(edge.getIn([ 'from', 'id' ]));\n\n if (!fromNode) { return null; }\n\n const toNode = nodes.get(edge.getIn([ 'to', 'id' ]));\n\n let targetX, targetY;\n\n if (toNode) {\n const toNodeInlets = nodeSpecs[toNode.get('type')].spec.inlets.map(prop('id'));\n const inletIdx = toNodeInlets.indexOf(edge.getIn([ 'to', 'inlet' ]));\n\n targetX = toNode.get('x') + 12 + 34 * inletIdx;\n targetY = toNode.get('y') + 8;\n }\n else if (id === 'dragging') {\n targetX = edge.get('x');\n targetY = edge.get('y');\n }\n\n return this.onClickEdge(id) }\n className={ classNames('edge', { 'edge--selected': selectedId === id }) }\n x1={ fromNode.get('x') + 12 }\n y1={ fromNode.get('y') + 96 }\n x2={ targetX }\n y2={ targetY }\n />\n })\n }\n ;\n }\n}\n\nconst mapDispatchToProps = (dispatch) => bindActionCreators({ deleteEdge }, dispatch);\n\nexport default connect(null, mapDispatchToProps)(enhanceWithClickOutside(EditorEdges));\n"}}},{"rowIdx":359,"cells":{"target":{"kind":"string","value":"src/parser/monk/brewmaster/modules/spells/azeritetraits/TrainingOfNiuzao.js"},"feat_repo_name":{"kind":"string","value":"ronaldpereira/WoWAnalyzer"},"text":{"kind":"string","value":"import React from 'react';\nimport Analyzer from 'parser/core/Analyzer';\n\nimport SPELLS from 'common/SPELLS';\nimport { calculateAzeriteEffects } from 'common/stats';\nimport { formatNumber, formatPercentage } from 'common/format';\nimport TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox';\nimport StatTracker from 'parser/shared/modules/StatTracker';\n\nconst TON_SCALE = {\n [SPELLS.LIGHT_STAGGER_DEBUFF.id]: 1,\n [SPELLS.MODERATE_STAGGER_DEBUFF.id]: 2,\n [SPELLS.HEAVY_STAGGER_DEBUFF.id]: 3,\n};\n\nexport function trainingOfNiuzaoStats(combatant) {\n if(!combatant.hasTrait(SPELLS.TRAINING_OF_NIUZAO.id)) {\n return null;\n }\n return {\n mastery: combatant.traitsBySpellId[SPELLS.TRAINING_OF_NIUZAO.id]\n .reduce((total, rank) => total + calculateAzeriteEffects(SPELLS.TRAINING_OF_NIUZAO.id, rank)[0], 0),\n };\n}\n\nconst NULL_MASTERY = { mastery: 0 };\n\n/**\n * Training of Niuzao\n *\n * Gain up to X mastery based on your level of Stagger.\n *\n * The effect size from scaling code is actually the amount given at\n * *Light* stagger, not the tooltip value.\n *\n * Scaling calculation is disconnected from this class so it can be\n * re-used by the StatTracker.\n *\n * Example Report: https://www.warcraftlogs.com/reports/X4kZzGnym1YMJwPd/#fight=32&source=7\n */\nclass TrainingOfNiuzao extends Analyzer {\n static dependencies = {\n statTracker: StatTracker,\n };\n\n mastery = 0;\n constructor(...args) {\n super(...args);\n if(!this.selectedCombatant.hasTrait(SPELLS.TRAINING_OF_NIUZAO.id)) {\n this.active = false;\n return;\n }\n\n this.mastery = trainingOfNiuzaoStats(this.selectedCombatant).mastery;\n\n this.statTracker.add(SPELLS.LIGHT_STAGGER_DEBUFF.id, {\n mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.LIGHT_STAGGER_DEBUFF.id],\n });\n this.statTracker.add(SPELLS.MODERATE_STAGGER_DEBUFF.id, {\n mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.MODERATE_STAGGER_DEBUFF.id],\n });\n this.statTracker.add(SPELLS.HEAVY_STAGGER_DEBUFF.id, {\n mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.HEAVY_STAGGER_DEBUFF.id],\n });\n }\n\n get avgMastery() {\n return Object.entries(TON_SCALE).reduce((current, [buff, scale]) => this.selectedCombatant.getBuffUptime(buff) / this.owner.fightDuration * scale * this.mastery + current, 0);\n }\n\n statistic() {\n const lightUptime = this.selectedCombatant.getBuffUptime(SPELLS.LIGHT_STAGGER_DEBUFF.id) / this.owner.fightDuration;\n const moderateUptime = this.selectedCombatant.getBuffUptime(SPELLS.MODERATE_STAGGER_DEBUFF.id) / this.owner.fightDuration;\n const heavyUptime = this.selectedCombatant.getBuffUptime(SPELLS.HEAVY_STAGGER_DEBUFF.id) / this.owner.fightDuration;\n\n const lightMastery = TON_SCALE[SPELLS.LIGHT_STAGGER_DEBUFF.id] * this.mastery;\n const moderateMastery = TON_SCALE[SPELLS.MODERATE_STAGGER_DEBUFF.id] * this.mastery;\n const heavyMastery = TON_SCALE[SPELLS.HEAVY_STAGGER_DEBUFF.id] * this.mastery;\n\n // the `this.owner.getModule(StatTracker)` bit is used because atm\n // StatTracker ALSO imports this module so that the mastery\n // calculation isn't done inline over there. it is possible to\n // import StatTracker, but not to set it as a dependency.\n return (\n \n Contribution Breakdown:\n
    \n
  • No Stagger: {formatPercentage(1 - lightUptime - moderateUptime - heavyUptime)}% of the fight.
  • \n
  • Light Stagger: {formatPercentage(lightUptime)}% of the fight at {formatNumber(lightMastery)} Mastery.
  • \n
  • Moderate Stagger: {formatPercentage(moderateUptime)}% of the fight at {formatNumber(moderateMastery)} Mastery.
  • \n
  • Heavy Stagger: {formatPercentage(heavyUptime)}% of the fight at {formatNumber(heavyMastery)} Mastery.
  • \n
\n \n )}\n />\n );\n }\n\n statisticOrder = STATISTIC_ORDER.OPTIONAL();\n}\n\nexport default TrainingOfNiuzao;\n"}}},{"rowIdx":360,"cells":{"target":{"kind":"string","value":"src/pages/maker-party/activities/mixin.js"},"feat_repo_name":{"kind":"string","value":"mozilla/advocacy.mozilla.org"},"text":{"kind":"string","value":"import React from 'react'\n\nmodule.exports = {\n componentDidMount: function() {\n var navTop, navEl, windowHeight, navHeight;\n\n navEl = document.querySelector(\".agenda-navigation\");\n var navOffset = navEl.getBoundingClientRect();\n navTop = navOffset.top;\n navigate(window.location.hash);\n\n function hide(el) {\n el.style.display = \"none\";\n }\n\n function show(el) {\n el.style.display = \"block\";\n }\n\n function forEachList(list, callback) {\n Array.prototype.forEach.call(list, callback);\n }\n\n function applyAll(list, event, callback) {\n forEachList(list, function(item) {\n item.addEventListener(event, callback);\n });\n }\n\n applyAll(navEl.querySelectorAll('a'), \"click\", function(e) {\n e.preventDefault();\n navigate(this.getAttribute(\"href\"));\n });\n\n function navigate(hash) {\n if (!hash) {\n return;\n }\n // First, we'll hide all of the content\n forEachList(document.querySelectorAll(\".agenda > li\"), function(item) {\n hide(item);\n });\n\n hide(document.querySelector(\"section.overview\"));\n\n // Next, we'll try to figure out what step to show based on the hash.\n hash = hash.toLowerCase();\n var numberOfSteps = document.querySelectorAll(\".agenda > li\").length;\n var overview = true;\n if(hash.indexOf(\"step\") > 0) {\n var step = hash.replace(\"#step-\",\"\");\n if(step <= numberOfSteps){\n overview = false;\n }\n }\n\n // If there's a step number in the hash, we'll show that step.\n // Otherwise, we'll default to the overview.\n if(overview) {\n hash = \"#overview\";\n show(document.querySelector(\"section.overview\"));\n document.querySelector(\".wrapper\").setAttribute(\"mode\",\"overview\");\n } else {\n show(document.querySelector(\".agenda > li:nth-child(\"+step+\")\"));\n document.querySelector(\".wrapper\").setAttribute(\"mode\",\"step\");\n }\n\n // Here we add the selected class to the activity navigation link.\n var selected = navEl.querySelector(\".selected\");\n if (selected) {\n selected.classList.remove(\"selected\");\n }\n navEl.querySelector(\"a[href='\"+hash+\"']\").parentNode.classList.add(\"selected\");\n\n window.location.hash = hash;\n }\n }\n};\n\n"}}},{"rowIdx":361,"cells":{"target":{"kind":"string","value":"ajax/libs/rxjs/2.3.7/rx.all.js"},"feat_repo_name":{"kind":"string","value":"mikelambert/cdnjs"},"text":{"kind":"string","value":"// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.\r\n\r\n;(function (undefined) {\r\n\r\n var objectTypes = {\r\n 'boolean': false,\r\n 'function': true,\r\n 'object': true,\r\n 'number': false,\r\n 'string': false,\r\n 'undefined': false\r\n };\r\n\r\n var root = (objectTypes[typeof window] && window) || this,\r\n freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,\r\n freeModule = objectTypes[typeof module] && module && !module.nodeType && module,\r\n moduleExports = freeModule && freeModule.exports === freeExports && freeExports,\r\n freeGlobal = objectTypes[typeof global] && global;\r\n \r\n if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {\r\n root = freeGlobal;\r\n }\r\n\r\n var Rx = { \r\n internals: {}, \r\n config: {\r\n Promise: root.Promise // Detect if promise exists\r\n },\r\n helpers: { }\r\n };\r\n \r\n // Defaults\r\n var noop = Rx.helpers.noop = function () { },\r\n notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, \r\n isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, \r\n identity = Rx.helpers.identity = function (x) { return x; },\r\n pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },\r\n just = Rx.helpers.just = function (value) { return function () { return value; }; }, \r\n defaultNow = Rx.helpers.defaultNow = Date.now,\r\n defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },\r\n defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },\r\n defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },\r\n defaultError = Rx.helpers.defaultError = function (err) { throw err; },\r\n isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },\r\n asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },\r\n not = Rx.helpers.not = function (a) { return !a; };\r\n\r\n // Errors\r\n var sequenceContainsNoElements = 'Sequence contains no elements.';\r\n var argumentOutOfRange = 'Argument out of range';\r\n var objectDisposed = 'Object has been disposed';\r\n function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } \r\n \r\n // Shim in iterator support\r\n var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||\r\n '_es6shim_iterator_';\r\n // Bug for mozilla version\r\n if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {\r\n $iterator$ = '@@iterator';\r\n }\r\n \r\n var doneEnumerator = { done: true, value: undefined };\r\n\r\n /** `Object#toString` result shortcuts */\r\n var argsClass = '[object Arguments]',\r\n arrayClass = '[object Array]',\r\n boolClass = '[object Boolean]',\r\n dateClass = '[object Date]',\r\n errorClass = '[object Error]',\r\n funcClass = '[object Function]',\r\n numberClass = '[object Number]',\r\n objectClass = '[object Object]',\r\n regexpClass = '[object RegExp]',\r\n stringClass = '[object String]';\r\n\r\n var toString = Object.prototype.toString,\r\n hasOwnProperty = Object.prototype.hasOwnProperty, \r\n supportsArgsClass = toString.call(arguments) == argsClass, // For less -1);\r\n }\r\n });\r\n }\r\n }\r\n stackA.pop();\r\n stackB.pop();\r\n\r\n return result;\r\n }\r\n var slice = Array.prototype.slice;\r\n function argsOrArray(args, idx) {\r\n return args.length === 1 && Array.isArray(args[idx]) ?\r\n args[idx] :\r\n slice.call(args);\r\n }\r\n var hasProp = {}.hasOwnProperty;\r\n\r\n /** @private */\r\n var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {\r\n function __() { this.constructor = child; }\r\n __.prototype = parent.prototype;\r\n child.prototype = new __();\r\n };\r\n\r\n /** @private */ \r\n var addProperties = Rx.internals.addProperties = function (obj) {\r\n var sources = slice.call(arguments, 1);\r\n for (var i = 0, len = sources.length; i < len; i++) {\r\n var source = sources[i];\r\n for (var prop in source) {\r\n obj[prop] = source[prop];\r\n }\r\n }\r\n };\r\n\r\n // Rx Utils\r\n var addRef = Rx.internals.addRef = function (xs, r) {\r\n return new AnonymousObservable(function (observer) {\r\n return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));\r\n });\r\n };\r\n\r\n // Collection polyfills\r\n function arrayInitialize(count, factory) {\r\n var a = new Array(count);\r\n for (var i = 0; i < count; i++) {\r\n a[i] = factory();\r\n }\r\n return a;\r\n }\r\n\r\n // Collections\r\n var IndexedItem = function (id, value) {\r\n this.id = id;\r\n this.value = value;\r\n };\r\n\r\n IndexedItem.prototype.compareTo = function (other) {\r\n var c = this.value.compareTo(other.value);\r\n if (c === 0) {\r\n c = this.id - other.id;\r\n }\r\n return c;\r\n };\r\n\r\n // Priority Queue for Scheduling\r\n var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {\r\n this.items = new Array(capacity);\r\n this.length = 0;\r\n };\r\n\r\n var priorityProto = PriorityQueue.prototype;\r\n priorityProto.isHigherPriority = function (left, right) {\r\n return this.items[left].compareTo(this.items[right]) < 0;\r\n };\r\n\r\n priorityProto.percolate = function (index) {\r\n if (index >= this.length || index < 0) {\r\n return;\r\n }\r\n var parent = index - 1 >> 1;\r\n if (parent < 0 || parent === index) {\r\n return;\r\n }\r\n if (this.isHigherPriority(index, parent)) {\r\n var temp = this.items[index];\r\n this.items[index] = this.items[parent];\r\n this.items[parent] = temp;\r\n this.percolate(parent);\r\n }\r\n };\r\n\r\n priorityProto.heapify = function (index) {\r\n if (index === undefined) {\r\n index = 0;\r\n }\r\n if (index >= this.length || index < 0) {\r\n return;\r\n }\r\n var left = 2 * index + 1,\r\n right = 2 * index + 2,\r\n first = index;\r\n if (left < this.length && this.isHigherPriority(left, first)) {\r\n first = left;\r\n }\r\n if (right < this.length && this.isHigherPriority(right, first)) {\r\n first = right;\r\n }\r\n if (first !== index) {\r\n var temp = this.items[index];\r\n this.items[index] = this.items[first];\r\n this.items[first] = temp;\r\n this.heapify(first);\r\n }\r\n };\r\n \r\n priorityProto.peek = function () { return this.items[0].value; };\r\n\r\n priorityProto.removeAt = function (index) {\r\n this.items[index] = this.items[--this.length];\r\n delete this.items[this.length];\r\n this.heapify();\r\n };\r\n\r\n priorityProto.dequeue = function () {\r\n var result = this.peek();\r\n this.removeAt(0);\r\n return result;\r\n };\r\n\r\n priorityProto.enqueue = function (item) {\r\n var index = this.length++;\r\n this.items[index] = new IndexedItem(PriorityQueue.count++, item);\r\n this.percolate(index);\r\n };\r\n\r\n priorityProto.remove = function (item) {\r\n for (var i = 0; i < this.length; i++) {\r\n if (this.items[i].value === item) {\r\n this.removeAt(i);\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n PriorityQueue.count = 0;\r\n /**\r\n * Represents a group of disposable resources that are disposed together.\r\n * @constructor\r\n */\r\n var CompositeDisposable = Rx.CompositeDisposable = function () {\r\n this.disposables = argsOrArray(arguments, 0);\r\n this.isDisposed = false;\r\n this.length = this.disposables.length;\r\n };\r\n\r\n var CompositeDisposablePrototype = CompositeDisposable.prototype;\r\n\r\n /**\r\n * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.\r\n * @param {Mixed} item Disposable to add.\r\n */ \r\n CompositeDisposablePrototype.add = function (item) {\r\n if (this.isDisposed) {\r\n item.dispose();\r\n } else {\r\n this.disposables.push(item);\r\n this.length++;\r\n }\r\n };\r\n\r\n /**\r\n * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.\r\n * @param {Mixed} item Disposable to remove.\r\n * @returns {Boolean} true if found; false otherwise.\r\n */\r\n CompositeDisposablePrototype.remove = function (item) {\r\n var shouldDispose = false;\r\n if (!this.isDisposed) {\r\n var idx = this.disposables.indexOf(item);\r\n if (idx !== -1) {\r\n shouldDispose = true;\r\n this.disposables.splice(idx, 1);\r\n this.length--;\r\n item.dispose();\r\n }\r\n\r\n }\r\n return shouldDispose;\r\n };\r\n\r\n /**\r\n * Disposes all disposables in the group and removes them from the group. \r\n */\r\n CompositeDisposablePrototype.dispose = function () {\r\n if (!this.isDisposed) {\r\n this.isDisposed = true;\r\n var currentDisposables = this.disposables.slice(0);\r\n this.disposables = [];\r\n this.length = 0;\r\n\r\n for (var i = 0, len = currentDisposables.length; i < len; i++) {\r\n currentDisposables[i].dispose();\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.\r\n */ \r\n CompositeDisposablePrototype.clear = function () {\r\n var currentDisposables = this.disposables.slice(0);\r\n this.disposables = [];\r\n this.length = 0;\r\n for (var i = 0, len = currentDisposables.length; i < len; i++) {\r\n currentDisposables[i].dispose();\r\n }\r\n };\r\n\r\n /**\r\n * Determines whether the CompositeDisposable contains a specific disposable. \r\n * @param {Mixed} item Disposable to search for.\r\n * @returns {Boolean} true if the disposable was found; otherwise, false.\r\n */ \r\n CompositeDisposablePrototype.contains = function (item) {\r\n return this.disposables.indexOf(item) !== -1;\r\n };\r\n\r\n /**\r\n * Converts the existing CompositeDisposable to an array of disposables\r\n * @returns {Array} An array of disposable objects.\r\n */ \r\n CompositeDisposablePrototype.toArray = function () {\r\n return this.disposables.slice(0);\r\n };\r\n \r\n /**\r\n * Provides a set of static methods for creating Disposables.\r\n *\r\n * @constructor \r\n * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.\r\n */\r\n var Disposable = Rx.Disposable = function (action) {\r\n this.isDisposed = false;\r\n this.action = action || noop;\r\n };\r\n\r\n /** Performs the task of cleaning up resources. */ \r\n Disposable.prototype.dispose = function () {\r\n if (!this.isDisposed) {\r\n this.action();\r\n this.isDisposed = true;\r\n }\r\n };\r\n\r\n /**\r\n * Creates a disposable object that invokes the specified action when disposed.\r\n * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.\r\n * @return {Disposable} The disposable object that runs the given action upon disposal.\r\n */\r\n var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };\r\n\r\n /** \r\n * Gets the disposable that does nothing when disposed. \r\n */\r\n var disposableEmpty = Disposable.empty = { dispose: noop };\r\n\r\n var BooleanDisposable = (function () {\r\n function BooleanDisposable (isSingle) {\r\n this.isSingle = isSingle;\r\n this.isDisposed = false;\r\n this.current = null;\r\n }\r\n\r\n var booleanDisposablePrototype = BooleanDisposable.prototype;\r\n\r\n /**\r\n * Gets the underlying disposable.\r\n * @return The underlying disposable.\r\n */\r\n booleanDisposablePrototype.getDisposable = function () {\r\n return this.current;\r\n };\r\n\r\n /**\r\n * Sets the underlying disposable.\r\n * @param {Disposable} value The new underlying disposable.\r\n */ \r\n booleanDisposablePrototype.setDisposable = function (value) {\r\n if (this.current && this.isSingle) {\r\n throw new Error('Disposable has already been assigned');\r\n }\r\n\r\n var shouldDispose = this.isDisposed, old;\r\n if (!shouldDispose) {\r\n old = this.current;\r\n this.current = value;\r\n }\r\n old && old.dispose();\r\n shouldDispose && value && value.dispose();\r\n };\r\n\r\n /** \r\n * Disposes the underlying disposable as well as all future replacements.\r\n */\r\n booleanDisposablePrototype.dispose = function () {\r\n var old;\r\n if (!this.isDisposed) {\r\n this.isDisposed = true;\r\n old = this.current;\r\n this.current = null;\r\n }\r\n old && old.dispose();\r\n };\r\n\r\n return BooleanDisposable;\r\n }());\r\n\r\n /**\r\n * Represents a disposable resource which only allows a single assignment of its underlying disposable resource.\r\n * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.\r\n */\r\n var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {\r\n inherits(SingleAssignmentDisposable, super_);\r\n\r\n function SingleAssignmentDisposable() {\r\n super_.call(this, true);\r\n }\r\n\r\n return SingleAssignmentDisposable;\r\n }(BooleanDisposable));\r\n\r\n /**\r\n * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.\r\n */\r\n var SerialDisposable = Rx.SerialDisposable = (function (super_) {\r\n inherits(SerialDisposable, super_);\r\n\r\n function SerialDisposable() {\r\n super_.call(this, false);\r\n }\r\n\r\n return SerialDisposable;\r\n }(BooleanDisposable));\r\n\r\n /**\r\n * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.\r\n */ \r\n var RefCountDisposable = Rx.RefCountDisposable = (function () {\r\n\r\n function InnerDisposable(disposable) {\r\n this.disposable = disposable;\r\n this.disposable.count++;\r\n this.isInnerDisposed = false;\r\n }\r\n\r\n InnerDisposable.prototype.dispose = function () {\r\n if (!this.disposable.isDisposed) {\r\n if (!this.isInnerDisposed) {\r\n this.isInnerDisposed = true;\r\n this.disposable.count--;\r\n if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {\r\n this.disposable.isDisposed = true;\r\n this.disposable.underlyingDisposable.dispose();\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Initializes a new instance of the RefCountDisposable with the specified disposable.\r\n * @constructor\r\n * @param {Disposable} disposable Underlying disposable.\r\n */\r\n function RefCountDisposable(disposable) {\r\n this.underlyingDisposable = disposable;\r\n this.isDisposed = false;\r\n this.isPrimaryDisposed = false;\r\n this.count = 0;\r\n }\r\n\r\n /** \r\n * Disposes the underlying disposable only when all dependent disposables have been disposed \r\n */\r\n RefCountDisposable.prototype.dispose = function () {\r\n if (!this.isDisposed) {\r\n if (!this.isPrimaryDisposed) {\r\n this.isPrimaryDisposed = true;\r\n if (this.count === 0) {\r\n this.isDisposed = true;\r\n this.underlyingDisposable.dispose();\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. \r\n * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.\r\n */ \r\n RefCountDisposable.prototype.getDisposable = function () {\r\n return this.isDisposed ? disposableEmpty : new InnerDisposable(this);\r\n };\r\n\r\n return RefCountDisposable;\r\n })();\r\n\r\n function ScheduledDisposable(scheduler, disposable) {\r\n this.scheduler = scheduler;\r\n this.disposable = disposable;\r\n this.isDisposed = false;\r\n }\r\n\r\n ScheduledDisposable.prototype.dispose = function () {\r\n var parent = this;\r\n this.scheduler.schedule(function () {\r\n if (!parent.isDisposed) {\r\n parent.isDisposed = true;\r\n parent.disposable.dispose();\r\n }\r\n });\r\n };\r\n\r\n var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {\r\n this.scheduler = scheduler;\r\n this.state = state;\r\n this.action = action;\r\n this.dueTime = dueTime;\r\n this.comparer = comparer || defaultSubComparer;\r\n this.disposable = new SingleAssignmentDisposable();\r\n }\r\n\r\n ScheduledItem.prototype.invoke = function () {\r\n this.disposable.setDisposable(this.invokeCore());\r\n };\r\n\r\n ScheduledItem.prototype.compareTo = function (other) {\r\n return this.comparer(this.dueTime, other.dueTime);\r\n };\r\n\r\n ScheduledItem.prototype.isCancelled = function () {\r\n return this.disposable.isDisposed;\r\n };\r\n\r\n ScheduledItem.prototype.invokeCore = function () {\r\n return this.action(this.scheduler, this.state);\r\n };\r\n\r\n /** Provides a set of static properties to access commonly used schedulers. */\r\n var Scheduler = Rx.Scheduler = (function () {\r\n\r\n function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {\r\n this.now = now;\r\n this._schedule = schedule;\r\n this._scheduleRelative = scheduleRelative;\r\n this._scheduleAbsolute = scheduleAbsolute;\r\n }\r\n\r\n function invokeRecImmediate(scheduler, pair) {\r\n var state = pair.first, action = pair.second, group = new CompositeDisposable(),\r\n recursiveAction = function (state1) {\r\n action(state1, function (state2) {\r\n var isAdded = false, isDone = false,\r\n d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {\r\n if (isAdded) {\r\n group.remove(d);\r\n } else {\r\n isDone = true;\r\n }\r\n recursiveAction(state3);\r\n return disposableEmpty;\r\n });\r\n if (!isDone) {\r\n group.add(d);\r\n isAdded = true;\r\n }\r\n });\r\n };\r\n recursiveAction(state);\r\n return group;\r\n }\r\n\r\n function invokeRecDate(scheduler, pair, method) {\r\n var state = pair.first, action = pair.second, group = new CompositeDisposable(),\r\n recursiveAction = function (state1) {\r\n action(state1, function (state2, dueTime1) {\r\n var isAdded = false, isDone = false,\r\n d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {\r\n if (isAdded) {\r\n group.remove(d);\r\n } else {\r\n isDone = true;\r\n }\r\n recursiveAction(state3);\r\n return disposableEmpty;\r\n });\r\n if (!isDone) {\r\n group.add(d);\r\n isAdded = true;\r\n }\r\n });\r\n };\r\n recursiveAction(state);\r\n return group;\r\n }\r\n\r\n function invokeAction(scheduler, action) {\r\n action();\r\n return disposableEmpty;\r\n }\r\n\r\n var schedulerProto = Scheduler.prototype;\r\n\r\n /**\r\n * Schedules an action to be executed. \r\n * @param {Function} action Action to execute.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.schedule = function (action) {\r\n return this._schedule(action, invokeAction);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed. \r\n * @param state State passed to the action to be executed.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleWithState = function (state, action) {\r\n return this._schedule(state, action);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed after the specified relative due time. \r\n * @param {Function} action Action to execute.\r\n * @param {Number} dueTime Relative time after which to execute the action.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleWithRelative = function (dueTime, action) {\r\n return this._scheduleRelative(action, dueTime, invokeAction);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed after dueTime. \r\n * @param state State passed to the action to be executed.\r\n * @param {Function} action Action to be executed.\r\n * @param {Number} dueTime Relative time after which to execute the action.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {\r\n return this._scheduleRelative(state, dueTime, action);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed at the specified absolute due time. \r\n * @param {Function} action Action to execute.\r\n * @param {Number} dueTime Absolute time at which to execute the action.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleWithAbsolute = function (dueTime, action) {\r\n return this._scheduleAbsolute(action, dueTime, invokeAction);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed at dueTime. \r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Function} action Action to be executed.\r\n * @param {Number}dueTime Absolute time at which to execute the action.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {\r\n return this._scheduleAbsolute(state, dueTime, action);\r\n };\r\n\r\n /** Gets the current time according to the local machine's system clock. */\r\n Scheduler.now = defaultNow;\r\n\r\n /**\r\n * Normalizes the specified TimeSpan value to a positive value.\r\n * @param {Number} timeSpan The time span value to normalize.\r\n * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0\r\n */ \r\n Scheduler.normalize = function (timeSpan) {\r\n timeSpan < 0 && (timeSpan = 0);\r\n return timeSpan;\r\n };\r\n\r\n return Scheduler;\r\n }());\r\n\r\n var normalizeTime = Scheduler.normalize;\r\n \r\n (function (schedulerProto) {\r\n function invokeRecImmediate(scheduler, pair) {\r\n var state = pair.first, action = pair.second, group = new CompositeDisposable(),\r\n recursiveAction = function (state1) {\r\n action(state1, function (state2) {\r\n var isAdded = false, isDone = false,\r\n d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {\r\n if (isAdded) {\r\n group.remove(d);\r\n } else {\r\n isDone = true;\r\n }\r\n recursiveAction(state3);\r\n return disposableEmpty;\r\n });\r\n if (!isDone) {\r\n group.add(d);\r\n isAdded = true;\r\n }\r\n });\r\n };\r\n recursiveAction(state);\r\n return group;\r\n }\r\n\r\n function invokeRecDate(scheduler, pair, method) {\r\n var state = pair.first, action = pair.second, group = new CompositeDisposable(),\r\n recursiveAction = function (state1) {\r\n action(state1, function (state2, dueTime1) {\r\n var isAdded = false, isDone = false,\r\n d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {\r\n if (isAdded) {\r\n group.remove(d);\r\n } else {\r\n isDone = true;\r\n }\r\n recursiveAction(state3);\r\n return disposableEmpty;\r\n });\r\n if (!isDone) {\r\n group.add(d);\r\n isAdded = true;\r\n }\r\n });\r\n };\r\n recursiveAction(state);\r\n return group;\r\n }\r\n\r\n function scheduleInnerRecursive(action, self) {\r\n action(function(dt) { self(action, dt); });\r\n }\r\n\r\n /**\r\n * Schedules an action to be executed recursively.\r\n * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursive = function (action) {\r\n return this.scheduleRecursiveWithState(action, function (_action, self) {\r\n _action(function () { self(_action); }); });\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed recursively. \r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursiveWithState = function (state, action) {\r\n return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed recursively after a specified relative due time. \r\n * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.\r\n * @param {Number}dueTime Relative time after which to execute the action for the first time.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {\r\n return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed recursively after a specified relative due time. \r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.\r\n * @param {Number}dueTime Relative time after which to execute the action for the first time.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {\r\n return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {\r\n return invokeRecDate(s, p, 'scheduleWithRelativeAndState');\r\n });\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed recursively at a specified absolute due time. \r\n * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.\r\n * @param {Number}dueTime Absolute time at which to execute the action for the first time.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {\r\n return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed recursively at a specified absolute due time. \r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.\r\n * @param {Number}dueTime Absolute time at which to execute the action for the first time.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {\r\n return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {\r\n return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');\r\n });\r\n }; \r\n }(Scheduler.prototype));\r\n\r\n (function (schedulerProto) {\r\n /**\r\n * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. \r\n * @param {Number} period Period for running the work periodically.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).\r\n */ \r\n Scheduler.prototype.schedulePeriodic = function (period, action) {\r\n return this.schedulePeriodicWithState(null, period, action);\r\n };\r\n\r\n /**\r\n * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. \r\n * @param {Mixed} state Initial state passed to the action upon the first iteration.\r\n * @param {Number} period Period for running the work periodically.\r\n * @param {Function} action Action to be executed, potentially updating the state.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).\r\n */\r\n Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) {\r\n var s = state;\r\n \r\n var id = setInterval(function () {\r\n s = action(s);\r\n }, period);\r\n\r\n return disposableCreate(function () {\r\n clearInterval(id);\r\n });\r\n };\r\n }(Scheduler.prototype));\r\n \r\n (function (schedulerProto) {\r\n /**\r\n * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. \r\n * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.\r\n * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.\r\n */ \r\n schedulerProto.catchError = schedulerProto['catch'] = function (handler) {\r\n return new CatchScheduler(this, handler);\r\n };\r\n }(Scheduler.prototype)); \r\n\r\n var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {\r\n function tick(command, recurse) {\r\n recurse(0, this._period);\r\n try {\r\n this._state = this._action(this._state);\r\n } catch (e) {\r\n this._cancel.dispose();\r\n throw e;\r\n }\r\n }\r\n\r\n function SchedulePeriodicRecursive(scheduler, state, period, action) {\r\n this._scheduler = scheduler;\r\n this._state = state;\r\n this._period = period;\r\n this._action = action;\r\n }\r\n\r\n SchedulePeriodicRecursive.prototype.start = function () {\r\n var d = new SingleAssignmentDisposable();\r\n this._cancel = d;\r\n d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));\r\n\r\n return d;\r\n };\r\n\r\n return SchedulePeriodicRecursive;\r\n }());\r\n\r\n /**\r\n * Gets a scheduler that schedules work immediately on the current thread.\r\n */ \r\n var immediateScheduler = Scheduler.immediate = (function () {\r\n\r\n function scheduleNow(state, action) { return action(this, state); }\r\n\r\n function scheduleRelative(state, dueTime, action) {\r\n var dt = normalizeTime(dt);\r\n while (dt - this.now() > 0) { }\r\n return action(this, state);\r\n }\r\n\r\n function scheduleAbsolute(state, dueTime, action) {\r\n return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);\r\n }\r\n\r\n return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);\r\n }());\r\n\r\n /** \r\n * Gets a scheduler that schedules work as soon as possible on the current thread.\r\n */\r\n var currentThreadScheduler = Scheduler.currentThread = (function () {\r\n var queue;\r\n\r\n function runTrampoline (q) {\r\n var item;\r\n while (q.length > 0) {\r\n item = q.dequeue();\r\n if (!item.isCancelled()) {\r\n // Note, do not schedule blocking work!\r\n while (item.dueTime - Scheduler.now() > 0) {\r\n }\r\n if (!item.isCancelled()) {\r\n item.invoke();\r\n }\r\n }\r\n }\r\n }\r\n\r\n function scheduleNow(state, action) {\r\n return this.scheduleWithRelativeAndState(state, 0, action);\r\n }\r\n\r\n function scheduleRelative(state, dueTime, action) {\r\n var dt = this.now() + Scheduler.normalize(dueTime),\r\n si = new ScheduledItem(this, state, action, dt);\r\n\r\n if (!queue) {\r\n queue = new PriorityQueue(4);\r\n queue.enqueue(si);\r\n try {\r\n runTrampoline(queue);\r\n } catch (e) { \r\n throw e;\r\n } finally {\r\n queue = null;\r\n }\r\n } else {\r\n queue.enqueue(si);\r\n }\r\n return si.disposable;\r\n }\r\n\r\n function scheduleAbsolute(state, dueTime, action) {\r\n return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);\r\n }\r\n\r\n var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);\r\n \r\n currentScheduler.scheduleRequired = function () { return !queue; };\r\n currentScheduler.ensureTrampoline = function (action) {\r\n if (!queue) { this.schedule(action); } else { action(); }\r\n };\r\n\r\n return currentScheduler;\r\n }());\r\n\r\n \r\n var scheduleMethod, clearMethod = noop;\r\n (function () {\r\n\r\n var reNative = RegExp('^' +\r\n String(toString)\r\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\r\n .replace(/toString| for [^\\]]+/g, '.*?') + '$'\r\n );\r\n\r\n var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&\r\n !reNative.test(setImmediate) && setImmediate,\r\n clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&\r\n !reNative.test(clearImmediate) && clearImmediate;\r\n\r\n function postMessageSupported () {\r\n // Ensure not in a worker\r\n if (!root.postMessage || root.importScripts) { return false; }\r\n var isAsync = false, \r\n oldHandler = root.onmessage;\r\n // Test for async\r\n root.onmessage = function () { isAsync = true; };\r\n root.postMessage('','*');\r\n root.onmessage = oldHandler;\r\n\r\n return isAsync;\r\n }\r\n\r\n // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout\r\n if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {\r\n scheduleMethod = process.nextTick;\r\n } else if (typeof setImmediate === 'function') {\r\n scheduleMethod = setImmediate;\r\n clearMethod = clearImmediate;\r\n } else if (postMessageSupported()) {\r\n var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),\r\n tasks = {},\r\n taskId = 0;\r\n\r\n function onGlobalPostMessage(event) {\r\n // Only if we're a match to avoid any other global events\r\n if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {\r\n var handleId = event.data.substring(MSG_PREFIX.length),\r\n action = tasks[handleId];\r\n action();\r\n delete tasks[handleId];\r\n }\r\n }\r\n\r\n if (root.addEventListener) {\r\n root.addEventListener('message', onGlobalPostMessage, false);\r\n } else {\r\n root.attachEvent('onmessage', onGlobalPostMessage, false);\r\n }\r\n\r\n scheduleMethod = function (action) {\r\n var currentId = taskId++;\r\n tasks[currentId] = action;\r\n root.postMessage(MSG_PREFIX + currentId, '*');\r\n };\r\n } else if (!!root.MessageChannel) {\r\n var channel = new root.MessageChannel(),\r\n channelTasks = {},\r\n channelTaskId = 0;\r\n\r\n channel.port1.onmessage = function (event) {\r\n var id = event.data,\r\n action = channelTasks[id];\r\n action();\r\n delete channelTasks[id];\r\n };\r\n\r\n scheduleMethod = function (action) {\r\n var id = channelTaskId++;\r\n channelTasks[id] = action;\r\n channel.port2.postMessage(id); \r\n };\r\n } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {\r\n \r\n scheduleMethod = function (action) {\r\n var scriptElement = root.document.createElement('script');\r\n scriptElement.onreadystatechange = function () { \r\n action();\r\n scriptElement.onreadystatechange = null;\r\n scriptElement.parentNode.removeChild(scriptElement);\r\n scriptElement = null; \r\n };\r\n root.document.documentElement.appendChild(scriptElement); \r\n };\r\n\r\n } else {\r\n scheduleMethod = function (action) { return setTimeout(action, 0); };\r\n clearMethod = clearTimeout;\r\n }\r\n }());\r\n\r\n /** \r\n * Gets a scheduler that schedules work via a timed callback based upon platform.\r\n */\r\n var timeoutScheduler = Scheduler.timeout = (function () {\r\n\r\n function scheduleNow(state, action) {\r\n var scheduler = this,\r\n disposable = new SingleAssignmentDisposable();\r\n var id = scheduleMethod(function () {\r\n if (!disposable.isDisposed) {\r\n disposable.setDisposable(action(scheduler, state));\r\n }\r\n });\r\n return new CompositeDisposable(disposable, disposableCreate(function () {\r\n clearMethod(id);\r\n }));\r\n }\r\n\r\n function scheduleRelative(state, dueTime, action) {\r\n var scheduler = this,\r\n dt = Scheduler.normalize(dueTime);\r\n if (dt === 0) {\r\n return scheduler.scheduleWithState(state, action);\r\n }\r\n var disposable = new SingleAssignmentDisposable();\r\n var id = setTimeout(function () {\r\n if (!disposable.isDisposed) {\r\n disposable.setDisposable(action(scheduler, state));\r\n }\r\n }, dt);\r\n return new CompositeDisposable(disposable, disposableCreate(function () {\r\n clearTimeout(id);\r\n }));\r\n }\r\n\r\n function scheduleAbsolute(state, dueTime, action) {\r\n return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);\r\n }\r\n\r\n return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);\r\n })();\r\n\r\n /** @private */\r\n var CatchScheduler = (function (_super) {\r\n\r\n function localNow() {\r\n return this._scheduler.now();\r\n }\r\n\r\n function scheduleNow(state, action) {\r\n return this._scheduler.scheduleWithState(state, this._wrap(action));\r\n }\r\n\r\n function scheduleRelative(state, dueTime, action) {\r\n return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));\r\n }\r\n\r\n function scheduleAbsolute(state, dueTime, action) {\r\n return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));\r\n }\r\n\r\n inherits(CatchScheduler, _super);\r\n\r\n /** @private */\r\n function CatchScheduler(scheduler, handler) {\r\n this._scheduler = scheduler;\r\n this._handler = handler;\r\n this._recursiveOriginal = null;\r\n this._recursiveWrapper = null;\r\n _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);\r\n }\r\n\r\n /** @private */\r\n CatchScheduler.prototype._clone = function (scheduler) {\r\n return new CatchScheduler(scheduler, this._handler);\r\n };\r\n\r\n /** @private */\r\n CatchScheduler.prototype._wrap = function (action) {\r\n var parent = this;\r\n return function (self, state) {\r\n try {\r\n return action(parent._getRecursiveWrapper(self), state);\r\n } catch (e) {\r\n if (!parent._handler(e)) { throw e; }\r\n return disposableEmpty;\r\n }\r\n };\r\n };\r\n\r\n /** @private */\r\n CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {\r\n if (this._recursiveOriginal !== scheduler) {\r\n this._recursiveOriginal = scheduler;\r\n var wrapper = this._clone(scheduler);\r\n wrapper._recursiveOriginal = scheduler;\r\n wrapper._recursiveWrapper = wrapper;\r\n this._recursiveWrapper = wrapper;\r\n }\r\n return this._recursiveWrapper;\r\n };\r\n\r\n /** @private */\r\n CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {\r\n var self = this, failed = false, d = new SingleAssignmentDisposable();\r\n\r\n d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {\r\n if (failed) { return null; }\r\n try {\r\n return action(state1);\r\n } catch (e) {\r\n failed = true;\r\n if (!self._handler(e)) { throw e; }\r\n d.dispose();\r\n return null;\r\n }\r\n }));\r\n\r\n return d;\r\n };\r\n\r\n return CatchScheduler;\r\n }(Scheduler));\r\n\r\n /**\r\n * Represents a notification to an observer.\r\n */\r\n var Notification = Rx.Notification = (function () {\r\n function Notification(kind, hasValue) { \r\n this.hasValue = hasValue == null ? false : hasValue;\r\n this.kind = kind;\r\n }\r\n\r\n /**\r\n * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.\r\n * \r\n * @memberOf Notification\r\n * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..\r\n * @param {Function} onError Delegate to invoke for an OnError notification.\r\n * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.\r\n * @returns {Any} Result produced by the observation.\r\n */\r\n Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {\r\n return observerOrOnNext && typeof observerOrOnNext === 'object' ?\r\n this._acceptObservable(observerOrOnNext) :\r\n this._accept(observerOrOnNext, onError, onCompleted);\r\n };\r\n\r\n /**\r\n * Returns an observable sequence with a single notification.\r\n * \r\n * @memberOf Notifications\r\n * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.\r\n * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.\r\n */\r\n Notification.prototype.toObservable = function (scheduler) {\r\n var notification = this;\r\n isScheduler(scheduler) || (scheduler = immediateScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n return scheduler.schedule(function () {\r\n notification._acceptObservable(observer);\r\n notification.kind === 'N' && observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n return Notification;\r\n })();\r\n\r\n /**\r\n * Creates an object that represents an OnNext notification to an observer.\r\n * @param {Any} value The value contained in the notification.\r\n * @returns {Notification} The OnNext notification containing the value.\r\n */\r\n var notificationCreateOnNext = Notification.createOnNext = (function () {\r\n\r\n function _accept (onNext) { return onNext(this.value); }\r\n function _acceptObservable(observer) { return observer.onNext(this.value); }\r\n function toString () { return 'OnNext(' + this.value + ')'; }\r\n\r\n return function (value) {\r\n var notification = new Notification('N', true);\r\n notification.value = value;\r\n notification._accept = _accept;\r\n notification._acceptObservable = _acceptObservable;\r\n notification.toString = toString;\r\n return notification;\r\n };\r\n }());\r\n\r\n /**\r\n * Creates an object that represents an OnError notification to an observer.\r\n * @param {Any} error The exception contained in the notification.\r\n * @returns {Notification} The OnError notification containing the exception.\r\n */\r\n var notificationCreateOnError = Notification.createOnError = (function () {\r\n\r\n function _accept (onNext, onError) { return onError(this.exception); }\r\n function _acceptObservable(observer) { return observer.onError(this.exception); }\r\n function toString () { return 'OnError(' + this.exception + ')'; }\r\n\r\n return function (exception) {\r\n var notification = new Notification('E');\r\n notification.exception = exception;\r\n notification._accept = _accept;\r\n notification._acceptObservable = _acceptObservable;\r\n notification.toString = toString;\r\n return notification;\r\n };\r\n }());\r\n\r\n /**\r\n * Creates an object that represents an OnCompleted notification to an observer.\r\n * @returns {Notification} The OnCompleted notification.\r\n */\r\n var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {\r\n\r\n function _accept (onNext, onError, onCompleted) { return onCompleted(); }\r\n function _acceptObservable(observer) { return observer.onCompleted(); }\r\n function toString () { return 'OnCompleted()'; }\r\n\r\n return function () {\r\n var notification = new Notification('C');\r\n notification._accept = _accept;\r\n notification._acceptObservable = _acceptObservable;\r\n notification.toString = toString;\r\n return notification;\r\n };\r\n }());\r\n\r\n var Enumerator = Rx.internals.Enumerator = function (next) {\r\n this._next = next;\r\n };\r\n\r\n Enumerator.prototype.next = function () {\r\n return this._next();\r\n };\r\n\r\n Enumerator.prototype[$iterator$] = function () { return this; }\r\n\r\n var Enumerable = Rx.internals.Enumerable = function (iterator) {\r\n this._iterator = iterator;\r\n };\r\n\r\n Enumerable.prototype[$iterator$] = function () {\r\n return this._iterator();\r\n };\r\n\r\n Enumerable.prototype.concat = function () {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var e;\r\n try {\r\n e = sources[$iterator$]();\r\n } catch(err) {\r\n observer.onError();\r\n return;\r\n }\r\n\r\n var isDisposed, \r\n subscription = new SerialDisposable();\r\n var cancelable = immediateScheduler.scheduleRecursive(function (self) {\r\n var currentItem;\r\n if (isDisposed) { return; }\r\n\r\n try {\r\n currentItem = e.next();\r\n } catch (ex) {\r\n observer.onError(ex);\r\n return;\r\n }\r\n\r\n if (currentItem.done) {\r\n observer.onCompleted();\r\n return;\r\n }\r\n\r\n // Check if promise\r\n var currentValue = currentItem.value;\r\n isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));\r\n\r\n var d = new SingleAssignmentDisposable();\r\n subscription.setDisposable(d);\r\n d.setDisposable(currentValue.subscribe(\r\n observer.onNext.bind(observer),\r\n observer.onError.bind(observer),\r\n function () { self(); })\r\n );\r\n });\r\n\r\n return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {\r\n isDisposed = true;\r\n }));\r\n });\r\n };\r\n\r\n Enumerable.prototype.catchException = function () {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var e;\r\n try {\r\n e = sources[$iterator$]();\r\n } catch(err) {\r\n observer.onError();\r\n return;\r\n }\r\n\r\n var isDisposed, \r\n lastException,\r\n subscription = new SerialDisposable();\r\n var cancelable = immediateScheduler.scheduleRecursive(function (self) {\r\n if (isDisposed) { return; }\r\n\r\n var currentItem;\r\n try {\r\n currentItem = e.next();\r\n } catch (ex) {\r\n observer.onError(ex);\r\n return;\r\n }\r\n\r\n if (currentItem.done) {\r\n if (lastException) {\r\n observer.onError(lastException);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n return;\r\n }\r\n\r\n // Check if promise\r\n var currentValue = currentItem.value;\r\n isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); \r\n\r\n var d = new SingleAssignmentDisposable();\r\n subscription.setDisposable(d);\r\n d.setDisposable(currentValue.subscribe(\r\n observer.onNext.bind(observer),\r\n function (exn) {\r\n lastException = exn;\r\n self();\r\n },\r\n observer.onCompleted.bind(observer)));\r\n });\r\n return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {\r\n isDisposed = true;\r\n }));\r\n });\r\n };\r\n\r\n var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {\r\n if (repeatCount == null) { repeatCount = -1; }\r\n return new Enumerable(function () {\r\n var left = repeatCount;\r\n return new Enumerator(function () {\r\n if (left === 0) { return doneEnumerator; }\r\n if (left > 0) { left--; }\r\n return { done: false, value: value };\r\n });\r\n });\r\n };\r\n\r\n var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {\r\n selector || (selector = identity);\r\n return new Enumerable(function () {\r\n var index = -1;\r\n return new Enumerator(\r\n function () {\r\n return ++index < source.length ?\r\n { done: false, value: selector.call(thisArg, source[index], index, source) } :\r\n doneEnumerator;\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Supports push-style iteration over an observable sequence.\r\n */\r\n var Observer = Rx.Observer = function () { };\r\n\r\n /**\r\n * Creates a notification callback from an observer.\r\n * \r\n * @param observer Observer object.\r\n * @returns The action that forwards its input notification to the underlying observer.\r\n */\r\n Observer.prototype.toNotifier = function () {\r\n var observer = this;\r\n return function (n) {\r\n return n.accept(observer);\r\n };\r\n };\r\n\r\n /**\r\n * Hides the identity of an observer.\r\n\r\n * @returns An observer that hides the identity of the specified observer. \r\n */ \r\n Observer.prototype.asObserver = function () {\r\n return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));\r\n };\r\n\r\n /**\r\n * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.\r\n * If a violation is detected, an Error is thrown from the offending observer method call.\r\n * \r\n * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.\r\n */ \r\n Observer.prototype.checked = function () { return new CheckedObserver(this); };\r\n\r\n /**\r\n * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.\r\n * \r\n * @static\r\n * @memberOf Observer\r\n * @param {Function} [onNext] Observer's OnNext action implementation.\r\n * @param {Function} [onError] Observer's OnError action implementation.\r\n * @param {Function} [onCompleted] Observer's OnCompleted action implementation.\r\n * @returns {Observer} The observer object implemented using the given actions.\r\n */\r\n var observerCreate = Observer.create = function (onNext, onError, onCompleted) {\r\n onNext || (onNext = noop);\r\n onError || (onError = defaultError);\r\n onCompleted || (onCompleted = noop);\r\n return new AnonymousObserver(onNext, onError, onCompleted);\r\n };\r\n\r\n /**\r\n * Creates an observer from a notification callback.\r\n * \r\n * @static\r\n * @memberOf Observer\r\n * @param {Function} handler Action that handles a notification.\r\n * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.\r\n */\r\n Observer.fromNotifier = function (handler) {\r\n return new AnonymousObserver(function (x) {\r\n return handler(notificationCreateOnNext(x));\r\n }, function (exception) {\r\n return handler(notificationCreateOnError(exception));\r\n }, function () {\r\n return handler(notificationCreateOnCompleted());\r\n });\r\n };\r\n\r\n /**\r\n * Schedules the invocation of observer methods on the given scheduler.\r\n * @param {Scheduler} scheduler Scheduler to schedule observer messages on.\r\n * @returns {Observer} Observer whose messages are scheduled on the given scheduler.\r\n */\r\n Observer.notifyOn = function (scheduler) {\r\n return new ObserveOnObserver(scheduler, this);\r\n };\r\n \r\n /**\r\n * Abstract base class for implementations of the Observer class.\r\n * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. \r\n */\r\n var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {\r\n inherits(AbstractObserver, _super);\r\n\r\n /**\r\n * Creates a new observer in a non-stopped state.\r\n *\r\n * @constructor\r\n */\r\n function AbstractObserver() {\r\n this.isStopped = false;\r\n _super.call(this);\r\n }\r\n\r\n /**\r\n * Notifies the observer of a new element in the sequence.\r\n * \r\n * @memberOf AbstractObserver\r\n * @param {Any} value Next element in the sequence. \r\n */\r\n AbstractObserver.prototype.onNext = function (value) {\r\n if (!this.isStopped) {\r\n this.next(value);\r\n }\r\n };\r\n\r\n /**\r\n * Notifies the observer that an exception has occurred.\r\n * \r\n * @memberOf AbstractObserver\r\n * @param {Any} error The error that has occurred. \r\n */ \r\n AbstractObserver.prototype.onError = function (error) {\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n this.error(error);\r\n }\r\n };\r\n\r\n /**\r\n * Notifies the observer of the end of the sequence.\r\n */ \r\n AbstractObserver.prototype.onCompleted = function () {\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n this.completed();\r\n }\r\n };\r\n\r\n /**\r\n * Disposes the observer, causing it to transition to the stopped state.\r\n */\r\n AbstractObserver.prototype.dispose = function () {\r\n this.isStopped = true;\r\n };\r\n\r\n AbstractObserver.prototype.fail = function (e) {\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n this.error(e);\r\n return true;\r\n }\r\n\r\n return false;\r\n };\r\n\r\n return AbstractObserver;\r\n }(Observer));\r\n\r\n /**\r\n * Class to create an Observer instance from delegate-based implementations of the on* methods.\r\n */\r\n var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {\r\n inherits(AnonymousObserver, _super);\r\n\r\n /**\r\n * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.\r\n * @param {Any} onNext Observer's OnNext action implementation.\r\n * @param {Any} onError Observer's OnError action implementation.\r\n * @param {Any} onCompleted Observer's OnCompleted action implementation. \r\n */ \r\n function AnonymousObserver(onNext, onError, onCompleted) {\r\n _super.call(this);\r\n this._onNext = onNext;\r\n this._onError = onError;\r\n this._onCompleted = onCompleted;\r\n }\r\n\r\n /**\r\n * Calls the onNext action.\r\n * @param {Any} value Next element in the sequence. \r\n */ \r\n AnonymousObserver.prototype.next = function (value) {\r\n this._onNext(value);\r\n };\r\n\r\n /**\r\n * Calls the onError action.\r\n * @param {Any} error The error that has occurred. \r\n */ \r\n AnonymousObserver.prototype.error = function (exception) {\r\n this._onError(exception);\r\n };\r\n\r\n /**\r\n * Calls the onCompleted action.\r\n */ \r\n AnonymousObserver.prototype.completed = function () {\r\n this._onCompleted();\r\n };\r\n\r\n return AnonymousObserver;\r\n }(AbstractObserver));\r\n\r\n var CheckedObserver = (function (_super) {\r\n inherits(CheckedObserver, _super);\r\n\r\n function CheckedObserver(observer) {\r\n _super.call(this);\r\n this._observer = observer;\r\n this._state = 0; // 0 - idle, 1 - busy, 2 - done\r\n }\r\n\r\n var CheckedObserverPrototype = CheckedObserver.prototype;\r\n\r\n CheckedObserverPrototype.onNext = function (value) {\r\n this.checkAccess();\r\n try {\r\n this._observer.onNext(value);\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n this._state = 0;\r\n }\r\n };\r\n\r\n CheckedObserverPrototype.onError = function (err) {\r\n this.checkAccess();\r\n try {\r\n this._observer.onError(err);\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n this._state = 2;\r\n }\r\n };\r\n\r\n CheckedObserverPrototype.onCompleted = function () {\r\n this.checkAccess();\r\n try {\r\n this._observer.onCompleted();\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n this._state = 2;\r\n }\r\n };\r\n\r\n CheckedObserverPrototype.checkAccess = function () {\r\n if (this._state === 1) { throw new Error('Re-entrancy detected'); }\r\n if (this._state === 2) { throw new Error('Observer completed'); }\r\n if (this._state === 0) { this._state = 1; }\r\n };\r\n\r\n return CheckedObserver;\r\n }(Observer));\r\n\r\n var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {\r\n inherits(ScheduledObserver, _super);\r\n\r\n function ScheduledObserver(scheduler, observer) {\r\n _super.call(this);\r\n this.scheduler = scheduler;\r\n this.observer = observer;\r\n this.isAcquired = false;\r\n this.hasFaulted = false;\r\n this.queue = [];\r\n this.disposable = new SerialDisposable();\r\n }\r\n\r\n ScheduledObserver.prototype.next = function (value) {\r\n var self = this;\r\n this.queue.push(function () {\r\n self.observer.onNext(value);\r\n });\r\n };\r\n\r\n ScheduledObserver.prototype.error = function (exception) {\r\n var self = this;\r\n this.queue.push(function () {\r\n self.observer.onError(exception);\r\n });\r\n };\r\n\r\n ScheduledObserver.prototype.completed = function () {\r\n var self = this;\r\n this.queue.push(function () {\r\n self.observer.onCompleted();\r\n });\r\n };\r\n\r\n ScheduledObserver.prototype.ensureActive = function () {\r\n var isOwner = false, parent = this;\r\n if (!this.hasFaulted && this.queue.length > 0) {\r\n isOwner = !this.isAcquired;\r\n this.isAcquired = true;\r\n }\r\n if (isOwner) {\r\n this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {\r\n var work;\r\n if (parent.queue.length > 0) {\r\n work = parent.queue.shift();\r\n } else {\r\n parent.isAcquired = false;\r\n return;\r\n }\r\n try {\r\n work();\r\n } catch (ex) {\r\n parent.queue = [];\r\n parent.hasFaulted = true;\r\n throw ex;\r\n }\r\n self();\r\n }));\r\n }\r\n };\r\n\r\n ScheduledObserver.prototype.dispose = function () {\r\n _super.prototype.dispose.call(this);\r\n this.disposable.dispose();\r\n };\r\n\r\n return ScheduledObserver;\r\n }(AbstractObserver));\r\n\r\n /** @private */\r\n var ObserveOnObserver = (function (_super) {\r\n inherits(ObserveOnObserver, _super);\r\n\r\n /** @private */ \r\n function ObserveOnObserver() {\r\n _super.apply(this, arguments);\r\n }\r\n\r\n /** @private */ \r\n ObserveOnObserver.prototype.next = function (value) {\r\n _super.prototype.next.call(this, value);\r\n this.ensureActive();\r\n };\r\n\r\n /** @private */ \r\n ObserveOnObserver.prototype.error = function (e) {\r\n _super.prototype.error.call(this, e);\r\n this.ensureActive();\r\n };\r\n\r\n /** @private */ \r\n ObserveOnObserver.prototype.completed = function () {\r\n _super.prototype.completed.call(this);\r\n this.ensureActive();\r\n };\r\n\r\n return ObserveOnObserver;\r\n })(ScheduledObserver);\r\n\r\n var observableProto;\r\n\r\n /**\r\n * Represents a push-style collection.\r\n */\r\n var Observable = Rx.Observable = (function () {\r\n\r\n function Observable(subscribe) {\r\n this._subscribe = subscribe;\r\n }\r\n\r\n observableProto = Observable.prototype;\r\n\r\n /**\r\n * Subscribes an observer to the observable sequence.\r\n * \r\n * @example\r\n * 1 - source.subscribe();\r\n * 2 - source.subscribe(observer);\r\n * 3 - source.subscribe(function (x) { console.log(x); });\r\n * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });\r\n * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });\r\n * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.\r\n * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.\r\n * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.\r\n * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. \r\n */\r\n observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {\r\n var subscriber = typeof observerOrOnNext === 'object' ?\r\n observerOrOnNext :\r\n observerCreate(observerOrOnNext, onError, onCompleted);\r\n\r\n return this._subscribe(subscriber);\r\n };\r\n\r\n return Observable;\r\n })();\r\n\r\n /**\r\n * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.\r\n * \r\n * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects\r\n * that require to be run on a scheduler, use subscribeOn.\r\n * \r\n * @param {Scheduler} scheduler Scheduler to notify observers on.\r\n * @returns {Observable} The source sequence whose observations happen on the specified scheduler. \r\n */\r\n observableProto.observeOn = function (scheduler) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(new ObserveOnObserver(scheduler, observer));\r\n });\r\n };\r\n\r\n /**\r\n * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;\r\n * see the remarks section for more information on the distinction between subscribeOn and observeOn.\r\n\r\n * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer\r\n * callbacks on a scheduler, use observeOn.\r\n\r\n * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.\r\n * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.\r\n */\r\n observableProto.subscribeOn = function (scheduler) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var m = new SingleAssignmentDisposable(), d = new SerialDisposable();\r\n d.setDisposable(m);\r\n m.setDisposable(scheduler.schedule(function () {\r\n d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));\r\n }));\r\n return d;\r\n });\r\n };\r\n\r\n /**\r\n * Converts a Promise to an Observable sequence\r\n * @param {Promise} An ES6 Compliant promise.\r\n * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.\r\n */\r\n var observableFromPromise = Observable.fromPromise = function (promise) {\r\n return new AnonymousObservable(function (observer) {\r\n promise.then(\r\n function (value) {\r\n observer.onNext(value);\r\n observer.onCompleted();\r\n }, \r\n function (reason) {\r\n observer.onError(reason);\r\n });\r\n\r\n return function () {\r\n if (promise && promise.abort) {\r\n promise.abort();\r\n }\r\n }\r\n });\r\n };\r\n /*\r\n * Converts an existing observable sequence to an ES6 Compatible Promise\r\n * @example\r\n * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);\r\n * \r\n * // With config\r\n * Rx.config.Promise = RSVP.Promise;\r\n * var promise = Rx.Observable.return(42).toPromise();\r\n * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.\r\n * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.\r\n */\r\n observableProto.toPromise = function (promiseCtor) {\r\n promiseCtor || (promiseCtor = Rx.config.Promise);\r\n if (!promiseCtor) {\r\n throw new Error('Promise type not provided nor in Rx.config.Promise');\r\n }\r\n var source = this;\r\n return new promiseCtor(function (resolve, reject) {\r\n // No cancellation can be done\r\n var value, hasValue = false;\r\n source.subscribe(function (v) {\r\n value = v;\r\n hasValue = true;\r\n }, function (err) {\r\n reject(err);\r\n }, function () {\r\n if (hasValue) {\r\n resolve(value);\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Creates a list from an observable sequence.\r\n * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. \r\n */\r\n observableProto.toArray = function () {\r\n var self = this;\r\n return new AnonymousObservable(function(observer) {\r\n var arr = [];\r\n return self.subscribe(\r\n arr.push.bind(arr),\r\n observer.onError.bind(observer),\r\n function () {\r\n observer.onNext(arr);\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Creates an observable sequence from a specified subscribe method implementation.\r\n * \r\n * @example\r\n * var res = Rx.Observable.create(function (observer) { return function () { } );\r\n * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); \r\n * var res = Rx.Observable.create(function (observer) { } ); \r\n * \r\n * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.\r\n * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.\r\n */\r\n Observable.create = Observable.createWithDisposable = function (subscribe) {\r\n return new AnonymousObservable(subscribe);\r\n };\r\n\r\n /**\r\n * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.\r\n * \r\n * @example\r\n * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); \r\n * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.\r\n * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.\r\n */\r\n var observableDefer = Observable.defer = function (observableFactory) {\r\n return new AnonymousObservable(function (observer) {\r\n var result;\r\n try {\r\n result = observableFactory();\r\n } catch (e) {\r\n return observableThrow(e).subscribe(observer);\r\n }\r\n isPromise(result) && (result = observableFromPromise(result));\r\n return result.subscribe(observer);\r\n });\r\n };\r\n\r\n /**\r\n * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.\r\n * \r\n * @example\r\n * var res = Rx.Observable.empty(); \r\n * var res = Rx.Observable.empty(Rx.Scheduler.timeout); \r\n * @param {Scheduler} [scheduler] Scheduler to send the termination call on.\r\n * @returns {Observable} An observable sequence with no elements.\r\n */\r\n var observableEmpty = Observable.empty = function (scheduler) {\r\n isScheduler(scheduler) || (scheduler = immediateScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n return scheduler.schedule(function () {\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n var maxSafeInteger = Math.pow(2, 53) - 1;\r\n\r\n function numberIsFinite(value) {\r\n return typeof value === 'number' && root.isFinite(value);\r\n }\r\n\r\n function isNan(n) {\r\n return n !== n;\r\n }\r\n\r\n function isIterable(o) {\r\n return o[$iterator$] !== undefined;\r\n }\r\n\r\n function sign(value) {\r\n var number = +value;\r\n if (number === 0) { return number; }\r\n if (isNaN(number)) { return number; }\r\n return number < 0 ? -1 : 1;\r\n }\r\n\r\n function toLength(o) {\r\n var len = +o.length;\r\n if (isNaN(len)) { return 0; }\r\n if (len === 0 || !numberIsFinite(len)) { return len; }\r\n len = sign(len) * Math.floor(Math.abs(len)); \r\n if (len <= 0) { return 0; }\r\n if (len > maxSafeInteger) { return maxSafeInteger; }\r\n return len;\r\n }\r\n\r\n function isCallable(f) {\r\n return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';\r\n }\r\n\r\n /**\r\n * This method creates a new Observable sequence from an array-like or iterable object.\r\n * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.\r\n * @param {Function} [mapFn] Map function to call on every element of the array.\r\n * @param {Any} [thisArg] The context to use calling the mapFn if provided.\r\n * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.\r\n */\r\n Observable.from = function (iterable, mapFn, thisArg, scheduler) {\r\n if (iterable == null) {\r\n throw new Error('iterable cannot be null.')\r\n }\r\n if (mapFn && !isCallable(mapFn)) {\r\n throw new Error('mapFn when provided must be a function');\r\n }\r\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var list = Object(iterable),\r\n objIsIterable = isIterable(list),\r\n len = objIsIterable ? 0 : toLength(list),\r\n it = objIsIterable ? list[$iterator$]() : null,\r\n i = 0;\r\n return scheduler.scheduleRecursive(function (self) {\r\n if (i < len || objIsIterable) {\r\n var result;\r\n if (objIsIterable) {\r\n var next = it.next();\r\n if (next.done) {\r\n observer.onCompleted();\r\n return;\r\n }\r\n\r\n result = next.value;\r\n } else {\r\n result = list[i];\r\n }\r\n\r\n if (mapFn && isCallable(mapFn)) {\r\n try {\r\n result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n } \r\n }\r\n\r\n observer.onNext(result);\r\n i++;\r\n self();\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.\r\n * \r\n * @example\r\n * var res = Rx.Observable.fromArray([1,2,3]);\r\n * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);\r\n * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.\r\n * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.\r\n */\r\n var observableFromArray = Observable.fromArray = function (array, scheduler) {\r\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var count = 0, len = array.length;\r\n return scheduler.scheduleRecursive(function (self) {\r\n if (count < len) {\r\n observer.onNext(array[count++]);\r\n self();\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.\r\n * \r\n * @example\r\n * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });\r\n * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);\r\n * @param {Mixed} initialState Initial state.\r\n * @param {Function} condition Condition to terminate generation (upon returning false).\r\n * @param {Function} iterate Iteration step function.\r\n * @param {Function} resultSelector Selector function for results produced in the sequence.\r\n * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.\r\n * @returns {Observable} The generated sequence.\r\n */\r\n Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {\r\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var first = true, state = initialState;\r\n return scheduler.scheduleRecursive(function (self) {\r\n var hasResult, result;\r\n try {\r\n if (first) {\r\n first = false;\r\n } else {\r\n state = iterate(state);\r\n }\r\n hasResult = condition(state);\r\n if (hasResult) {\r\n result = resultSelector(state);\r\n }\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n if (hasResult) {\r\n observer.onNext(result);\r\n self();\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.\r\n * @example\r\n * var res = Rx.Observable.of(1,2,3);\r\n * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.\r\n */\r\n Observable.of = function () {\r\n var len = arguments.length, args = new Array(len);\r\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\r\n return observableFromArray(args);\r\n };\r\n\r\n /**\r\n * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. \r\n * @example\r\n * var res = Rx.Observable.of(1,2,3);\r\n * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.\r\n * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.\r\n */\r\n var observableOf = Observable.ofWithScheduler = function (scheduler) {\r\n var len = arguments.length - 1, args = new Array(len);\r\n for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }\r\n return observableFromArray(args, scheduler);\r\n };\r\n\r\n /**\r\n * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).\r\n * @returns {Observable} An observable sequence whose observers will never get called.\r\n */\r\n var observableNever = Observable.never = function () {\r\n return new AnonymousObservable(function () {\r\n return disposableEmpty;\r\n });\r\n };\r\n\r\n /**\r\n * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.\r\n * \r\n * @example\r\n * var res = Rx.Observable.range(0, 10);\r\n * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);\r\n * @param {Number} start The value of the first integer in the sequence.\r\n * @param {Number} count The number of sequential integers to generate.\r\n * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.\r\n * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.\r\n */\r\n Observable.range = function (start, count, scheduler) {\r\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n return scheduler.scheduleRecursiveWithState(0, function (i, self) {\r\n if (i < count) {\r\n observer.onNext(start + i);\r\n self(i + 1);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.\r\n * \r\n * @example\r\n * var res = Rx.Observable.repeat(42);\r\n * var res = Rx.Observable.repeat(42, 4);\r\n * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);\r\n * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);\r\n * @param {Mixed} value Element to repeat.\r\n * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.\r\n * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.\r\n * @returns {Observable} An observable sequence that repeats the given element the specified number of times.\r\n */\r\n Observable.repeat = function (value, repeatCount, scheduler) {\r\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\r\n return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);\r\n };\r\n\r\n /**\r\n * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.\r\n * There is an alias called 'just', and 'returnValue' for browsers 0) {\r\n s = q.shift();\r\n subscribe(s);\r\n } else {\r\n activeCount--;\r\n if (isStopped && activeCount === 0) {\r\n observer.onCompleted();\r\n }\r\n }\r\n }));\r\n };\r\n group.add(sources.subscribe(function (innerSource) {\r\n if (activeCount < maxConcurrentOrOther) {\r\n activeCount++;\r\n subscribe(innerSource);\r\n } else {\r\n q.push(innerSource);\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n isStopped = true;\r\n if (activeCount === 0) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n return group;\r\n });\r\n };\r\n\r\n /**\r\n * Merges all the observable sequences into a single observable sequence. \r\n * The scheduler is optional and if not specified, the immediate scheduler is used.\r\n * \r\n * @example\r\n * 1 - merged = Rx.Observable.merge(xs, ys, zs);\r\n * 2 - merged = Rx.Observable.merge([xs, ys, zs]);\r\n * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);\r\n * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); \r\n * @returns {Observable} The observable sequence that merges the elements of the observable sequences. \r\n */ \r\n var observableMerge = Observable.merge = function () {\r\n var scheduler, sources;\r\n if (!arguments[0]) {\r\n scheduler = immediateScheduler;\r\n sources = slice.call(arguments, 1);\r\n } else if (arguments[0].now) {\r\n scheduler = arguments[0];\r\n sources = slice.call(arguments, 1);\r\n } else {\r\n scheduler = immediateScheduler;\r\n sources = slice.call(arguments, 0);\r\n }\r\n if (Array.isArray(sources[0])) {\r\n sources = sources[0];\r\n }\r\n return observableFromArray(sources, scheduler).mergeObservable();\r\n }; \r\n\r\n /**\r\n * Merges an observable sequence of observable sequences into an observable sequence.\r\n * @returns {Observable} The observable sequence that merges the elements of the inner sequences. \r\n */ \r\n observableProto.mergeObservable = observableProto.mergeAll =function () {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var group = new CompositeDisposable(),\r\n isStopped = false,\r\n m = new SingleAssignmentDisposable();\r\n\r\n group.add(m);\r\n m.setDisposable(sources.subscribe(function (innerSource) {\r\n var innerSubscription = new SingleAssignmentDisposable();\r\n group.add(innerSubscription);\r\n\r\n // Check if Promise or Observable\r\n if (isPromise(innerSource)) {\r\n innerSource = observableFromPromise(innerSource);\r\n }\r\n\r\n innerSubscription.setDisposable(innerSource.subscribe(function (x) {\r\n observer.onNext(x);\r\n }, observer.onError.bind(observer), function () {\r\n group.remove(innerSubscription);\r\n if (isStopped && group.length === 1) { observer.onCompleted(); }\r\n }));\r\n }, observer.onError.bind(observer), function () {\r\n isStopped = true;\r\n if (group.length === 1) { observer.onCompleted(); }\r\n }));\r\n return group;\r\n });\r\n };\r\n\r\n /**\r\n * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.\r\n * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.\r\n * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.\r\n */\r\n observableProto.onErrorResumeNext = function (second) {\r\n if (!second) {\r\n throw new Error('Second observable is required');\r\n }\r\n return onErrorResumeNext([this, second]);\r\n };\r\n\r\n /**\r\n * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.\r\n * \r\n * @example\r\n * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);\r\n * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);\r\n * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. \r\n */\r\n var onErrorResumeNext = Observable.onErrorResumeNext = function () {\r\n var sources = argsOrArray(arguments, 0);\r\n return new AnonymousObservable(function (observer) {\r\n var pos = 0, subscription = new SerialDisposable(),\r\n cancelable = immediateScheduler.scheduleRecursive(function (self) {\r\n var current, d;\r\n if (pos < sources.length) {\r\n current = sources[pos++];\r\n isPromise(current) && (current = observableFromPromise(current));\r\n d = new SingleAssignmentDisposable();\r\n subscription.setDisposable(d);\r\n d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {\r\n self();\r\n }, function () {\r\n self();\r\n }));\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n return new CompositeDisposable(subscription, cancelable);\r\n });\r\n };\r\n\r\n /**\r\n * Returns the values from the source observable sequence only after the other observable sequence produces a value.\r\n * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.\r\n * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. \r\n */\r\n observableProto.skipUntil = function (other) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var isOpen = false;\r\n var disposables = new CompositeDisposable(source.subscribe(function (left) {\r\n isOpen && observer.onNext(left);\r\n }, observer.onError.bind(observer), function () {\r\n isOpen && observer.onCompleted();\r\n }));\r\n\r\n isPromise(other) && (other = observableFromPromise(other));\r\n\r\n var rightSubscription = new SingleAssignmentDisposable();\r\n disposables.add(rightSubscription);\r\n rightSubscription.setDisposable(other.subscribe(function () {\r\n isOpen = true;\r\n rightSubscription.dispose();\r\n }, observer.onError.bind(observer), function () {\r\n rightSubscription.dispose();\r\n }));\r\n\r\n return disposables;\r\n });\r\n };\r\n\r\n /**\r\n * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.\r\n * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. \r\n */\r\n observableProto['switch'] = observableProto.switchLatest = function () {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var hasLatest = false,\r\n innerSubscription = new SerialDisposable(),\r\n isStopped = false,\r\n latest = 0,\r\n subscription = sources.subscribe(function (innerSource) {\r\n var d = new SingleAssignmentDisposable(), id = ++latest;\r\n hasLatest = true;\r\n innerSubscription.setDisposable(d);\r\n\r\n // Check if Promise or Observable\r\n if (isPromise(innerSource)) {\r\n innerSource = observableFromPromise(innerSource);\r\n }\r\n\r\n d.setDisposable(innerSource.subscribe(function (x) {\r\n if (latest === id) {\r\n observer.onNext(x);\r\n }\r\n }, function (e) {\r\n if (latest === id) {\r\n observer.onError(e);\r\n }\r\n }, function () {\r\n if (latest === id) {\r\n hasLatest = false;\r\n if (isStopped) {\r\n observer.onCompleted();\r\n }\r\n }\r\n }));\r\n }, observer.onError.bind(observer), function () {\r\n isStopped = true;\r\n if (!hasLatest) {\r\n observer.onCompleted();\r\n }\r\n });\r\n return new CompositeDisposable(subscription, innerSubscription);\r\n });\r\n };\r\n\r\n /**\r\n * Returns the values from the source observable sequence until the other observable sequence produces a value.\r\n * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.\r\n * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. \r\n */\r\n observableProto.takeUntil = function (other) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n isPromise(other) && (other = observableFromPromise(other));\r\n return new CompositeDisposable(\r\n source.subscribe(observer),\r\n other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)\r\n );\r\n });\r\n };\r\n\r\n function zipArray(second, resultSelector) {\r\n var first = this;\r\n return new AnonymousObservable(function (observer) {\r\n var index = 0, len = second.length;\r\n return first.subscribe(function (left) {\r\n if (index < len) {\r\n var right = second[index++], result;\r\n try {\r\n result = resultSelector(left, right);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n observer.onNext(result);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n } \r\n\r\n /**\r\n * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.\r\n * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.\r\n *\r\n * @example\r\n * 1 - res = obs1.zip(obs2, fn);\r\n * 1 - res = x1.zip([1,2,3], fn); \r\n * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. \r\n */ \r\n observableProto.zip = function () {\r\n if (Array.isArray(arguments[0])) {\r\n return zipArray.apply(this, arguments);\r\n }\r\n var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();\r\n sources.unshift(parent);\r\n return new AnonymousObservable(function (observer) {\r\n var n = sources.length,\r\n queues = arrayInitialize(n, function () { return []; }),\r\n isDone = arrayInitialize(n, function () { return false; });\r\n \r\n function next(i) {\r\n var res, queuedValues;\r\n if (queues.every(function (x) { return x.length > 0; })) {\r\n try {\r\n queuedValues = queues.map(function (x) { return x.shift(); });\r\n res = resultSelector.apply(parent, queuedValues);\r\n } catch (ex) {\r\n observer.onError(ex);\r\n return;\r\n }\r\n observer.onNext(res);\r\n } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {\r\n observer.onCompleted();\r\n }\r\n };\r\n\r\n function done(i) {\r\n isDone[i] = true;\r\n if (isDone.every(function (x) { return x; })) {\r\n observer.onCompleted();\r\n }\r\n }\r\n\r\n var subscriptions = new Array(n);\r\n for (var idx = 0; idx < n; idx++) {\r\n (function (i) {\r\n var source = sources[i], sad = new SingleAssignmentDisposable();\r\n isPromise(source) && (source = observableFromPromise(source));\r\n sad.setDisposable(source.subscribe(function (x) {\r\n queues[i].push(x);\r\n next(i);\r\n }, observer.onError.bind(observer), function () {\r\n done(i);\r\n }));\r\n subscriptions[i] = sad;\r\n })(idx);\r\n }\r\n\r\n return new CompositeDisposable(subscriptions);\r\n });\r\n };\r\n /**\r\n * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.\r\n * @param arguments Observable sources.\r\n * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.\r\n * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.\r\n */\r\n Observable.zip = function () {\r\n var args = slice.call(arguments, 0),\r\n first = args.shift();\r\n return first.zip.apply(first, args);\r\n };\r\n\r\n /**\r\n * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.\r\n * @param arguments Observable sources.\r\n * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.\r\n */\r\n Observable.zipArray = function () {\r\n var sources = argsOrArray(arguments, 0);\r\n return new AnonymousObservable(function (observer) {\r\n var n = sources.length,\r\n queues = arrayInitialize(n, function () { return []; }),\r\n isDone = arrayInitialize(n, function () { return false; });\r\n\r\n function next(i) {\r\n if (queues.every(function (x) { return x.length > 0; })) {\r\n var res = queues.map(function (x) { return x.shift(); });\r\n observer.onNext(res);\r\n } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {\r\n observer.onCompleted();\r\n return;\r\n }\r\n };\r\n\r\n function done(i) {\r\n isDone[i] = true;\r\n if (isDone.every(identity)) {\r\n observer.onCompleted();\r\n return;\r\n }\r\n }\r\n\r\n var subscriptions = new Array(n);\r\n for (var idx = 0; idx < n; idx++) {\r\n (function (i) {\r\n subscriptions[i] = new SingleAssignmentDisposable();\r\n subscriptions[i].setDisposable(sources[i].subscribe(function (x) {\r\n queues[i].push(x);\r\n next(i);\r\n }, observer.onError.bind(observer), function () {\r\n done(i);\r\n }));\r\n })(idx);\r\n }\r\n\r\n var compositeDisposable = new CompositeDisposable(subscriptions);\r\n compositeDisposable.add(disposableCreate(function () {\r\n for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {\r\n queues[qIdx] = [];\r\n }\r\n }));\r\n return compositeDisposable;\r\n });\r\n };\r\n\r\n /**\r\n * Hides the identity of an observable sequence.\r\n * @returns {Observable} An observable sequence that hides the identity of the source sequence. \r\n */\r\n observableProto.asObservable = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(observer);\r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.\r\n * \r\n * @example\r\n * var res = xs.bufferWithCount(10);\r\n * var res = xs.bufferWithCount(10, 1);\r\n * @param {Number} count Length of each buffer.\r\n * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.\r\n * @returns {Observable} An observable sequence of buffers. \r\n */\r\n observableProto.bufferWithCount = function (count, skip) {\r\n if (typeof skip !== 'number') {\r\n skip = count;\r\n }\r\n return this.windowWithCount(count, skip).selectMany(function (x) {\r\n return x.toArray();\r\n }).where(function (x) {\r\n return x.length > 0;\r\n });\r\n };\r\n\r\n /**\r\n * Dematerializes the explicit notification values of an observable sequence as implicit notifications.\r\n * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.\r\n */ \r\n observableProto.dematerialize = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(function (x) {\r\n return x.accept(observer);\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.\r\n * \r\n * var obs = observable.distinctUntilChanged();\r\n * var obs = observable.distinctUntilChanged(function (x) { return x.id; });\r\n * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });\r\n *\r\n * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.\r\n * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.\r\n * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. \r\n */\r\n observableProto.distinctUntilChanged = function (keySelector, comparer) {\r\n var source = this;\r\n keySelector || (keySelector = identity);\r\n comparer || (comparer = defaultComparer);\r\n return new AnonymousObservable(function (observer) {\r\n var hasCurrentKey = false, currentKey;\r\n return source.subscribe(function (value) {\r\n var comparerEquals = false, key;\r\n try {\r\n key = keySelector(value);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n if (hasCurrentKey) {\r\n try {\r\n comparerEquals = comparer(currentKey, key);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n }\r\n if (!hasCurrentKey || !comparerEquals) {\r\n hasCurrentKey = true;\r\n currentKey = key;\r\n observer.onNext(value);\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.\r\n * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.\r\n * \r\n * @example\r\n * var res = observable.do(observer);\r\n * var res = observable.do(onNext);\r\n * var res = observable.do(onNext, onError);\r\n * var res = observable.do(onNext, onError, onCompleted);\r\n * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.\r\n * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.\r\n * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.\r\n * @returns {Observable} The source sequence with the side-effecting behavior applied. \r\n */\r\n observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {\r\n var source = this, onNextFunc;\r\n if (typeof observerOrOnNext === 'function') {\r\n onNextFunc = observerOrOnNext;\r\n } else {\r\n onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);\r\n onError = observerOrOnNext.onError.bind(observerOrOnNext);\r\n onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(function (x) {\r\n try {\r\n onNextFunc(x);\r\n } catch (e) {\r\n observer.onError(e);\r\n }\r\n observer.onNext(x);\r\n }, function (err) {\r\n if (!onError) {\r\n observer.onError(err);\r\n } else {\r\n try {\r\n onError(err);\r\n } catch (e) {\r\n observer.onError(e);\r\n }\r\n observer.onError(err);\r\n }\r\n }, function () {\r\n if (!onCompleted) {\r\n observer.onCompleted();\r\n } else {\r\n try {\r\n onCompleted();\r\n } catch (e) {\r\n observer.onError(e);\r\n }\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.\r\n * \r\n * @example\r\n * var res = observable.finallyAction(function () { console.log('sequence ended'; });\r\n * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.\r\n * @returns {Observable} Source sequence with the action-invoking termination behavior applied. \r\n */ \r\n observableProto['finally'] = observableProto.finallyAction = function (action) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var subscription;\r\n try {\r\n subscription = source.subscribe(observer);\r\n } catch (e) {\r\n action();\r\n throw e;\r\n }\r\n return disposableCreate(function () {\r\n try {\r\n subscription.dispose();\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n action();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Ignores all elements in an observable sequence leaving only the termination messages.\r\n * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. \r\n */\r\n observableProto.ignoreElements = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Materializes the implicit notifications of an observable sequence as explicit notification values.\r\n * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.\r\n */ \r\n observableProto.materialize = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(function (value) {\r\n observer.onNext(notificationCreateOnNext(value));\r\n }, function (e) {\r\n observer.onNext(notificationCreateOnError(e));\r\n observer.onCompleted();\r\n }, function () {\r\n observer.onNext(notificationCreateOnCompleted());\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.\r\n * \r\n * @example\r\n * var res = repeated = source.repeat();\r\n * var res = repeated = source.repeat(42);\r\n * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.\r\n * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. \r\n */\r\n observableProto.repeat = function (repeatCount) {\r\n return enumerableRepeat(this, repeatCount).concat();\r\n };\r\n\r\n /**\r\n * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.\r\n * Note if you encounter an error and want it to retry once, then you must use .retry(2);\r\n * \r\n * @example\r\n * var res = retried = retry.repeat();\r\n * var res = retried = retry.repeat(2);\r\n * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.\r\n * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. \r\n */\r\n observableProto.retry = function (retryCount) {\r\n return enumerableRepeat(this, retryCount).catchException();\r\n };\r\n\r\n /**\r\n * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.\r\n * For aggregation behavior with no intermediate results, see Observable.aggregate.\r\n * @example\r\n * var res = source.scan(function (acc, x) { return acc + x; });\r\n * var res = source.scan(0, function (acc, x) { return acc + x; });\r\n * @param {Mixed} [seed] The initial accumulator value.\r\n * @param {Function} accumulator An accumulator function to be invoked on each element.\r\n * @returns {Observable} An observable sequence containing the accumulated values.\r\n */\r\n observableProto.scan = function () {\r\n var hasSeed = false, seed, accumulator, source = this;\r\n if (arguments.length === 2) {\r\n hasSeed = true;\r\n seed = arguments[0];\r\n accumulator = arguments[1]; \r\n } else {\r\n accumulator = arguments[0];\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var hasAccumulation, accumulation, hasValue;\r\n return source.subscribe (\r\n function (x) {\r\n try {\r\n if (!hasValue) {\r\n hasValue = true;\r\n }\r\n \r\n if (hasAccumulation) {\r\n accumulation = accumulator(accumulation, x);\r\n } else {\r\n accumulation = hasSeed ? accumulator(seed, x) : x;\r\n hasAccumulation = true;\r\n } \r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n \r\n observer.onNext(accumulation);\r\n },\r\n observer.onError.bind(observer),\r\n function () {\r\n if (!hasValue && hasSeed) {\r\n observer.onNext(seed);\r\n }\r\n observer.onCompleted();\r\n }\r\n );\r\n });\r\n };\r\n\r\n /**\r\n * Bypasses a specified number of elements at the end of an observable sequence.\r\n * @description\r\n * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are\r\n * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. \r\n * @param count Number of elements to bypass at the end of the source sequence.\r\n * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. \r\n */\r\n observableProto.skipLast = function (count) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n return source.subscribe(function (x) {\r\n q.push(x);\r\n if (q.length > count) {\r\n observer.onNext(q.shift());\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.\r\n * \r\n * var res = source.startWith(1, 2, 3);\r\n * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);\r\n * \r\n * @memberOf Observable#\r\n * @returns {Observable} The source sequence prepended with the specified values. \r\n */\r\n observableProto.startWith = function () {\r\n var values, scheduler, start = 0;\r\n if (!!arguments.length && 'now' in Object(arguments[0])) {\r\n scheduler = arguments[0];\r\n start = 1;\r\n } else {\r\n scheduler = immediateScheduler;\r\n }\r\n values = slice.call(arguments, start);\r\n return enumerableFor([observableFromArray(values, scheduler), this]).concat();\r\n };\r\n\r\n /**\r\n * Returns a specified number of contiguous elements from the end of an observable sequence.\r\n * \r\n * @example\r\n * var res = source.takeLast(5);\r\n * \r\n * @description\r\n * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of\r\n * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.\r\n * @param {Number} count Number of elements to take from the end of the source sequence.\r\n * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.\r\n */ \r\n observableProto.takeLast = function (count) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n return source.subscribe(function (x) {\r\n q.push(x);\r\n q.length > count && q.shift();\r\n }, observer.onError.bind(observer), function () {\r\n while(q.length > 0) { observer.onNext(q.shift()); }\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Returns an array with the specified number of contiguous elements from the end of an observable sequence.\r\n * \r\n * @description\r\n * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the\r\n * source sequence, this buffer is produced on the result sequence. \r\n * @param {Number} count Number of elements to take from the end of the source sequence.\r\n * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.\r\n */\r\n observableProto.takeLastBuffer = function (count) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n return source.subscribe(function (x) {\r\n q.push(x);\r\n q.length > count && q.shift();\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(q);\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.\r\n * \r\n * var res = xs.windowWithCount(10);\r\n * var res = xs.windowWithCount(10, 1);\r\n * @param {Number} count Length of each window.\r\n * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.\r\n * @returns {Observable} An observable sequence of windows. \r\n */\r\n observableProto.windowWithCount = function (count, skip) {\r\n var source = this;\r\n if (count <= 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n if (arguments.length === 1) {\r\n skip = count;\r\n }\r\n if (skip <= 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var m = new SingleAssignmentDisposable(),\r\n refCountDisposable = new RefCountDisposable(m),\r\n n = 0,\r\n q = [],\r\n createWindow = function () {\r\n var s = new Subject();\r\n q.push(s);\r\n observer.onNext(addRef(s, refCountDisposable));\r\n };\r\n createWindow();\r\n m.setDisposable(source.subscribe(function (x) {\r\n var s;\r\n for (var i = 0, len = q.length; i < len; i++) {\r\n q[i].onNext(x);\r\n }\r\n var c = n - count + 1;\r\n if (c >= 0 && c % skip === 0) {\r\n s = q.shift();\r\n s.onCompleted();\r\n }\r\n n++;\r\n if (n % skip === 0) {\r\n createWindow();\r\n }\r\n }, function (exception) {\r\n while (q.length > 0) {\r\n q.shift().onError(exception);\r\n }\r\n observer.onError(exception);\r\n }, function () {\r\n while (q.length > 0) {\r\n q.shift().onCompleted();\r\n }\r\n observer.onCompleted();\r\n }));\r\n return refCountDisposable;\r\n });\r\n };\r\n\r\n function concatMap(source, selector, thisArg) {\r\n return source.map(function (x, i) {\r\n var result = selector.call(thisArg, x, i);\r\n return isPromise(result) ? observableFromPromise(result) : result;\r\n }).concatAll();\r\n }\r\n\r\n /**\r\n * One of the Following:\r\n * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.\r\n * \r\n * @example\r\n * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });\r\n * Or:\r\n * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.\r\n * \r\n * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });\r\n * Or:\r\n * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.\r\n * \r\n * var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));\r\n * @param selector A transform function to apply to each element or an observable sequence to project each element from the \r\n * source sequence onto which could be either an observable or Promise.\r\n * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.\r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. \r\n */\r\n observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {\r\n if (resultSelector) {\r\n return this.concatMap(function (x, i) {\r\n var selectorResult = selector(x, i),\r\n result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;\r\n\r\n return result.map(function (y) {\r\n return resultSelector(x, y, i);\r\n });\r\n });\r\n }\r\n return typeof selector === 'function' ?\r\n concatMap(this, selector, thisArg) :\r\n concatMap(this, function () { return selector; });\r\n };\r\n\r\n /**\r\n * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.\r\n * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.\r\n * @param {Function} onError A transform function to apply when an error occurs in the source sequence.\r\n * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.\r\n * @param {Any} [thisArg] An optional \"this\" to use to invoke each transform. \r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.\r\n */ \r\n observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var index = 0;\r\n\r\n return source.subscribe(\r\n function (x) {\r\n var result;\r\n try {\r\n result = onNext.call(thisArg, x, index++);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n isPromise(result) && (result = observableFromPromise(result));\r\n observer.onNext(result);\r\n },\r\n function (err) {\r\n var result;\r\n try {\r\n result = onError.call(thisArg, err);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n isPromise(result) && (result = observableFromPromise(result));\r\n observer.onNext(result);\r\n observer.onCompleted();\r\n }, \r\n function () {\r\n var result;\r\n try {\r\n result = onCompleted.call(thisArg);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n } \r\n isPromise(result) && (result = observableFromPromise(result)); \r\n observer.onNext(result);\r\n observer.onCompleted();\r\n });\r\n }).concatAll();\r\n };\r\n /**\r\n * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.\r\n * \r\n * var res = obs = xs.defaultIfEmpty();\r\n * 2 - obs = xs.defaultIfEmpty(false);\r\n * \r\n * @memberOf Observable#\r\n * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.\r\n * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. \r\n */\r\n observableProto.defaultIfEmpty = function (defaultValue) {\r\n var source = this;\r\n if (defaultValue === undefined) {\r\n defaultValue = null;\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var found = false;\r\n return source.subscribe(function (x) {\r\n found = true;\r\n observer.onNext(x);\r\n }, observer.onError.bind(observer), function () {\r\n if (!found) {\r\n observer.onNext(defaultValue);\r\n }\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n // Swap out for Array.findIndex\r\n function arrayIndexOfComparer(array, item, comparer) {\r\n for (var i = 0, len = array.length; i < len; i++) {\r\n if (comparer(array[i], item)) { return i; }\r\n }\r\n return -1;\r\n }\r\n\r\n function HashSet(comparer) {\r\n this.comparer = comparer;\r\n this.set = [];\r\n }\r\n HashSet.prototype.push = function(value) {\r\n var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;\r\n retValue && this.set.push(value);\r\n return retValue;\r\n };\r\n\r\n /**\r\n * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.\r\n * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. \r\n * \r\n * @example\r\n * var res = obs = xs.distinct();\r\n * 2 - obs = xs.distinct(function (x) { return x.id; });\r\n * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); \r\n * @param {Function} [keySelector] A function to compute the comparison key for each element.\r\n * @param {Function} [comparer] Used to compare items in the collection.\r\n * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.\r\n */\r\n observableProto.distinct = function (keySelector, comparer) {\r\n var source = this;\r\n comparer || (comparer = defaultComparer);\r\n return new AnonymousObservable(function (observer) {\r\n var hashSet = new HashSet(comparer);\r\n return source.subscribe(function (x) {\r\n var key = x;\r\n\r\n if (keySelector) {\r\n try {\r\n key = keySelector(x);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n } \r\n }\r\n hashSet.push(key) && observer.onNext(x);\r\n }, \r\n observer.onError.bind(observer), \r\n observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.\r\n * \r\n * @example\r\n * var res = observable.groupBy(function (x) { return x.id; });\r\n * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });\r\n * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });\r\n * @param {Function} keySelector A function to extract the key for each element.\r\n * @param {Function} [elementSelector] A function to map each source element to an element in an observable group.\r\n * @param {Function} [comparer] Used to determine whether the objects are equal.\r\n * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. \r\n */\r\n observableProto.groupBy = function (keySelector, elementSelector, comparer) {\r\n return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);\r\n };\r\n\r\n /**\r\n * Groups the elements of an observable sequence according to a specified key selector function.\r\n * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same\r\n * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.\r\n * \r\n * @example\r\n * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });\r\n * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });\r\n * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });\r\n * @param {Function} keySelector A function to extract the key for each element.\r\n * @param {Function} durationSelector A function to signal the expiration of a group.\r\n * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.\r\n * @returns {Observable} \r\n * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.\r\n * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.\r\n * \r\n */\r\n observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {\r\n var source = this;\r\n elementSelector || (elementSelector = identity);\r\n comparer || (comparer = defaultComparer);\r\n return new AnonymousObservable(function (observer) {\r\n function handleError(e) { return function (item) { item.onError(e); }; }\r\n var map = new Dictionary(0, comparer),\r\n groupDisposable = new CompositeDisposable(),\r\n refCountDisposable = new RefCountDisposable(groupDisposable);\r\n\r\n groupDisposable.add(source.subscribe(function (x) {\r\n var key;\r\n try {\r\n key = keySelector(x);\r\n } catch (e) {\r\n map.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n var fireNewMapEntry = false,\r\n writer = map.tryGetValue(key);\r\n if (!writer) {\r\n writer = new Subject();\r\n map.set(key, writer);\r\n fireNewMapEntry = true;\r\n }\r\n\r\n if (fireNewMapEntry) {\r\n var group = new GroupedObservable(key, writer, refCountDisposable),\r\n durationGroup = new GroupedObservable(key, writer);\r\n try {\r\n duration = durationSelector(durationGroup);\r\n } catch (e) {\r\n map.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n observer.onNext(group);\r\n \r\n var md = new SingleAssignmentDisposable();\r\n groupDisposable.add(md);\r\n \r\n var expire = function () {\r\n map.remove(key) && writer.onCompleted();\r\n groupDisposable.remove(md);\r\n };\r\n\r\n md.setDisposable(duration.take(1).subscribe(\r\n noop, \r\n function (exn) {\r\n map.getValues().forEach(handleError(exn));\r\n observer.onError(exn);\r\n }, \r\n expire)\r\n );\r\n }\r\n\r\n var element;\r\n try {\r\n element = elementSelector(x);\r\n } catch (e) {\r\n map.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n writer.onNext(element);\r\n }, function (ex) {\r\n map.getValues().forEach(handleError(ex));\r\n observer.onError(ex);\r\n }, function () {\r\n map.getValues().forEach(function (item) { item.onCompleted(); });\r\n observer.onCompleted();\r\n }));\r\n\r\n return refCountDisposable;\r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into a new form by incorporating the element's index.\r\n * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback.\r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. \r\n */\r\n observableProto.select = observableProto.map = function (selector, thisArg) {\r\n var parent = this;\r\n return new AnonymousObservable(function (observer) {\r\n var count = 0;\r\n return parent.subscribe(function (value) {\r\n var result;\r\n try {\r\n result = selector.call(thisArg, value, count++, parent);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n observer.onNext(result);\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Retrieves the value of a specified property from all elements in the Observable sequence.\r\n * @param {String} property The property to pluck.\r\n * @returns {Observable} Returns a new Observable sequence of property values.\r\n */\r\n observableProto.pluck = function (property) {\r\n return this.select(function (x) { return x[property]; });\r\n };\r\n\r\n function flatMap(source, selector, thisArg) {\r\n return source.map(function (x, i) {\r\n var result = selector.call(thisArg, x, i);\r\n return isPromise(result) ? observableFromPromise(result) : result;\r\n }).mergeObservable();\r\n }\r\n\r\n /**\r\n * One of the Following:\r\n * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.\r\n * \r\n * @example\r\n * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });\r\n * Or:\r\n * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.\r\n * \r\n * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });\r\n * Or:\r\n * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.\r\n * \r\n * var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));\r\n * @param selector A transform function to apply to each element or an observable sequence to project each element from the \r\n * source sequence onto which could be either an observable or Promise.\r\n * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.\r\n * @param {Any} [thisArg] Object to use as this when executing callback.\r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. \r\n */\r\n observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {\r\n if (resultSelector) {\r\n return this.flatMap(function (x, i) {\r\n var selectorResult = selector(x, i),\r\n result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;\r\n\r\n return result.map(function (y) {\r\n return resultSelector(x, y, i);\r\n });\r\n }, thisArg);\r\n }\r\n return typeof selector === 'function' ?\r\n flatMap(this, selector, thisArg) :\r\n flatMap(this, function () { return selector; });\r\n };\r\n\r\n /**\r\n * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.\r\n * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.\r\n * @param {Function} onError A transform function to apply when an error occurs in the source sequence.\r\n * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.\r\n * @param {Any} [thisArg] An optional \"this\" to use to invoke each transform.\r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.\r\n */\r\n observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var index = 0;\r\n\r\n return source.subscribe(\r\n function (x) {\r\n var result;\r\n try {\r\n result = onNext.call(thisArg, x, index++);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n isPromise(result) && (result = observableFromPromise(result));\r\n observer.onNext(result);\r\n },\r\n function (err) {\r\n var result;\r\n try {\r\n result = onError.call(thisArg, err);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n isPromise(result) && (result = observableFromPromise(result));\r\n observer.onNext(result);\r\n observer.onCompleted();\r\n }, \r\n function () {\r\n var result;\r\n try {\r\n result = onCompleted.call(thisArg);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n } \r\n isPromise(result) && (result = observableFromPromise(result)); \r\n observer.onNext(result);\r\n observer.onCompleted();\r\n });\r\n }).mergeAll();\r\n };\r\n /**\r\n * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then \r\n * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.\r\n * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback.\r\n * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences \r\n * and that at any point in time produces the elements of the most recent inner observable sequence that has been received.\r\n */\r\n observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {\r\n return this.select(selector, thisArg).switchLatest();\r\n };\r\n\r\n /**\r\n * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.\r\n * @param {Number} count The number of elements to skip before returning the remaining elements.\r\n * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. \r\n */\r\n observableProto.skip = function (count) {\r\n if (count < 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n var observable = this;\r\n return new AnonymousObservable(function (observer) {\r\n var remaining = count;\r\n return observable.subscribe(function (x) {\r\n if (remaining <= 0) {\r\n observer.onNext(x);\r\n } else {\r\n remaining--;\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.\r\n * The element's index is used in the logic of the predicate function.\r\n * \r\n * var res = source.skipWhile(function (value) { return value < 10; });\r\n * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });\r\n * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback. \r\n * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. \r\n */\r\n observableProto.skipWhile = function (predicate, thisArg) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var i = 0, running = false;\r\n return source.subscribe(function (x) {\r\n if (!running) {\r\n try {\r\n running = !predicate.call(thisArg, x, i++, source);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n }\r\n if (running) {\r\n observer.onNext(x);\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).\r\n * \r\n * var res = source.take(5);\r\n * var res = source.take(0, Rx.Scheduler.timeout);\r\n * @param {Number} count The number of elements to return.\r\n * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case is set to 0.\r\n * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. \r\n */\r\n observableProto.take = function (count, scheduler) {\r\n if (count < 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n if (count === 0) {\r\n return observableEmpty(scheduler);\r\n }\r\n var observable = this;\r\n return new AnonymousObservable(function (observer) {\r\n var remaining = count;\r\n return observable.subscribe(function (x) {\r\n if (remaining > 0) {\r\n remaining--;\r\n observer.onNext(x);\r\n if (remaining === 0) {\r\n observer.onCompleted();\r\n }\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Returns elements from an observable sequence as long as a specified condition is true.\r\n * The element's index is used in the logic of the predicate function.\r\n * \r\n * @example\r\n * var res = source.takeWhile(function (value) { return value < 10; });\r\n * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });\r\n * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback. \r\n * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. \r\n */\r\n observableProto.takeWhile = function (predicate, thisArg) {\r\n var observable = this;\r\n return new AnonymousObservable(function (observer) {\r\n var i = 0, running = true;\r\n return observable.subscribe(function (x) {\r\n if (running) {\r\n try {\r\n running = predicate.call(thisArg, x, i++, observable);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (running) {\r\n observer.onNext(x);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.\r\n * \r\n * @example\r\n * var res = source.where(function (value) { return value < 10; });\r\n * var res = source.where(function (value, index) { return value < 10 || index < 10; });\r\n * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback.\r\n * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. \r\n */\r\n observableProto.where = observableProto.filter = function (predicate, thisArg) {\r\n var parent = this;\r\n return new AnonymousObservable(function (observer) {\r\n var count = 0;\r\n return parent.subscribe(function (value) {\r\n var shouldRun;\r\n try {\r\n shouldRun = predicate.call(thisArg, value, count++, parent);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n if (shouldRun) {\r\n observer.onNext(value);\r\n }\r\n }, observer.onError.bind(observer), observer.onCompleted.bind(observer));\r\n });\r\n };\r\n\r\n observableProto.finalValue = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var hasValue = false, value;\r\n return source.subscribe(function (x) {\r\n hasValue = true;\r\n value = x;\r\n }, observer.onError.bind(observer), function () {\r\n if (!hasValue) {\r\n observer.onError(new Error(sequenceContainsNoElements));\r\n } else {\r\n observer.onNext(value);\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n function extremaBy(source, keySelector, comparer) {\r\n return new AnonymousObservable(function (observer) {\r\n var hasValue = false, lastKey = null, list = [];\r\n return source.subscribe(function (x) {\r\n var comparison, key;\r\n try {\r\n key = keySelector(x);\r\n } catch (ex) {\r\n observer.onError(ex);\r\n return;\r\n }\r\n comparison = 0;\r\n if (!hasValue) {\r\n hasValue = true;\r\n lastKey = key;\r\n } else {\r\n try {\r\n comparison = comparer(key, lastKey);\r\n } catch (ex1) {\r\n observer.onError(ex1);\r\n return;\r\n }\r\n }\r\n if (comparison > 0) {\r\n lastKey = key;\r\n list = [];\r\n }\r\n if (comparison >= 0) {\r\n list.push(x);\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(list);\r\n observer.onCompleted();\r\n });\r\n });\r\n }\r\n\r\n function firstOnly(x) {\r\n if (x.length === 0) {\r\n throw new Error(sequenceContainsNoElements);\r\n }\r\n return x[0];\r\n }\r\n\r\n /**\r\n * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.\r\n * For aggregation behavior with incremental intermediate results, see Observable.scan.\r\n * @example\r\n * 1 - res = source.aggregate(function (acc, x) { return acc + x; });\r\n * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; });\r\n * @param {Mixed} [seed] The initial accumulator value.\r\n * @param {Function} accumulator An accumulator function to be invoked on each element.\r\n * @returns {Observable} An observable sequence containing a single element with the final accumulator value.\r\n */\r\n observableProto.aggregate = function () {\r\n var seed, hasSeed, accumulator;\r\n if (arguments.length === 2) {\r\n seed = arguments[0];\r\n hasSeed = true;\r\n accumulator = arguments[1];\r\n } else {\r\n accumulator = arguments[0];\r\n }\r\n return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();\r\n };\r\n\r\n /**\r\n * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.\r\n * For aggregation behavior with incremental intermediate results, see Observable.scan.\r\n * @example\r\n * 1 - res = source.reduce(function (acc, x) { return acc + x; });\r\n * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0);\r\n * @param {Function} accumulator An accumulator function to be invoked on each element.\r\n * @param {Any} [seed] The initial accumulator value. \r\n * @returns {Observable} An observable sequence containing a single element with the final accumulator value.\r\n */\r\n observableProto.reduce = function (accumulator) {\r\n var seed, hasSeed;\r\n if (arguments.length === 2) {\r\n hasSeed = true;\r\n seed = arguments[1];\r\n } \r\n return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();\r\n };\r\n\r\n /**\r\n * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.\r\n * @example\r\n * var result = source.any();\r\n * var result = source.any(function (x) { return x > 3; });\r\n * @param {Function} [predicate] A function to test each element for a condition.\r\n * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.\r\n */\r\n observableProto.some = observableProto.any = function (predicate, thisArg) {\r\n var source = this;\r\n return predicate ? \r\n source.where(predicate, thisArg).any() : \r\n new AnonymousObservable(function (observer) {\r\n return source.subscribe(function () {\r\n observer.onNext(true);\r\n observer.onCompleted();\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Determines whether an observable sequence is empty.\r\n * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.\r\n */\r\n observableProto.isEmpty = function () {\r\n return this.any().map(not);\r\n };\r\n\r\n /**\r\n * Determines whether all elements of an observable sequence satisfy a condition.\r\n * \r\n * 1 - res = source.all(function (value) { return value.length > 3; });\r\n * @memberOf Observable#\r\n * @param {Function} [predicate] A function to test each element for a condition.\r\n * @param {Any} [thisArg] Object to use as this when executing callback.\r\n * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.\r\n */\r\n observableProto.every = observableProto.all = function (predicate, thisArg) {\r\n return this.where(function (v) {\r\n return !predicate(v);\r\n }, thisArg).any().select(function (b) {\r\n return !b;\r\n });\r\n };\r\n\r\n /**\r\n * Determines whether an observable sequence contains a specified element with an optional equality comparer.\r\n * @example\r\n * 1 - res = source.contains(42);\r\n * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; });\r\n * @param value The value to locate in the source sequence.\r\n * @param {Function} [comparer] An equality comparer to compare elements.\r\n * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value.\r\n */\r\n observableProto.contains = function (value, comparer) {\r\n comparer || (comparer = defaultComparer);\r\n return this.where(function (v) {\r\n return comparer(v, value);\r\n }).any();\r\n };\r\n\r\n /**\r\n * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.\r\n * @example\r\n * res = source.count();\r\n * res = source.count(function (x) { return x > 3; });\r\n * @param {Function} [predicate]A function to test each element for a condition.\r\n * @param {Any} [thisArg] Object to use as this when executing callback. \r\n * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.\r\n */\r\n observableProto.count = function (predicate, thisArg) {\r\n return predicate ?\r\n this.where(predicate, thisArg).count() :\r\n this.aggregate(0, function (count) {\r\n return count + 1;\r\n });\r\n };\r\n\r\n /**\r\n * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.\r\n * @example\r\n * var res = source.sum();\r\n * var res = source.sum(function (x) { return x.value; });\r\n * @param {Function} [selector] A transform function to apply to each element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback. \r\n * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.\r\n */ \r\n observableProto.sum = function (keySelector, thisArg) {\r\n return keySelector ? \r\n this.select(keySelector, thisArg).sum() :\r\n this.aggregate(0, function (prev, curr) {\r\n return prev + curr;\r\n });\r\n };\r\n\r\n /**\r\n * Returns the elements in an observable sequence with the minimum key value according to the specified comparer.\r\n * @example\r\n * var res = source.minBy(function (x) { return x.value; });\r\n * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });\r\n * @param {Function} keySelector Key selector function.\r\n * @param {Function} [comparer] Comparer used to compare key values.\r\n * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.\r\n */ \r\n observableProto.minBy = function (keySelector, comparer) {\r\n comparer || (comparer = defaultSubComparer);\r\n return extremaBy(this, keySelector, function (x, y) {\r\n return comparer(x, y) * -1;\r\n });\r\n };\r\n\r\n /**\r\n * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.\r\n * @example\r\n * var res = source.min();\r\n * var res = source.min(function (x, y) { return x.value - y.value; });\r\n * @param {Function} [comparer] Comparer used to compare elements.\r\n * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.\r\n */\r\n observableProto.min = function (comparer) {\r\n return this.minBy(identity, comparer).select(function (x) {\r\n return firstOnly(x);\r\n });\r\n };\r\n\r\n /**\r\n * Returns the elements in an observable sequence with the maximum key value according to the specified comparer.\r\n * @example\r\n * var res = source.maxBy(function (x) { return x.value; });\r\n * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });\r\n * @param {Function} keySelector Key selector function.\r\n * @param {Function} [comparer] Comparer used to compare key values.\r\n * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.\r\n */\r\n observableProto.maxBy = function (keySelector, comparer) {\r\n comparer || (comparer = defaultSubComparer);\r\n return extremaBy(this, keySelector, comparer);\r\n };\r\n\r\n /**\r\n * Returns the maximum value in an observable sequence according to the specified comparer.\r\n * @example\r\n * var res = source.max();\r\n * var res = source.max(function (x, y) { return x.value - y.value; });\r\n * @param {Function} [comparer] Comparer used to compare elements.\r\n * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.\r\n */\r\n observableProto.max = function (comparer) {\r\n return this.maxBy(identity, comparer).select(function (x) {\r\n return firstOnly(x);\r\n });\r\n };\r\n\r\n /**\r\n * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.\r\n * @example\r\n * var res = res = source.average();\r\n * var res = res = source.average(function (x) { return x.value; });\r\n * @param {Function} [selector] A transform function to apply to each element.\r\n * @param {Any} [thisArg] Object to use as this when executing callback. \r\n * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.\r\n */\r\n observableProto.average = function (keySelector, thisArg) {\r\n return keySelector ?\r\n this.select(keySelector, thisArg).average() :\r\n this.scan({\r\n sum: 0,\r\n count: 0\r\n }, function (prev, cur) {\r\n return {\r\n sum: prev.sum + cur,\r\n count: prev.count + 1\r\n };\r\n }).finalValue().select(function (s) {\r\n if (s.count === 0) {\r\n throw new Error('The input sequence was empty');\r\n }\r\n return s.sum / s.count;\r\n });\r\n };\r\n\r\n function sequenceEqualArray(first, second, comparer) {\r\n return new AnonymousObservable(function (observer) {\r\n var count = 0, len = second.length;\r\n return first.subscribe(function (value) {\r\n var equal = false;\r\n try {\r\n if (count < len) {\r\n equal = comparer(value, second[count++]);\r\n }\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (!equal) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(count === len);\r\n observer.onCompleted();\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.\r\n * \r\n * @example\r\n * var res = res = source.sequenceEqual([1,2,3]);\r\n * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });\r\n * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));\r\n * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });\r\n * @param {Observable} second Second observable sequence or array to compare.\r\n * @param {Function} [comparer] Comparer used to compare elements of both sequences.\r\n * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.\r\n */\r\n observableProto.sequenceEqual = function (second, comparer) {\r\n var first = this;\r\n comparer || (comparer = defaultComparer);\r\n if (Array.isArray(second)) {\r\n return sequenceEqualArray(first, second, comparer);\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var donel = false, doner = false, ql = [], qr = [];\r\n var subscription1 = first.subscribe(function (x) {\r\n var equal, v;\r\n if (qr.length > 0) {\r\n v = qr.shift();\r\n try {\r\n equal = comparer(v, x);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (!equal) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n }\r\n } else if (doner) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n } else {\r\n ql.push(x);\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n donel = true;\r\n if (ql.length === 0) {\r\n if (qr.length > 0) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n } else if (doner) {\r\n observer.onNext(true);\r\n observer.onCompleted();\r\n }\r\n }\r\n });\r\n\r\n isPromise(second) && (second = observableFromPromise(second));\r\n var subscription2 = second.subscribe(function (x) {\r\n var equal, v;\r\n if (ql.length > 0) {\r\n v = ql.shift();\r\n try {\r\n equal = comparer(v, x);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n if (!equal) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n }\r\n } else if (donel) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n } else {\r\n qr.push(x);\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n doner = true;\r\n if (qr.length === 0) {\r\n if (ql.length > 0) {\r\n observer.onNext(false);\r\n observer.onCompleted();\r\n } else if (donel) {\r\n observer.onNext(true);\r\n observer.onCompleted();\r\n }\r\n }\r\n });\r\n return new CompositeDisposable(subscription1, subscription2);\r\n });\r\n };\r\n\r\n function elementAtOrDefault(source, index, hasDefault, defaultValue) {\r\n if (index < 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var i = index;\r\n return source.subscribe(function (x) {\r\n if (i === 0) {\r\n observer.onNext(x);\r\n observer.onCompleted();\r\n }\r\n i--;\r\n }, observer.onError.bind(observer), function () {\r\n if (!hasDefault) {\r\n observer.onError(new Error(argumentOutOfRange));\r\n } else {\r\n observer.onNext(defaultValue);\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Returns the element at a specified index in a sequence.\r\n * @example\r\n * var res = source.elementAt(5);\r\n * @param {Number} index The zero-based index of the element to retrieve.\r\n * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.\r\n */\r\n observableProto.elementAt = function (index) {\r\n return elementAtOrDefault(this, index, false);\r\n };\r\n\r\n /**\r\n * Returns the element at a specified index in a sequence or a default value if the index is out of range.\r\n * @example\r\n * var res = source.elementAtOrDefault(5);\r\n * var res = source.elementAtOrDefault(5, 0);\r\n * @param {Number} index The zero-based index of the element to retrieve.\r\n * @param [defaultValue] The default value if the index is outside the bounds of the source sequence.\r\n * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.\r\n */ \r\n observableProto.elementAtOrDefault = function (index, defaultValue) {\r\n return elementAtOrDefault(this, index, true, defaultValue);\r\n };\r\n\r\n function singleOrDefaultAsync(source, hasDefault, defaultValue) {\r\n return new AnonymousObservable(function (observer) {\r\n var value = defaultValue, seenValue = false;\r\n return source.subscribe(function (x) {\r\n if (seenValue) {\r\n observer.onError(new Error('Sequence contains more than one element'));\r\n } else {\r\n value = x;\r\n seenValue = true;\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n if (!seenValue && !hasDefault) {\r\n observer.onError(new Error(sequenceContainsNoElements));\r\n } else {\r\n observer.onNext(value);\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.\r\n * @example\r\n * var res = res = source.single();\r\n * var res = res = source.single(function (x) { return x === 42; });\r\n * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.\r\n */\r\n observableProto.single = function (predicate, thisArg) {\r\n return predicate ?\r\n this.where(predicate, thisArg).single() :\r\n singleOrDefaultAsync(this, false);\r\n };\r\n\r\n /**\r\n * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.\r\n * @example\r\n * var res = res = source.singleOrDefault();\r\n * var res = res = source.singleOrDefault(function (x) { return x === 42; });\r\n * res = source.singleOrDefault(function (x) { return x === 42; }, 0);\r\n * res = source.singleOrDefault(null, 0);\r\n * @memberOf Observable#\r\n * @param {Function} predicate A predicate function to evaluate for elements in the source sequence.\r\n * @param [defaultValue] The default value if the index is outside the bounds of the source sequence.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.\r\n */\r\n observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {\r\n return predicate?\r\n this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :\r\n singleOrDefaultAsync(this, true, defaultValue)\r\n };\r\n function firstOrDefaultAsync(source, hasDefault, defaultValue) {\r\n return new AnonymousObservable(function (observer) {\r\n return source.subscribe(function (x) {\r\n observer.onNext(x);\r\n observer.onCompleted();\r\n }, observer.onError.bind(observer), function () {\r\n if (!hasDefault) {\r\n observer.onError(new Error(sequenceContainsNoElements));\r\n } else {\r\n observer.onNext(defaultValue);\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.\r\n * @example\r\n * var res = res = source.first();\r\n * var res = res = source.first(function (x) { return x > 3; });\r\n * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.\r\n */ \r\n observableProto.first = function (predicate, thisArg) {\r\n return predicate ?\r\n this.where(predicate, thisArg).first() :\r\n firstOrDefaultAsync(this, false);\r\n };\r\n\r\n /**\r\n * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.\r\n * @example \r\n * var res = res = source.firstOrDefault();\r\n * var res = res = source.firstOrDefault(function (x) { return x > 3; });\r\n * var res = source.firstOrDefault(function (x) { return x > 3; }, 0);\r\n * var res = source.firstOrDefault(null, 0);\r\n * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. \r\n * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate.\r\n * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.\r\n */\r\n observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {\r\n return predicate ?\r\n this.where(predicate).firstOrDefault(null, defaultValue) :\r\n firstOrDefaultAsync(this, true, defaultValue);\r\n };\r\n\r\n function lastOrDefaultAsync(source, hasDefault, defaultValue) {\r\n return new AnonymousObservable(function (observer) {\r\n var value = defaultValue, seenValue = false;\r\n return source.subscribe(function (x) {\r\n value = x;\r\n seenValue = true;\r\n }, observer.onError.bind(observer), function () {\r\n if (!seenValue && !hasDefault) {\r\n observer.onError(new Error(sequenceContainsNoElements));\r\n } else {\r\n observer.onNext(value);\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.\r\n * @example\r\n * var res = source.last();\r\n * var res = source.last(function (x) { return x > 3; });\r\n * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.\r\n */\r\n observableProto.last = function (predicate, thisArg) {\r\n return predicate ?\r\n this.where(predicate, thisArg).last() :\r\n lastOrDefaultAsync(this, false);\r\n };\r\n\r\n /**\r\n * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.\r\n * @example\r\n * var res = source.lastOrDefault();\r\n * var res = source.lastOrDefault(function (x) { return x > 3; });\r\n * var res = source.lastOrDefault(function (x) { return x > 3; }, 0);\r\n * var res = source.lastOrDefault(null, 0);\r\n * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.\r\n * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.\r\n */\r\n observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {\r\n return predicate ? \r\n this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :\r\n lastOrDefaultAsync(this, true, defaultValue);\r\n };\r\n\r\n function findValue (source, predicate, thisArg, yieldIndex) {\r\n return new AnonymousObservable(function (observer) {\r\n var i = 0;\r\n return source.subscribe(function (x) {\r\n var shouldRun;\r\n try {\r\n shouldRun = predicate.call(thisArg, x, i, source);\r\n } catch(e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (shouldRun) {\r\n observer.onNext(yieldIndex ? i : x);\r\n observer.onCompleted();\r\n } else {\r\n i++;\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(yieldIndex ? -1 : undefined);\r\n observer.onCompleted();\r\n });\r\n }); \r\n }\r\n\r\n /**\r\n * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.\r\n * @param {Function} predicate The predicate that defines the conditions of the element to search for.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.\r\n */\r\n observableProto.find = function (predicate, thisArg) {\r\n return findValue(this, predicate, thisArg, false);\r\n };\r\n\r\n /**\r\n * Searches for an element that matches the conditions defined by the specified predicate, and returns \r\n * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. \r\n * @param {Function} predicate The predicate that defines the conditions of the element to search for.\r\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate. \r\n * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.\r\n */\r\n observableProto.findIndex = function (predicate, thisArg) {\r\n return findValue(this, predicate, thisArg, true);\r\n };\r\n\r\n /**\r\n * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.\r\n * \r\n * @example\r\n * var res = Rx.Observable.start(function () { console.log('hello'); });\r\n * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);\r\n * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);\r\n * \r\n * @param {Function} func Function to run asynchronously.\r\n * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.\r\n * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\r\n * @returns {Observable} An observable sequence exposing the function's result value, or an exception.\r\n * \r\n * Remarks\r\n * * The function is called immediately, not during the subscription of the resulting sequence.\r\n * * Multiple subscriptions to the resulting sequence can observe the function's result. \r\n */\r\n Observable.start = function (func, context, scheduler) {\r\n return observableToAsync(func, context, scheduler)();\r\n };\r\n\r\n /**\r\n * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.\r\n * \r\n * @example\r\n * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);\r\n * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);\r\n * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');\r\n * \r\n * @param {Function} function Function to convert to an asynchronous function.\r\n * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.\r\n * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\r\n * @returns {Function} Asynchronous function.\r\n */\r\n var observableToAsync = Observable.toAsync = function (func, context, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return function () {\r\n var args = arguments, \r\n subject = new AsyncSubject();\r\n\r\n scheduler.schedule(function () {\r\n var result;\r\n try {\r\n result = func.apply(context, args);\r\n } catch (e) {\r\n subject.onError(e);\r\n return;\r\n }\r\n subject.onNext(result);\r\n subject.onCompleted();\r\n });\r\n return subject.asObservable();\r\n };\r\n };\r\n\r\n /**\r\n * Converts a callback function to an observable sequence. \r\n * \r\n * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.\r\n * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\r\n * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.\r\n * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.\r\n */\r\n Observable.fromCallback = function (func, context, selector) {\r\n return function () {\r\n var args = slice.call(arguments, 0);\r\n\r\n return new AnonymousObservable(function (observer) {\r\n function handler(e) {\r\n var results = e;\r\n \r\n if (selector) {\r\n try {\r\n results = selector(arguments);\r\n } catch (err) {\r\n observer.onError(err);\r\n return;\r\n }\r\n\r\n observer.onNext(results);\r\n } else {\r\n if (results.length <= 1) { \r\n observer.onNext.apply(observer, results);\r\n } else {\r\n observer.onNext(results);\r\n }\r\n }\r\n \r\n observer.onCompleted();\r\n }\r\n\r\n args.push(handler);\r\n func.apply(context, args);\r\n });\r\n };\r\n };\r\n\r\n /**\r\n * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.\r\n * @param {Function} func The function to call\r\n * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\r\n * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. \r\n * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.\r\n */\r\n Observable.fromNodeCallback = function (func, context, selector) {\r\n return function () {\r\n var args = slice.call(arguments, 0);\r\n\r\n return new AnonymousObservable(function (observer) {\r\n function handler(err) {\r\n if (err) {\r\n observer.onError(err);\r\n return;\r\n }\r\n\r\n var results = slice.call(arguments, 1);\r\n \r\n if (selector) {\r\n try {\r\n results = selector(results);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n observer.onNext(results);\r\n } else {\r\n if (results.length <= 1) { \r\n observer.onNext.apply(observer, results);\r\n } else {\r\n observer.onNext(results);\r\n }\r\n }\r\n\r\n observer.onCompleted();\r\n }\r\n\r\n args.push(handler);\r\n func.apply(context, args);\r\n });\r\n };\r\n };\r\n\r\n function createListener (element, name, handler) {\r\n if (element.addEventListener) {\r\n element.addEventListener(name, handler, false);\r\n return disposableCreate(function () {\r\n element.removeEventListener(name, handler, false);\r\n });\r\n }\r\n throw new Error('No listener found');\r\n }\r\n\r\n function createEventListener (el, eventName, handler) {\r\n var disposables = new CompositeDisposable();\r\n\r\n // Asume NodeList\r\n if (Object.prototype.toString.call(el) === '[object NodeList]') {\r\n for (var i = 0, len = el.length; i < len; i++) {\r\n disposables.add(createEventListener(el.item(i), eventName, handler));\r\n }\r\n } else if (el) {\r\n disposables.add(createListener(el, eventName, handler));\r\n }\r\n\r\n return disposables;\r\n }\r\n\r\n /**\r\n * Configuration option to determine whether to use native events only \r\n */\r\n Rx.config.useNativeEvents = false;\r\n\r\n // Check for Angular/jQuery/Zepto support\r\n var jq =\r\n !!root.angular && !!angular.element ? angular.element :\r\n (!!root.jQuery ? root.jQuery : (\r\n !!root.Zepto ? root.Zepto : null));\r\n\r\n // Check for ember\r\n var ember = !!root.Ember && typeof root.Ember.addListener === 'function';\r\n \r\n // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs\r\n // for proper loading order!\r\n var marionette = !!root.Backbone && !!root.Backbone.Marionette;\r\n\r\n /**\r\n * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.\r\n *\r\n * @example\r\n * var source = Rx.Observable.fromEvent(element, 'mouseup');\r\n * \r\n * @param {Object} element The DOMElement or NodeList to attach a listener.\r\n * @param {String} eventName The event name to attach the observable sequence.\r\n * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. \r\n * @returns {Observable} An observable sequence of events from the specified element and the specified event.\r\n */\r\n Observable.fromEvent = function (element, eventName, selector) {\r\n // Node.js specific\r\n if (element.addListener) {\r\n return fromEventPattern(\r\n function (h) { element.addListener(eventName, h); },\r\n function (h) { element.removeListener(eventName, h); },\r\n selector);\r\n } \r\n \r\n // Use only if non-native events are allowed\r\n if (!Rx.config.useNativeEvents) {\r\n if (marionette) {\r\n return fromEventPattern(\r\n function (h) { element.on(eventName, h); },\r\n function (h) { element.off(eventName, h); },\r\n selector);\r\n }\r\n if (ember) {\r\n return fromEventPattern(\r\n function (h) { Ember.addListener(element, eventName, h); },\r\n function (h) { Ember.removeListener(element, eventName, h); },\r\n selector);\r\n } \r\n if (jq) {\r\n var $elem = jq(element);\r\n return fromEventPattern(\r\n function (h) { $elem.on(eventName, h); },\r\n function (h) { $elem.off(eventName, h); },\r\n selector);\r\n }\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n return createEventListener(\r\n element, \r\n eventName, \r\n function handler (e) { \r\n var results = e;\r\n\r\n if (selector) {\r\n try {\r\n results = selector(arguments);\r\n } catch (err) {\r\n observer.onError(err);\r\n return\r\n }\r\n }\r\n\r\n observer.onNext(results); \r\n });\r\n }).publish().refCount();\r\n };\r\n\r\n /**\r\n * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.\r\n * @param {Function} addHandler The function to add a handler to the emitter.\r\n * @param {Function} [removeHandler] The optional function to remove a handler from an emitter.\r\n * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.\r\n * @returns {Observable} An observable sequence which wraps an event from an event emitter\r\n */\r\n var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {\r\n return new AnonymousObservable(function (observer) {\r\n function innerHandler (e) {\r\n var result = e;\r\n if (selector) {\r\n try {\r\n result = selector(arguments);\r\n } catch (err) {\r\n observer.onError(err);\r\n return;\r\n }\r\n }\r\n observer.onNext(result);\r\n }\r\n\r\n var returnValue = addHandler(innerHandler);\r\n return disposableCreate(function () {\r\n if (removeHandler) {\r\n removeHandler(innerHandler, returnValue);\r\n }\r\n });\r\n }).publish().refCount();\r\n };\r\n\r\n /**\r\n * Invokes the asynchronous function, surfacing the result through an observable sequence.\r\n * @param {Function} functionAsync Asynchronous function which returns a Promise to run.\r\n * @returns {Observable} An observable sequence exposing the function's result value, or an exception.\r\n */\r\n Observable.startAsync = function (functionAsync) {\r\n var promise;\r\n try {\r\n promise = functionAsync();\r\n } catch (e) {\r\n return observableThrow(e);\r\n }\r\n return observableFromPromise(promise);\r\n }\r\n\r\n var PausableObservable = (function (_super) {\r\n\r\n inherits(PausableObservable, _super);\r\n\r\n function subscribe(observer) {\r\n var conn = this.source.publish(),\r\n subscription = conn.subscribe(observer),\r\n connection = disposableEmpty;\r\n\r\n var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {\r\n if (b) {\r\n connection = conn.connect();\r\n } else {\r\n connection.dispose();\r\n connection = disposableEmpty;\r\n }\r\n });\r\n\r\n return new CompositeDisposable(subscription, connection, pausable);\r\n }\r\n\r\n function PausableObservable(source, subject) {\r\n this.source = source;\r\n this.subject = subject || new Subject();\r\n this.isPaused = true;\r\n _super.call(this, subscribe);\r\n }\r\n\r\n PausableObservable.prototype.pause = function () {\r\n if (this.isPaused === true){\r\n return;\r\n }\r\n this.isPaused = true;\r\n this.subject.onNext(false);\r\n };\r\n\r\n PausableObservable.prototype.resume = function () {\r\n if (this.isPaused === false){\r\n return;\r\n }\r\n this.isPaused = false;\r\n this.subject.onNext(true);\r\n };\r\n\r\n return PausableObservable;\r\n\r\n }(Observable));\r\n\r\n /**\r\n * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.\r\n * @example\r\n * var pauser = new Rx.Subject();\r\n * var source = Rx.Observable.interval(100).pausable(pauser);\r\n * @param {Observable} pauser The observable sequence used to pause the underlying sequence.\r\n * @returns {Observable} The observable sequence which is paused based upon the pauser.\r\n */\r\n observableProto.pausable = function (pauser) {\r\n return new PausableObservable(this, pauser);\r\n };\r\n function combineLatestSource(source, subject, resultSelector) {\r\n return new AnonymousObservable(function (observer) {\r\n var n = 2,\r\n hasValue = [false, false],\r\n hasValueAll = false,\r\n isDone = false,\r\n values = new Array(n);\r\n\r\n function next(x, i) {\r\n values[i] = x\r\n var res;\r\n hasValue[i] = true;\r\n if (hasValueAll || (hasValueAll = hasValue.every(identity))) {\r\n try {\r\n res = resultSelector.apply(null, values);\r\n } catch (ex) {\r\n observer.onError(ex);\r\n return;\r\n }\r\n observer.onNext(res);\r\n } else if (isDone) {\r\n observer.onCompleted();\r\n }\r\n }\r\n\r\n return new CompositeDisposable(\r\n source.subscribe(\r\n function (x) {\r\n next(x, 0);\r\n },\r\n observer.onError.bind(observer),\r\n function () {\r\n isDone = true;\r\n observer.onCompleted();\r\n }),\r\n subject.subscribe(\r\n function (x) {\r\n next(x, 1);\r\n },\r\n observer.onError.bind(observer))\r\n );\r\n });\r\n }\r\n\r\n var PausableBufferedObservable = (function (_super) {\r\n\r\n inherits(PausableBufferedObservable, _super);\r\n\r\n function subscribe(observer) {\r\n var q = [], previousShouldFire;\r\n \r\n var subscription = \r\n combineLatestSource(\r\n this.source,\r\n this.subject.distinctUntilChanged(), \r\n function (data, shouldFire) {\r\n return { data: data, shouldFire: shouldFire }; \r\n })\r\n .subscribe(\r\n function (results) {\r\n if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {\r\n // change in shouldFire\r\n if (results.shouldFire) {\r\n while (q.length > 0) {\r\n observer.onNext(q.shift());\r\n }\r\n }\r\n } else {\r\n // new data\r\n if (results.shouldFire) {\r\n observer.onNext(results.data);\r\n } else {\r\n q.push(results.data);\r\n }\r\n }\r\n previousShouldFire = results.shouldFire;\r\n\r\n }, \r\n function (err) {\r\n // Empty buffer before sending error\r\n while (q.length > 0) {\r\n observer.onNext(q.shift());\r\n }\r\n observer.onError(err);\r\n },\r\n function () {\r\n // Empty buffer before sending completion\r\n while (q.length > 0) {\r\n observer.onNext(q.shift());\r\n }\r\n observer.onCompleted(); \r\n }\r\n );\r\n\r\n this.subject.onNext(false);\r\n\r\n return subscription; \r\n }\r\n\r\n function PausableBufferedObservable(source, subject) {\r\n this.source = source;\r\n this.subject = subject || new Subject();\r\n this.isPaused = true;\r\n _super.call(this, subscribe);\r\n }\r\n\r\n PausableBufferedObservable.prototype.pause = function () {\r\n if (this.isPaused === true){\r\n return;\r\n }\r\n this.isPaused = true;\r\n this.subject.onNext(false);\r\n };\r\n\r\n PausableBufferedObservable.prototype.resume = function () {\r\n if (this.isPaused === false){\r\n return;\r\n }\r\n this.isPaused = false;\r\n this.subject.onNext(true);\r\n };\r\n\r\n return PausableBufferedObservable; \r\n\r\n }(Observable));\r\n\r\n /**\r\n * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,\r\n * and yields the values that were buffered while paused.\r\n * @example\r\n * var pauser = new Rx.Subject();\r\n * var source = Rx.Observable.interval(100).pausableBuffered(pauser);\r\n * @param {Observable} pauser The observable sequence used to pause the underlying sequence.\r\n * @returns {Observable} The observable sequence which is paused based upon the pauser.\r\n */ \r\n observableProto.pausableBuffered = function (subject) {\r\n return new PausableBufferedObservable(this, subject);\r\n };\r\n\r\n /**\r\n * Attaches a controller to the observable sequence with the ability to queue.\r\n * @example\r\n * var source = Rx.Observable.interval(100).controlled();\r\n * source.request(3); // Reads 3 values\r\n * @param {Observable} pauser The observable sequence used to pause the underlying sequence.\r\n * @returns {Observable} The observable sequence which is paused based upon the pauser.\r\n */ \r\n observableProto.controlled = function (enableQueue) {\r\n if (enableQueue == null) { enableQueue = true; }\r\n return new ControlledObservable(this, enableQueue);\r\n };\r\n var ControlledObservable = (function (_super) {\r\n\r\n inherits(ControlledObservable, _super);\r\n\r\n function subscribe (observer) {\r\n return this.source.subscribe(observer);\r\n }\r\n\r\n function ControlledObservable (source, enableQueue) {\r\n _super.call(this, subscribe);\r\n this.subject = new ControlledSubject(enableQueue);\r\n this.source = source.multicast(this.subject).refCount();\r\n }\r\n\r\n ControlledObservable.prototype.request = function (numberOfItems) {\r\n if (numberOfItems == null) { numberOfItems = -1; }\r\n return this.subject.request(numberOfItems);\r\n };\r\n\r\n return ControlledObservable;\r\n\r\n }(Observable));\r\n\r\n var ControlledSubject = Rx.ControlledSubject = (function (_super) {\r\n\r\n function subscribe (observer) {\r\n return this.subject.subscribe(observer);\r\n }\r\n\r\n inherits(ControlledSubject, _super);\r\n\r\n function ControlledSubject(enableQueue) {\r\n if (enableQueue == null) {\r\n enableQueue = true;\r\n }\r\n\r\n _super.call(this, subscribe);\r\n this.subject = new Subject();\r\n this.enableQueue = enableQueue;\r\n this.queue = enableQueue ? [] : null;\r\n this.requestedCount = 0;\r\n this.requestedDisposable = disposableEmpty;\r\n this.error = null;\r\n this.hasFailed = false;\r\n this.hasCompleted = false;\r\n this.controlledDisposable = disposableEmpty;\r\n }\r\n\r\n addProperties(ControlledSubject.prototype, Observer, {\r\n onCompleted: function () {\r\n checkDisposed.call(this);\r\n this.hasCompleted = true;\r\n\r\n if (!this.enableQueue || this.queue.length === 0) {\r\n this.subject.onCompleted();\r\n }\r\n },\r\n onError: function (error) {\r\n checkDisposed.call(this);\r\n this.hasFailed = true;\r\n this.error = error;\r\n\r\n if (!this.enableQueue || this.queue.length === 0) {\r\n this.subject.onError(error);\r\n } \r\n },\r\n onNext: function (value) {\r\n checkDisposed.call(this);\r\n var hasRequested = false;\r\n\r\n if (this.requestedCount === 0) {\r\n if (this.enableQueue) {\r\n this.queue.push(value);\r\n }\r\n } else {\r\n if (this.requestedCount !== -1) {\r\n if (this.requestedCount-- === 0) {\r\n this.disposeCurrentRequest();\r\n }\r\n }\r\n hasRequested = true;\r\n }\r\n\r\n if (hasRequested) {\r\n this.subject.onNext(value);\r\n }\r\n },\r\n _processRequest: function (numberOfItems) {\r\n if (this.enableQueue) {\r\n //console.log('queue length', this.queue.length);\r\n\r\n while (this.queue.length >= numberOfItems && numberOfItems > 0) {\r\n //console.log('number of items', numberOfItems);\r\n this.subject.onNext(this.queue.shift());\r\n numberOfItems--;\r\n }\r\n\r\n if (this.queue.length !== 0) {\r\n return { numberOfItems: numberOfItems, returnValue: true };\r\n } else {\r\n return { numberOfItems: numberOfItems, returnValue: false };\r\n }\r\n }\r\n\r\n if (this.hasFailed) {\r\n this.subject.onError(this.error);\r\n this.controlledDisposable.dispose();\r\n this.controlledDisposable = disposableEmpty;\r\n } else if (this.hasCompleted) {\r\n this.subject.onCompleted();\r\n this.controlledDisposable.dispose();\r\n this.controlledDisposable = disposableEmpty; \r\n }\r\n\r\n return { numberOfItems: numberOfItems, returnValue: false };\r\n },\r\n request: function (number) {\r\n checkDisposed.call(this);\r\n this.disposeCurrentRequest();\r\n var self = this,\r\n r = this._processRequest(number);\r\n\r\n number = r.numberOfItems;\r\n if (!r.returnValue) {\r\n this.requestedCount = number;\r\n this.requestedDisposable = disposableCreate(function () {\r\n self.requestedCount = 0;\r\n });\r\n\r\n return this.requestedDisposable\r\n } else {\r\n return disposableEmpty;\r\n }\r\n },\r\n disposeCurrentRequest: function () {\r\n this.requestedDisposable.dispose();\r\n this.requestedDisposable = disposableEmpty;\r\n },\r\n\r\n dispose: function () {\r\n this.isDisposed = true;\r\n this.error = null;\r\n this.subject.dispose();\r\n this.requestedDisposable.dispose();\r\n }\r\n });\r\n\r\n return ControlledSubject;\r\n }(Observable));\r\n /**\r\n * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each\r\n * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's\r\n * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.\r\n * \r\n * @example\r\n * 1 - res = source.multicast(observable);\r\n * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });\r\n * \r\n * @param {Function|Subject} subjectOrSubjectSelector \r\n * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.\r\n * Or:\r\n * Subject to push source elements into.\r\n * \r\n * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if 0;\r\n },\r\n /**\r\n * Notifies all subscribed observers about the end of the sequence.\r\n */ \r\n onCompleted: function () {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n this.isStopped = true;\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onCompleted();\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the exception.\r\n * @param {Mixed} error The exception to send to all observers.\r\n */ \r\n onError: function (error) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n this.isStopped = true;\r\n this.exception = error;\r\n\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onError(error);\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the arrival of the specified element in the sequence.\r\n * @param {Mixed} value The value to send to all observers.\r\n */ \r\n onNext: function (value) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.value = value;\r\n var os = this.observers.slice(0);\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onNext(value);\r\n }\r\n }\r\n },\r\n /**\r\n * Unsubscribe all observers and release resources.\r\n */ \r\n dispose: function () {\r\n this.isDisposed = true;\r\n this.observers = null;\r\n this.value = null;\r\n this.exception = null;\r\n }\r\n });\r\n\r\n return BehaviorSubject;\r\n }(Observable));\r\n\r\n /**\r\n * Represents an object that is both an observable sequence as well as an observer.\r\n * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.\r\n */ \r\n var ReplaySubject = Rx.ReplaySubject = (function (_super) {\r\n\r\n function RemovableDisposable (subject, observer) {\r\n this.subject = subject;\r\n this.observer = observer;\r\n };\r\n\r\n RemovableDisposable.prototype.dispose = function () {\r\n this.observer.dispose();\r\n if (!this.subject.isDisposed) {\r\n var idx = this.subject.observers.indexOf(this.observer);\r\n this.subject.observers.splice(idx, 1);\r\n }\r\n };\r\n\r\n function subscribe(observer) {\r\n var so = new ScheduledObserver(this.scheduler, observer),\r\n subscription = new RemovableDisposable(this, so);\r\n checkDisposed.call(this);\r\n this._trim(this.scheduler.now());\r\n this.observers.push(so);\r\n\r\n var n = this.q.length;\r\n\r\n for (var i = 0, len = this.q.length; i < len; i++) {\r\n so.onNext(this.q[i].value);\r\n }\r\n\r\n if (this.hasError) {\r\n n++;\r\n so.onError(this.error);\r\n } else if (this.isStopped) {\r\n n++;\r\n so.onCompleted();\r\n }\r\n\r\n so.ensureActive(n);\r\n return subscription;\r\n }\r\n\r\n inherits(ReplaySubject, _super);\r\n\r\n /**\r\n * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.\r\n * @param {Number} [bufferSize] Maximum element count of the replay buffer.\r\n * @param {Number} [windowSize] Maximum time length of the replay buffer.\r\n * @param {Scheduler} [scheduler] Scheduler the observers are invoked on.\r\n */\r\n function ReplaySubject(bufferSize, windowSize, scheduler) {\r\n this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;\r\n this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;\r\n this.scheduler = scheduler || currentThreadScheduler;\r\n this.q = [];\r\n this.observers = [];\r\n this.isStopped = false;\r\n this.isDisposed = false;\r\n this.hasError = false;\r\n this.error = null;\r\n _super.call(this, subscribe);\r\n }\r\n\r\n addProperties(ReplaySubject.prototype, Observer, {\r\n /**\r\n * Indicates whether the subject has observers subscribed to it.\r\n * @returns {Boolean} Indicates whether the subject has observers subscribed to it.\r\n */ \r\n hasObservers: function () {\r\n return this.observers.length > 0;\r\n }, \r\n /* @private */\r\n _trim: function (now) {\r\n while (this.q.length > this.bufferSize) {\r\n this.q.shift();\r\n }\r\n while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {\r\n this.q.shift();\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the arrival of the specified element in the sequence.\r\n * @param {Mixed} value The value to send to all observers.\r\n */ \r\n onNext: function (value) {\r\n var observer;\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var now = this.scheduler.now();\r\n this.q.push({ interval: now, value: value });\r\n this._trim(now);\r\n\r\n var o = this.observers.slice(0);\r\n for (var i = 0, len = o.length; i < len; i++) {\r\n observer = o[i];\r\n observer.onNext(value);\r\n observer.ensureActive();\r\n }\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the exception.\r\n * @param {Mixed} error The exception to send to all observers.\r\n */ \r\n onError: function (error) {\r\n var observer;\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n this.error = error;\r\n this.hasError = true;\r\n var now = this.scheduler.now();\r\n this._trim(now);\r\n var o = this.observers.slice(0);\r\n for (var i = 0, len = o.length; i < len; i++) {\r\n observer = o[i];\r\n observer.onError(error);\r\n observer.ensureActive();\r\n }\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the end of the sequence.\r\n */ \r\n onCompleted: function () {\r\n var observer;\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n var now = this.scheduler.now();\r\n this._trim(now);\r\n var o = this.observers.slice(0);\r\n for (var i = 0, len = o.length; i < len; i++) {\r\n observer = o[i];\r\n observer.onCompleted();\r\n observer.ensureActive();\r\n }\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Unsubscribe all observers and release resources.\r\n */ \r\n dispose: function () {\r\n this.isDisposed = true;\r\n this.observers = null;\r\n }\r\n });\r\n\r\n return ReplaySubject;\r\n }(Observable));\r\n\r\n var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {\r\n inherits(ConnectableObservable, __super__);\r\n\r\n function ConnectableObservable(source, subject) {\r\n var hasSubscription = false, \r\n subscription,\r\n sourceObservable = source.asObservable();\r\n\r\n this.connect = function () {\r\n if (!hasSubscription) {\r\n hasSubscription = true;\r\n subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {\r\n hasSubscription = false;\r\n }));\r\n }\r\n return subscription;\r\n };\r\n\r\n __super__.call(this, subject.subscribe.bind(subject));\r\n }\r\n \r\n ConnectableObservable.prototype.refCount = function () {\r\n var connectableSubscription, count = 0, source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var shouldConnect = ++count === 1,\r\n subscription = source.subscribe(observer);\r\n shouldConnect && (connectableSubscription = source.connect());\r\n return function () {\r\n subscription.dispose();\r\n --count === 0 && connectableSubscription.dispose();\r\n };\r\n });\r\n };\r\n\r\n return ConnectableObservable;\r\n }(Observable));\r\n \r\n var Dictionary = (function () {\r\n \r\n var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],\r\n noSuchkey = \"no such key\",\r\n duplicatekey = \"duplicate key\";\r\n\r\n function isPrime(candidate) {\r\n if (candidate & 1 === 0) { return candidate === 2; }\r\n var num1 = Math.sqrt(candidate),\r\n num2 = 3;\r\n while (num2 <= num1) {\r\n if (candidate % num2 === 0) { return false; }\r\n num2 += 2;\r\n }\r\n return true;\r\n }\r\n\r\n function getPrime(min) {\r\n var index, num, candidate;\r\n for (index = 0; index < primes.length; ++index) {\r\n num = primes[index];\r\n if (num >= min) { return num; }\r\n }\r\n candidate = min | 1;\r\n while (candidate < primes[primes.length - 1]) {\r\n if (isPrime(candidate)) { return candidate; }\r\n candidate += 2;\r\n }\r\n return min;\r\n }\r\n\r\n function stringHashFn(str) {\r\n var hash = 757602046;\r\n if (!str.length) { return hash; }\r\n for (var i = 0, len = str.length; i < len; i++) {\r\n var character = str.charCodeAt(i);\r\n hash = ((hash<<5)-hash)+character;\r\n hash = hash & hash;\r\n }\r\n return hash;\r\n }\r\n\r\n function numberHashFn(key) {\r\n var c2 = 0x27d4eb2d; \r\n key = (key ^ 61) ^ (key >>> 16);\r\n key = key + (key << 3);\r\n key = key ^ (key >>> 4);\r\n key = key * c2;\r\n key = key ^ (key >>> 15);\r\n return key;\r\n }\r\n\r\n var getHashCode = (function () {\r\n var uniqueIdCounter = 0;\r\n\r\n return function (obj) {\r\n if (obj == null) { throw new Error(noSuchkey); }\r\n\r\n // Check for built-ins before tacking on our own for any object\r\n if (typeof obj === 'string') { return stringHashFn(obj); }\r\n if (typeof obj === 'number') { return numberHashFn(obj); }\r\n if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }\r\n if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }\r\n if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }\r\n if (typeof obj.valueOf === 'function') {\r\n // Hack check for valueOf\r\n var valueOf = obj.valueOf();\r\n if (typeof valueOf === 'number') { return numberHashFn(valueOf); }\r\n if (typeof obj === 'string') { return stringHashFn(valueOf); }\r\n }\r\n if (obj.getHashCode) { return obj.getHashCode(); }\r\n\r\n var id = 17 * uniqueIdCounter++;\r\n obj.getHashCode = function () { return id; };\r\n return id;\r\n };\r\n }());\r\n\r\n function newEntry() {\r\n return { key: null, value: null, next: 0, hashCode: 0 };\r\n }\r\n\r\n function Dictionary(capacity, comparer) {\r\n if (capacity < 0) { throw new Error('out of range'); }\r\n if (capacity > 0) { this._initialize(capacity); }\r\n \r\n this.comparer = comparer || defaultComparer;\r\n this.freeCount = 0;\r\n this.size = 0;\r\n this.freeList = -1;\r\n }\r\n\r\n var dictionaryProto = Dictionary.prototype;\r\n\r\n dictionaryProto._initialize = function (capacity) {\r\n var prime = getPrime(capacity), i;\r\n this.buckets = new Array(prime);\r\n this.entries = new Array(prime);\r\n for (i = 0; i < prime; i++) {\r\n this.buckets[i] = -1;\r\n this.entries[i] = newEntry();\r\n }\r\n this.freeList = -1;\r\n };\r\n\r\n dictionaryProto.add = function (key, value) {\r\n return this._insert(key, value, true);\r\n };\r\n\r\n dictionaryProto._insert = function (key, value, add) {\r\n if (!this.buckets) { this._initialize(0); }\r\n var index3,\r\n num = getHashCode(key) & 2147483647,\r\n index1 = num % this.buckets.length;\r\n for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {\r\n if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {\r\n if (add) { throw new Error(duplicatekey); }\r\n this.entries[index2].value = value;\r\n return;\r\n }\r\n }\r\n if (this.freeCount > 0) {\r\n index3 = this.freeList;\r\n this.freeList = this.entries[index3].next;\r\n --this.freeCount;\r\n } else {\r\n if (this.size === this.entries.length) {\r\n this._resize();\r\n index1 = num % this.buckets.length;\r\n }\r\n index3 = this.size;\r\n ++this.size;\r\n }\r\n this.entries[index3].hashCode = num;\r\n this.entries[index3].next = this.buckets[index1];\r\n this.entries[index3].key = key;\r\n this.entries[index3].value = value;\r\n this.buckets[index1] = index3;\r\n };\r\n\r\n dictionaryProto._resize = function () {\r\n var prime = getPrime(this.size * 2),\r\n numArray = new Array(prime);\r\n for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }\r\n var entryArray = new Array(prime);\r\n for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }\r\n for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }\r\n for (var index1 = 0; index1 < this.size; ++index1) {\r\n var index2 = entryArray[index1].hashCode % prime;\r\n entryArray[index1].next = numArray[index2];\r\n numArray[index2] = index1;\r\n }\r\n this.buckets = numArray;\r\n this.entries = entryArray;\r\n };\r\n\r\n dictionaryProto.remove = function (key) {\r\n if (this.buckets) {\r\n var num = getHashCode(key) & 2147483647,\r\n index1 = num % this.buckets.length,\r\n index2 = -1;\r\n for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {\r\n if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {\r\n if (index2 < 0) {\r\n this.buckets[index1] = this.entries[index3].next;\r\n } else {\r\n this.entries[index2].next = this.entries[index3].next;\r\n }\r\n this.entries[index3].hashCode = -1;\r\n this.entries[index3].next = this.freeList;\r\n this.entries[index3].key = null;\r\n this.entries[index3].value = null;\r\n this.freeList = index3;\r\n ++this.freeCount;\r\n return true;\r\n } else {\r\n index2 = index3;\r\n }\r\n }\r\n }\r\n return false;\r\n };\r\n\r\n dictionaryProto.clear = function () {\r\n var index, len;\r\n if (this.size <= 0) { return; }\r\n for (index = 0, len = this.buckets.length; index < len; ++index) {\r\n this.buckets[index] = -1;\r\n }\r\n for (index = 0; index < this.size; ++index) {\r\n this.entries[index] = newEntry();\r\n }\r\n this.freeList = -1;\r\n this.size = 0;\r\n };\r\n\r\n dictionaryProto._findEntry = function (key) {\r\n if (this.buckets) {\r\n var num = getHashCode(key) & 2147483647;\r\n for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {\r\n if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {\r\n return index;\r\n }\r\n }\r\n }\r\n return -1;\r\n };\r\n\r\n dictionaryProto.count = function () {\r\n return this.size - this.freeCount;\r\n };\r\n\r\n dictionaryProto.tryGetValue = function (key) {\r\n var entry = this._findEntry(key);\r\n return entry >= 0 ?\r\n this.entries[entry].value :\r\n undefined;\r\n };\r\n\r\n dictionaryProto.getValues = function () {\r\n var index = 0, results = [];\r\n if (this.entries) {\r\n for (var index1 = 0; index1 < this.size; index1++) {\r\n if (this.entries[index1].hashCode >= 0) {\r\n results[index++] = this.entries[index1].value;\r\n }\r\n }\r\n }\r\n return results;\r\n };\r\n\r\n dictionaryProto.get = function (key) {\r\n var entry = this._findEntry(key);\r\n if (entry >= 0) { return this.entries[entry].value; }\r\n throw new Error(noSuchkey);\r\n };\r\n\r\n dictionaryProto.set = function (key, value) {\r\n this._insert(key, value, false);\r\n };\r\n\r\n dictionaryProto.containskey = function (key) {\r\n return this._findEntry(key) >= 0;\r\n };\r\n\r\n return Dictionary;\r\n }()); \r\n\r\n /**\r\n * Correlates the elements of two sequences based on overlapping durations.\r\n * \r\n * @param {Observable} right The right observable sequence to join elements for.\r\n * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.\r\n * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.\r\n * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.\r\n * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.\r\n */ \r\n observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {\r\n var left = this;\r\n return new AnonymousObservable(function (observer) {\r\n var group = new CompositeDisposable();\r\n var leftDone = false, rightDone = false;\r\n var leftId = 0, rightId = 0;\r\n var leftMap = new Dictionary(), rightMap = new Dictionary();\r\n\r\n group.add(left.subscribe(\r\n function (value) {\r\n var id = leftId++;\r\n var md = new SingleAssignmentDisposable();\r\n\r\n leftMap.add(id, value);\r\n group.add(md);\r\n \r\n var expire = function () {\r\n leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();\r\n group.remove(md);\r\n };\r\n \r\n var duration;\r\n try {\r\n duration = leftDurationSelector(value);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));\r\n\r\n rightMap.getValues().forEach(function (v) {\r\n var result;\r\n try {\r\n result = resultSelector(value, v);\r\n } catch (exn) {\r\n observer.onError(exn);\r\n return;\r\n }\r\n\r\n observer.onNext(result);\r\n });\r\n }, \r\n observer.onError.bind(observer), \r\n function () {\r\n leftDone = true;\r\n (rightDone || leftMap.count() === 0) && observer.onCompleted();\r\n })\r\n );\r\n\r\n group.add(right.subscribe(\r\n function (value) {\r\n var id = rightId++;\r\n var md = new SingleAssignmentDisposable();\r\n\r\n rightMap.add(id, value);\r\n group.add(md);\r\n\r\n var expire = function () {\r\n rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();\r\n group.remove(md);\r\n };\r\n\r\n var duration;\r\n try {\r\n duration = rightDurationSelector(value);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));\r\n\r\n leftMap.getValues().forEach(function (v) {\r\n var result;\r\n try {\r\n result = resultSelector(v, value);\r\n } catch(exn) {\r\n observer.onError(exn);\r\n return;\r\n }\r\n\r\n observer.onNext(result);\r\n });\r\n }, \r\n observer.onError.bind(observer), \r\n function () {\r\n rightDone = true;\r\n (leftDone || rightMap.count() === 0) && observer.onCompleted();\r\n })\r\n );\r\n return group;\r\n });\r\n };\r\n\r\n /**\r\n * Correlates the elements of two sequences based on overlapping durations, and groups the results.\r\n * \r\n * @param {Observable} right The right observable sequence to join elements for.\r\n * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.\r\n * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.\r\n * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.\r\n * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.\r\n */ \r\n observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {\r\n var left = this;\r\n return new AnonymousObservable(function (observer) {\r\n var group = new CompositeDisposable();\r\n var r = new RefCountDisposable(group);\r\n var leftMap = new Dictionary(), rightMap = new Dictionary();\r\n var leftId = 0, rightId = 0;\r\n\r\n function handleError(e) { return function (v) { v.onError(e); }; };\r\n\r\n group.add(left.subscribe(\r\n function (value) {\r\n var s = new Subject();\r\n var id = leftId++;\r\n leftMap.add(id, s);\r\n\r\n var result;\r\n try {\r\n result = resultSelector(value, addRef(s, r));\r\n } catch (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n observer.onNext(result);\r\n\r\n rightMap.getValues().forEach(function (v) { s.onNext(v); });\r\n\r\n var md = new SingleAssignmentDisposable();\r\n group.add(md);\r\n\r\n var expire = function () {\r\n leftMap.remove(id) && s.onCompleted();\r\n group.remove(md);\r\n };\r\n\r\n var duration;\r\n try {\r\n duration = leftDurationSelector(value);\r\n } catch (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n md.setDisposable(duration.take(1).subscribe(\r\n noop,\r\n function (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n },\r\n expire)\r\n );\r\n },\r\n function (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n },\r\n observer.onCompleted.bind(observer))\r\n );\r\n\r\n group.add(right.subscribe(\r\n function (value) {\r\n var id = rightId++;\r\n rightMap.add(id, value);\r\n\r\n var md = new SingleAssignmentDisposable();\r\n group.add(md);\r\n\r\n var expire = function () {\r\n rightMap.remove(id);\r\n group.remove(md);\r\n };\r\n\r\n var duration;\r\n try {\r\n duration = rightDurationSelector(value);\r\n } catch (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n return;\r\n }\r\n md.setDisposable(duration.take(1).subscribe(\r\n noop,\r\n function (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n },\r\n expire)\r\n );\r\n\r\n leftMap.getValues().forEach(function (v) { v.onNext(value); });\r\n },\r\n function (e) {\r\n leftMap.getValues().forEach(handleError(e));\r\n observer.onError(e);\r\n })\r\n );\r\n\r\n return r;\r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more buffers.\r\n * \r\n * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).\r\n * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.\r\n * @returns {Observable} An observable sequence of windows. \r\n */\r\n observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {\r\n return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more windows.\r\n * \r\n * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).\r\n * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.\r\n * @returns {Observable} An observable sequence of windows.\r\n */ \r\n observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {\r\n if (arguments.length === 1 && typeof arguments[0] !== 'function') {\r\n return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);\r\n }\r\n return typeof windowOpeningsOrClosingSelector === 'function' ?\r\n observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :\r\n observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);\r\n };\r\n \r\n function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {\r\n return windowOpenings.groupJoin(this, windowClosingSelector, function () {\r\n return observableEmpty();\r\n }, function (_, window) {\r\n return window;\r\n });\r\n }\r\n\r\n function observableWindowWithBounaries(windowBoundaries) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var window = new Subject(), \r\n d = new CompositeDisposable(), \r\n r = new RefCountDisposable(d);\r\n\r\n observer.onNext(addRef(window, r));\r\n\r\n d.add(source.subscribe(function (x) {\r\n window.onNext(x);\r\n }, function (err) {\r\n window.onError(err);\r\n observer.onError(err);\r\n }, function () {\r\n window.onCompleted();\r\n observer.onCompleted();\r\n }));\r\n\r\n d.add(windowBoundaries.subscribe(function (w) {\r\n window.onCompleted();\r\n window = new Subject();\r\n observer.onNext(addRef(window, r));\r\n }, function (err) {\r\n window.onError(err);\r\n observer.onError(err);\r\n }, function () {\r\n window.onCompleted();\r\n observer.onCompleted();\r\n }));\r\n\r\n return r;\r\n });\r\n }\r\n\r\n function observableWindowWithClosingSelector(windowClosingSelector) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var createWindowClose,\r\n m = new SerialDisposable(),\r\n d = new CompositeDisposable(m),\r\n r = new RefCountDisposable(d),\r\n window = new Subject();\r\n observer.onNext(addRef(window, r));\r\n d.add(source.subscribe(function (x) {\r\n window.onNext(x);\r\n }, function (ex) {\r\n window.onError(ex);\r\n observer.onError(ex);\r\n }, function () {\r\n window.onCompleted();\r\n observer.onCompleted();\r\n }));\r\n createWindowClose = function () {\r\n var m1, windowClose;\r\n try {\r\n windowClose = windowClosingSelector();\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n m1 = new SingleAssignmentDisposable();\r\n m.setDisposable(m1);\r\n m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) {\r\n window.onError(ex);\r\n observer.onError(ex);\r\n }, function () {\r\n window.onCompleted();\r\n window = new Subject();\r\n observer.onNext(addRef(window, r));\r\n createWindowClose();\r\n }));\r\n };\r\n createWindowClose();\r\n return r;\r\n });\r\n }\r\n\r\n /**\r\n * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. \r\n * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. \r\n * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.\r\n * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.\r\n */\r\n observableProto.pairwise = function () {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var previous, hasPrevious = false;\r\n return source.subscribe(\r\n function (x) {\r\n if (hasPrevious) {\r\n observer.onNext([previous, x]);\r\n } else {\r\n hasPrevious = true;\r\n }\r\n previous = x;\r\n },\r\n observer.onError.bind(observer),\r\n observer.onCompleted.bind(observer));\r\n });\r\n };\r\n /** \r\n * Returns two observables which partition the observations of the source by the given function.\r\n * The first will trigger observations for those values for which the predicate returns true. \r\n * The second will trigger observations for those values where the predicate returns false. \r\n * The predicate is executed once for each subscribed observer. \r\n * Both also propagate all error observations arising from the source and each completes \r\n * when the source completes.\r\n * @param {Function} predicate \r\n * The function to determine which output Observable will trigger a particular observation.\r\n * @returns {Array}\r\n * An array of observables. The first triggers when the predicate returns true, \r\n * and the second triggers when the predicate returns false.\r\n */\r\n observableProto.partition = function(predicate, thisArg) {\r\n var published = this.publish().refCount();\r\n return [ \r\n published.filter(predicate, thisArg), \r\n published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })\r\n ];\r\n };\r\n\r\n function enumerableWhile(condition, source) {\r\n return new Enumerable(function () {\r\n return new Enumerator(function () {\r\n return condition() ?\r\n { done: false, value: source } :\r\n { done: true, value: undefined }; \r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.\r\n * This operator allows for a fluent style of writing queries that use the same sequence multiple times.\r\n *\r\n * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.\r\n * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.\r\n */\r\n observableProto.letBind = observableProto['let'] = function (func) {\r\n return func(this);\r\n };\r\n\r\n /**\r\n * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) {\r\n isOwner = !isAcquired;\r\n isAcquired = true;\r\n }\r\n if (isOwner) {\r\n m.setDisposable(scheduler.scheduleRecursive(function (self) {\r\n var work;\r\n if (q.length > 0) {\r\n work = q.shift();\r\n } else {\r\n isAcquired = false;\r\n return;\r\n }\r\n var m1 = new SingleAssignmentDisposable();\r\n d.add(m1);\r\n m1.setDisposable(work.subscribe(function (x) {\r\n observer.onNext(x);\r\n var result = null;\r\n try {\r\n result = selector(x);\r\n } catch (e) {\r\n observer.onError(e);\r\n }\r\n q.push(result);\r\n activeCount++;\r\n ensureActive();\r\n }, observer.onError.bind(observer), function () {\r\n d.remove(m1);\r\n activeCount--;\r\n if (activeCount === 0) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n self();\r\n }));\r\n }\r\n };\r\n\r\n q.push(source);\r\n activeCount++;\r\n ensureActive();\r\n return d;\r\n });\r\n };\r\n\r\n /**\r\n * Runs all observable sequences in parallel and collect their last elements.\r\n * \r\n * @example\r\n * 1 - res = Rx.Observable.forkJoin([obs1, obs2]);\r\n * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); \r\n * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.\r\n */\r\n Observable.forkJoin = function () {\r\n var allSources = argsOrArray(arguments, 0);\r\n return new AnonymousObservable(function (subscriber) {\r\n var count = allSources.length;\r\n if (count === 0) {\r\n subscriber.onCompleted();\r\n return disposableEmpty;\r\n }\r\n var group = new CompositeDisposable(),\r\n finished = false,\r\n hasResults = new Array(count),\r\n hasCompleted = new Array(count),\r\n results = new Array(count);\r\n\r\n for (var idx = 0; idx < count; idx++) {\r\n (function (i) {\r\n var source = allSources[i];\r\n isPromise(source) && (source = observableFromPromise(source));\r\n group.add(\r\n source.subscribe(\r\n function (value) {\r\n if (!finished) {\r\n hasResults[i] = true;\r\n results[i] = value;\r\n }\r\n }, \r\n function (e) {\r\n finished = true;\r\n subscriber.onError(e);\r\n group.dispose();\r\n }, \r\n function () {\r\n if (!finished) {\r\n if (!hasResults[i]) {\r\n subscriber.onCompleted();\r\n return;\r\n }\r\n hasCompleted[i] = true;\r\n for (var ix = 0; ix < count; ix++) {\r\n if (!hasCompleted[ix]) { return; }\r\n }\r\n finished = true;\r\n subscriber.onNext(results);\r\n subscriber.onCompleted();\r\n }\r\n }));\r\n })(idx);\r\n }\r\n\r\n return group;\r\n });\r\n };\r\n\r\n /**\r\n * Runs two observable sequences in parallel and combines their last elemenets.\r\n *\r\n * @param {Observable} second Second observable sequence.\r\n * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.\r\n * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.\r\n */\r\n observableProto.forkJoin = function (second, resultSelector) {\r\n var first = this;\r\n\r\n return new AnonymousObservable(function (observer) {\r\n var leftStopped = false, rightStopped = false,\r\n hasLeft = false, hasRight = false,\r\n lastLeft, lastRight,\r\n leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();\r\n\r\n isPromise(second) && (second = observableFromPromise(second));\r\n\r\n leftSubscription.setDisposable(\r\n first.subscribe(function (left) {\r\n hasLeft = true;\r\n lastLeft = left;\r\n }, function (err) {\r\n rightSubscription.dispose();\r\n observer.onError(err);\r\n }, function () {\r\n leftStopped = true;\r\n if (rightStopped) {\r\n if (!hasLeft) {\r\n observer.onCompleted();\r\n } else if (!hasRight) {\r\n observer.onCompleted();\r\n } else {\r\n var result;\r\n try {\r\n result = resultSelector(lastLeft, lastRight);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n observer.onNext(result);\r\n observer.onCompleted();\r\n }\r\n }\r\n })\r\n );\r\n\r\n rightSubscription.setDisposable(\r\n second.subscribe(function (right) {\r\n hasRight = true;\r\n lastRight = right;\r\n }, function (err) {\r\n leftSubscription.dispose();\r\n observer.onError(err);\r\n }, function () {\r\n rightStopped = true;\r\n if (leftStopped) {\r\n if (!hasLeft) {\r\n observer.onCompleted();\r\n } else if (!hasRight) {\r\n observer.onCompleted();\r\n } else {\r\n var result;\r\n try {\r\n result = resultSelector(lastLeft, lastRight);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n observer.onNext(result);\r\n observer.onCompleted();\r\n }\r\n }\r\n })\r\n );\r\n\r\n return new CompositeDisposable(leftSubscription, rightSubscription);\r\n });\r\n };\r\n\r\n /**\r\n * Comonadic bind operator.\r\n * @param {Function} selector A transform function to apply to each element.\r\n * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.\r\n * @returns {Observable} An observable sequence which results from the comonadic bind operation.\r\n */\r\n observableProto.manySelect = function (selector, scheduler) {\r\n isScheduler(scheduler) || (scheduler = immediateScheduler);\r\n var source = this;\r\n return observableDefer(function () {\r\n var chain;\r\n\r\n return source\r\n .map(function (x) {\r\n var curr = new ChainObservable(x);\r\n\r\n chain && chain.onNext(x);\r\n chain = curr;\r\n\r\n return curr;\r\n })\r\n .tap(\r\n noop,\r\n function (e) { chain && chain.onError(e); },\r\n function () { chain && chain.onCompleted(); }\r\n )\r\n .observeOn(scheduler)\r\n .map(selector);\r\n });\r\n };\r\n\r\n var ChainObservable = (function (__super__) {\r\n\r\n function subscribe (observer) {\r\n var self = this, g = new CompositeDisposable();\r\n g.add(currentThreadScheduler.schedule(function () {\r\n observer.onNext(self.head);\r\n g.add(self.tail.mergeObservable().subscribe(observer));\r\n }));\r\n\r\n return g;\r\n }\r\n\r\n inherits(ChainObservable, __super__);\r\n\r\n function ChainObservable(head) {\r\n __super__.call(this, subscribe);\r\n this.head = head;\r\n this.tail = new AsyncSubject();\r\n }\r\n\r\n addProperties(ChainObservable.prototype, Observer, {\r\n onCompleted: function () {\r\n this.onNext(Observable.empty());\r\n },\r\n onError: function (e) {\r\n this.onNext(Observable.throwException(e));\r\n },\r\n onNext: function (v) {\r\n this.tail.onNext(v);\r\n this.tail.onCompleted();\r\n }\r\n });\r\n\r\n return ChainObservable;\r\n\r\n }(Observable));\r\n\r\n /** @private */\r\n var Map = (function () {\r\n\r\n /**\r\n * @constructor\r\n * @private\r\n */\r\n function Map() {\r\n this.keys = [];\r\n this.values = [];\r\n }\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */\r\n Map.prototype['delete'] = function (key) {\r\n var i = this.keys.indexOf(key);\r\n if (i !== -1) {\r\n this.keys.splice(i, 1);\r\n this.values.splice(i, 1);\r\n }\r\n return i !== -1;\r\n };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */\r\n Map.prototype.get = function (key, fallback) {\r\n var i = this.keys.indexOf(key);\r\n return i !== -1 ? this.values[i] : fallback;\r\n };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */\r\n Map.prototype.set = function (key, value) {\r\n var i = this.keys.indexOf(key);\r\n if (i !== -1) {\r\n this.values[i] = value;\r\n }\r\n this.values[this.keys.push(key) - 1] = value;\r\n };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */\r\n Map.prototype.size = function () { return this.keys.length; };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */ \r\n Map.prototype.has = function (key) {\r\n return this.keys.indexOf(key) !== -1;\r\n };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */ \r\n Map.prototype.getKeys = function () { return this.keys.slice(0); };\r\n\r\n /**\r\n * @private\r\n * @memberOf Map#\r\n */ \r\n Map.prototype.getValues = function () { return this.values.slice(0); };\r\n\r\n return Map;\r\n }());\r\n\r\n /**\r\n * @constructor\r\n * Represents a join pattern over observable sequences.\r\n */\r\n function Pattern(patterns) {\r\n this.patterns = patterns;\r\n }\r\n\r\n /**\r\n * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.\r\n * \r\n * @param other Observable sequence to match in addition to the current pattern.\r\n * @return Pattern object that matches when all observable sequences in the pattern have an available value. \r\n */ \r\n Pattern.prototype.and = function (other) {\r\n var patterns = this.patterns.slice(0);\r\n patterns.push(other);\r\n return new Pattern(patterns);\r\n };\r\n\r\n /**\r\n * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.\r\n * \r\n * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.\r\n * @return Plan that produces the projected values, to be fed (with other plans) to the when operator.\r\n */\r\n Pattern.prototype.thenDo = function (selector) {\r\n return new Plan(this, selector);\r\n };\r\n\r\n function Plan(expression, selector) {\r\n this.expression = expression;\r\n this.selector = selector;\r\n }\r\n \r\n Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {\r\n var self = this;\r\n var joinObservers = [];\r\n for (var i = 0, len = this.expression.patterns.length; i < len; i++) {\r\n joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));\r\n }\r\n var activePlan = new ActivePlan(joinObservers, function () {\r\n var result;\r\n try {\r\n result = self.selector.apply(self, arguments);\r\n } catch (exception) {\r\n observer.onError(exception);\r\n return;\r\n }\r\n observer.onNext(result);\r\n }, function () {\r\n for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {\r\n joinObservers[j].removeActivePlan(activePlan);\r\n }\r\n deactivate(activePlan);\r\n });\r\n for (i = 0, len = joinObservers.length; i < len; i++) {\r\n joinObservers[i].addActivePlan(activePlan);\r\n }\r\n return activePlan;\r\n };\r\n\r\n function planCreateObserver(externalSubscriptions, observable, onError) {\r\n var entry = externalSubscriptions.get(observable);\r\n if (!entry) {\r\n var observer = new JoinObserver(observable, onError);\r\n externalSubscriptions.set(observable, observer);\r\n return observer;\r\n }\r\n return entry;\r\n }\r\n\r\n // Active Plan\r\n function ActivePlan(joinObserverArray, onNext, onCompleted) {\r\n var i, joinObserver;\r\n this.joinObserverArray = joinObserverArray;\r\n this.onNext = onNext;\r\n this.onCompleted = onCompleted;\r\n this.joinObservers = new Map();\r\n for (i = 0; i < this.joinObserverArray.length; i++) {\r\n joinObserver = this.joinObserverArray[i];\r\n this.joinObservers.set(joinObserver, joinObserver);\r\n }\r\n }\r\n\r\n ActivePlan.prototype.dequeue = function () {\r\n var values = this.joinObservers.getValues();\r\n for (var i = 0, len = values.length; i < len; i++) {\r\n values[i].queue.shift();\r\n }\r\n };\r\n ActivePlan.prototype.match = function () {\r\n var firstValues, i, len, isCompleted, values, hasValues = true;\r\n for (i = 0, len = this.joinObserverArray.length; i < len; i++) {\r\n if (this.joinObserverArray[i].queue.length === 0) {\r\n hasValues = false;\r\n break;\r\n }\r\n }\r\n if (hasValues) {\r\n firstValues = [];\r\n isCompleted = false;\r\n for (i = 0, len = this.joinObserverArray.length; i < len; i++) {\r\n firstValues.push(this.joinObserverArray[i].queue[0]);\r\n if (this.joinObserverArray[i].queue[0].kind === 'C') {\r\n isCompleted = true;\r\n }\r\n }\r\n if (isCompleted) {\r\n this.onCompleted();\r\n } else {\r\n this.dequeue();\r\n values = [];\r\n for (i = 0; i < firstValues.length; i++) {\r\n values.push(firstValues[i].value);\r\n }\r\n this.onNext.apply(this, values);\r\n }\r\n }\r\n };\r\n\r\n /** @private */\r\n var JoinObserver = (function (_super) {\r\n\r\n inherits(JoinObserver, _super);\r\n\r\n /**\r\n * @constructor\r\n * @private\r\n */\r\n function JoinObserver(source, onError) {\r\n _super.call(this);\r\n this.source = source;\r\n this.onError = onError;\r\n this.queue = [];\r\n this.activePlans = [];\r\n this.subscription = new SingleAssignmentDisposable();\r\n this.isDisposed = false;\r\n }\r\n\r\n var JoinObserverPrototype = JoinObserver.prototype;\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */\r\n JoinObserverPrototype.next = function (notification) {\r\n if (!this.isDisposed) {\r\n if (notification.kind === 'E') {\r\n this.onError(notification.exception);\r\n return;\r\n }\r\n this.queue.push(notification);\r\n var activePlans = this.activePlans.slice(0);\r\n for (var i = 0, len = activePlans.length; i < len; i++) {\r\n activePlans[i].match();\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */ \r\n JoinObserverPrototype.error = noop;\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */ \r\n JoinObserverPrototype.completed = noop;\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */\r\n JoinObserverPrototype.addActivePlan = function (activePlan) {\r\n this.activePlans.push(activePlan);\r\n };\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */ \r\n JoinObserverPrototype.subscribe = function () {\r\n this.subscription.setDisposable(this.source.materialize().subscribe(this));\r\n };\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */ \r\n JoinObserverPrototype.removeActivePlan = function (activePlan) {\r\n var idx = this.activePlans.indexOf(activePlan);\r\n this.activePlans.splice(idx, 1);\r\n if (this.activePlans.length === 0) {\r\n this.dispose();\r\n }\r\n };\r\n\r\n /**\r\n * @memberOf JoinObserver#\r\n * @private\r\n */ \r\n JoinObserverPrototype.dispose = function () {\r\n _super.prototype.dispose.call(this);\r\n if (!this.isDisposed) {\r\n this.isDisposed = true;\r\n this.subscription.dispose();\r\n }\r\n };\r\n \r\n return JoinObserver;\r\n } (AbstractObserver));\r\n\r\n /**\r\n * Creates a pattern that matches when both observable sequences have an available value.\r\n * \r\n * @param right Observable sequence to match with the current sequence.\r\n * @return {Pattern} Pattern object that matches when both observable sequences have an available value. \r\n */\r\n observableProto.and = function (right) {\r\n return new Pattern([this, right]);\r\n };\r\n\r\n /**\r\n * Matches when the observable sequence has an available value and projects the value.\r\n * \r\n * @param selector Selector that will be invoked for values in the source sequence.\r\n * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. \r\n */ \r\n observableProto.thenDo = function (selector) {\r\n return new Pattern([this]).thenDo(selector);\r\n };\r\n\r\n /**\r\n * Joins together the results from several patterns.\r\n * \r\n * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.\r\n * @returns {Observable} Observable sequence with the results form matching several patterns. \r\n */\r\n Observable.when = function () {\r\n var plans = argsOrArray(arguments, 0);\r\n return new AnonymousObservable(function (observer) {\r\n var activePlans = [],\r\n externalSubscriptions = new Map(),\r\n group,\r\n i, len,\r\n joinObserver,\r\n joinValues,\r\n outObserver;\r\n outObserver = observerCreate(observer.onNext.bind(observer), function (exception) {\r\n var values = externalSubscriptions.getValues();\r\n for (var j = 0, jlen = values.length; j < jlen; j++) {\r\n values[j].onError(exception);\r\n }\r\n observer.onError(exception);\r\n }, observer.onCompleted.bind(observer));\r\n try {\r\n for (i = 0, len = plans.length; i < len; i++) {\r\n activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {\r\n var idx = activePlans.indexOf(activePlan);\r\n activePlans.splice(idx, 1);\r\n if (activePlans.length === 0) {\r\n outObserver.onCompleted();\r\n }\r\n }));\r\n }\r\n } catch (e) {\r\n observableThrow(e).subscribe(observer);\r\n }\r\n group = new CompositeDisposable();\r\n joinValues = externalSubscriptions.getValues();\r\n for (i = 0, len = joinValues.length; i < len; i++) {\r\n joinObserver = joinValues[i];\r\n joinObserver.subscribe();\r\n group.add(joinObserver);\r\n }\r\n return group;\r\n });\r\n };\r\n\r\n function observableTimerDate(dueTime, scheduler) {\r\n return new AnonymousObservable(function (observer) {\r\n return scheduler.scheduleWithAbsolute(dueTime, function () {\r\n observer.onNext(0);\r\n observer.onCompleted();\r\n });\r\n });\r\n }\r\n\r\n function observableTimerDateAndPeriod(dueTime, period, scheduler) {\r\n return new AnonymousObservable(function (observer) {\r\n var count = 0, d = dueTime, p = normalizeTime(period);\r\n return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {\r\n if (p > 0) {\r\n var now = scheduler.now();\r\n d = d + p;\r\n d <= now && (d = now + p);\r\n }\r\n observer.onNext(count++);\r\n self(d);\r\n });\r\n });\r\n }\r\n\r\n function observableTimerTimeSpan(dueTime, scheduler) {\r\n return new AnonymousObservable(function (observer) {\r\n return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {\r\n observer.onNext(0);\r\n observer.onCompleted();\r\n });\r\n });\r\n }\r\n\r\n function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {\r\n return dueTime === period ?\r\n new AnonymousObservable(function (observer) {\r\n return scheduler.schedulePeriodicWithState(0, period, function (count) {\r\n observer.onNext(count);\r\n return count + 1;\r\n });\r\n }) :\r\n observableDefer(function () {\r\n return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);\r\n });\r\n }\r\n\r\n /**\r\n * Returns an observable sequence that produces a value after each period.\r\n * \r\n * @example\r\n * 1 - res = Rx.Observable.interval(1000);\r\n * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);\r\n * \r\n * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).\r\n * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.\r\n * @returns {Observable} An observable sequence that produces a value after each period.\r\n */\r\n var observableinterval = Observable.interval = function (period, scheduler) {\r\n return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);\r\n };\r\n\r\n /**\r\n * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.\r\n * \r\n * @example\r\n * 1 - res = Rx.Observable.timer(new Date());\r\n * 2 - res = Rx.Observable.timer(new Date(), 1000);\r\n * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);\r\n * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);\r\n * \r\n * 5 - res = Rx.Observable.timer(5000);\r\n * 6 - res = Rx.Observable.timer(5000, 1000);\r\n * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);\r\n * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);\r\n * \r\n * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.\r\n * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.\r\n * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.\r\n */\r\n var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {\r\n var period;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {\r\n period = periodOrScheduler;\r\n } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {\r\n scheduler = periodOrScheduler;\r\n }\r\n if (dueTime instanceof Date && period === undefined) {\r\n return observableTimerDate(dueTime.getTime(), scheduler);\r\n }\r\n if (dueTime instanceof Date && period !== undefined) {\r\n period = periodOrScheduler;\r\n return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);\r\n }\r\n return period === undefined ?\r\n observableTimerTimeSpan(dueTime, scheduler) :\r\n observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);\r\n };\r\n\r\n function observableDelayTimeSpan(source, dueTime, scheduler) {\r\n return new AnonymousObservable(function (observer) {\r\n var active = false,\r\n cancelable = new SerialDisposable(),\r\n exception = null,\r\n q = [],\r\n running = false,\r\n subscription;\r\n subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {\r\n var d, shouldRun;\r\n if (notification.value.kind === 'E') {\r\n q = [];\r\n q.push(notification);\r\n exception = notification.value.exception;\r\n shouldRun = !running;\r\n } else {\r\n q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });\r\n shouldRun = !active;\r\n active = true;\r\n }\r\n if (shouldRun) {\r\n if (exception !== null) {\r\n observer.onError(exception);\r\n } else {\r\n d = new SingleAssignmentDisposable();\r\n cancelable.setDisposable(d);\r\n d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {\r\n var e, recurseDueTime, result, shouldRecurse;\r\n if (exception !== null) {\r\n return;\r\n }\r\n running = true;\r\n do {\r\n result = null;\r\n if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {\r\n result = q.shift().value;\r\n }\r\n if (result !== null) {\r\n result.accept(observer);\r\n }\r\n } while (result !== null);\r\n shouldRecurse = false;\r\n recurseDueTime = 0;\r\n if (q.length > 0) {\r\n shouldRecurse = true;\r\n recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());\r\n } else {\r\n active = false;\r\n }\r\n e = exception;\r\n running = false;\r\n if (e !== null) {\r\n observer.onError(e);\r\n } else if (shouldRecurse) {\r\n self(recurseDueTime);\r\n }\r\n }));\r\n }\r\n }\r\n });\r\n return new CompositeDisposable(subscription, cancelable);\r\n });\r\n }\r\n\r\n function observableDelayDate(source, dueTime, scheduler) {\r\n return observableDefer(function () {\r\n return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);\r\n });\r\n }\r\n\r\n /**\r\n * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.\r\n * \r\n * @example\r\n * 1 - res = Rx.Observable.delay(new Date());\r\n * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);\r\n * \r\n * 3 - res = Rx.Observable.delay(5000);\r\n * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);\r\n * @memberOf Observable#\r\n * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.\r\n * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} Time-shifted sequence.\r\n */\r\n observableProto.delay = function (dueTime, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return dueTime instanceof Date ?\r\n observableDelayDate(this, dueTime.getTime(), scheduler) :\r\n observableDelayTimeSpan(this, dueTime, scheduler);\r\n };\r\n\r\n /**\r\n * Ignores values from an observable sequence which are followed by another value before dueTime.\r\n * \r\n * @example\r\n * 1 - res = source.throttle(5000); // 5 seconds\r\n * 2 - res = source.throttle(5000, scheduler); \r\n * \r\n * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).\r\n * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} The throttled sequence.\r\n */\r\n observableProto.throttle = function (dueTime, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more windows which are produced based on timing information.\r\n * \r\n * @example\r\n * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second\r\n * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds\r\n * \r\n * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).\r\n * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.\r\n * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence of windows.\r\n */\r\n observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {\r\n var source = this, timeShift;\r\n\r\n timeShiftOrScheduler == null && (timeShift = timeSpan);\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n if (typeof timeShiftOrScheduler === 'number') {\r\n timeShift = timeShiftOrScheduler;\r\n } else if (typeof timeShiftOrScheduler === 'object') {\r\n timeShift = timeSpan;\r\n scheduler = timeShiftOrScheduler;\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var groupDisposable,\r\n nextShift = timeShift,\r\n nextSpan = timeSpan,\r\n q = [],\r\n refCountDisposable,\r\n timerD = new SerialDisposable(),\r\n totalTime = 0;\r\n groupDisposable = new CompositeDisposable(timerD),\r\n refCountDisposable = new RefCountDisposable(groupDisposable);\r\n\r\n\r\n q.push(new Subject());\r\n observer.onNext(addRef(q[0], refCountDisposable));\r\n createTimer();\r\n groupDisposable.add(source.subscribe(function (x) {\r\n var i, len;\r\n for (i = 0, len = q.length; i < len; i++) {\r\n q[i].onNext(x);\r\n }\r\n }, function (e) {\r\n var i, len;\r\n for (i = 0, len = q.length; i < len; i++) {\r\n q[i].onError(e);\r\n }\r\n observer.onError(e);\r\n }, function () {\r\n var i, len;\r\n for (i = 0, len = q.length; i < len; i++) {\r\n q[i].onCompleted();\r\n }\r\n observer.onCompleted();\r\n }));\r\n\r\n return refCountDisposable;\r\n\r\n function createTimer () {\r\n var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false;\r\n timerD.setDisposable(m);\r\n\r\n if (nextSpan === nextShift) {\r\n isSpan = true;\r\n isShift = true;\r\n } else if (nextSpan < nextShift) {\r\n isSpan = true;\r\n } else {\r\n isShift = true;\r\n }\r\n\r\n var newTotalTime = isSpan ? nextSpan : nextShift,\r\n ts = newTotalTime - totalTime;\r\n totalTime = newTotalTime;\r\n isSpan && (nextSpan += timeShift);\r\n isShift && (nextShift += timeShift);\r\n\r\n m.setDisposable(scheduler.scheduleWithRelative(ts, function () {\r\n var s;\r\n if (isShift) {\r\n s = new Subject();\r\n q.push(s);\r\n observer.onNext(addRef(s, refCountDisposable));\r\n }\r\n if (isSpan) {\r\n s = q.shift();\r\n s.onCompleted();\r\n }\r\n createTimer();\r\n }));\r\n } \r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.\r\n * @example\r\n * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items\r\n * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items\r\n * \r\n * @memberOf Observable#\r\n * @param {Number} timeSpan Maximum time length of a window.\r\n * @param {Number} count Maximum element count of a window.\r\n * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence of windows.\r\n */\r\n observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var createTimer,\r\n groupDisposable,\r\n n = 0,\r\n refCountDisposable,\r\n s = new Subject()\r\n timerD = new SerialDisposable(),\r\n windowId = 0;\r\n groupDisposable = new CompositeDisposable(timerD);\r\n refCountDisposable = new RefCountDisposable(groupDisposable);\r\n\r\n observer.onNext(addRef(s, refCountDisposable));\r\n createTimer(0);\r\n groupDisposable.add(source.subscribe(function (x) {\r\n var newId = 0, newWindow = false;\r\n s.onNext(x);\r\n n++;\r\n if (n === count) {\r\n newWindow = true;\r\n n = 0;\r\n newId = ++windowId;\r\n s.onCompleted();\r\n s = new Subject();\r\n observer.onNext(addRef(s, refCountDisposable));\r\n }\r\n newWindow && createTimer(newId);\r\n }, function (e) {\r\n s.onError(e);\r\n observer.onError(e);\r\n }, function () {\r\n s.onCompleted();\r\n observer.onCompleted();\r\n })); \r\n\r\n return refCountDisposable; \r\n\r\n function createTimer(id) {\r\n var m = new SingleAssignmentDisposable();\r\n timerD.setDisposable(m);\r\n m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {\r\n var newId;\r\n if (id !== windowId) { return; }\r\n n = 0;\r\n newId = ++windowId;\r\n s.onCompleted();\r\n s = new Subject();\r\n observer.onNext(addRef(s, refCountDisposable));\r\n createTimer(newId);\r\n }));\r\n } \r\n });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.\r\n * \r\n * @example\r\n * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second\r\n * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds\r\n * \r\n * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).\r\n * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.\r\n * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence of buffers.\r\n */\r\n observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {\r\n return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });\r\n };\r\n\r\n /**\r\n * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.\r\n * \r\n * @example\r\n * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array \r\n * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array\r\n * \r\n * @param {Number} timeSpan Maximum time length of a buffer.\r\n * @param {Number} count Maximum element count of a buffer.\r\n * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence of buffers.\r\n */\r\n observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {\r\n return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {\r\n return x.toArray();\r\n });\r\n };\r\n\r\n /**\r\n * Records the time interval between consecutive values in an observable sequence.\r\n * \r\n * @example\r\n * 1 - res = source.timeInterval();\r\n * 2 - res = source.timeInterval(Rx.Scheduler.timeout);\r\n * \r\n * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence with time interval information on values.\r\n */\r\n observableProto.timeInterval = function (scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return observableDefer(function () {\r\n var last = scheduler.now();\r\n return source.map(function (x) {\r\n var now = scheduler.now(), span = now - last;\r\n last = now;\r\n return { value: x, interval: span };\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Records the timestamp for each value in an observable sequence.\r\n * \r\n * @example\r\n * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }\r\n * 2 - res = source.timestamp(Rx.Scheduler.timeout);\r\n * \r\n * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} An observable sequence with timestamp information on values.\r\n */\r\n observableProto.timestamp = function (scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return this.map(function (x) {\r\n return { value: x, timestamp: scheduler.now() };\r\n });\r\n };\r\n\r\n function sampleObservable(source, sampler) {\r\n \r\n return new AnonymousObservable(function (observer) {\r\n var atEnd, value, hasValue;\r\n\r\n function sampleSubscribe() {\r\n if (hasValue) {\r\n hasValue = false;\r\n observer.onNext(value);\r\n }\r\n atEnd && observer.onCompleted();\r\n }\r\n\r\n return new CompositeDisposable(\r\n source.subscribe(function (newValue) {\r\n hasValue = true;\r\n value = newValue;\r\n }, observer.onError.bind(observer), function () {\r\n atEnd = true;\r\n }),\r\n sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)\r\n );\r\n });\r\n }\r\n\r\n /**\r\n * Samples the observable sequence at each interval.\r\n * \r\n * @example\r\n * 1 - res = source.sample(sampleObservable); // Sampler tick sequence\r\n * 2 - res = source.sample(5000); // 5 seconds\r\n * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds\r\n * \r\n * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.\r\n * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} Sampled observable sequence.\r\n */\r\n observableProto.sample = function (intervalOrSampler, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return typeof intervalOrSampler === 'number' ?\r\n sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :\r\n sampleObservable(this, intervalOrSampler);\r\n };\r\n\r\n /**\r\n * Returns the source observable sequence or the other observable sequence if dueTime elapses.\r\n * \r\n * @example\r\n * 1 - res = source.timeout(new Date()); // As a date\r\n * 2 - res = source.timeout(5000); // 5 seconds\r\n * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable\r\n * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable\r\n * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable\r\n * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable\r\n * \r\n * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.\r\n * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.\r\n * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} The source sequence switching to the other sequence in case of a timeout.\r\n */\r\n observableProto.timeout = function (dueTime, other, scheduler) {\r\n other || (other = observableThrow(new Error('Timeout')));\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n \r\n var source = this, schedulerMethod = dueTime instanceof Date ?\r\n 'scheduleWithAbsolute' :\r\n 'scheduleWithRelative';\r\n\r\n return new AnonymousObservable(function (observer) {\r\n var id = 0,\r\n original = new SingleAssignmentDisposable(),\r\n subscription = new SerialDisposable(),\r\n switched = false,\r\n timer = new SerialDisposable();\r\n\r\n subscription.setDisposable(original);\r\n\r\n var createTimer = function () {\r\n var myId = id;\r\n timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {\r\n if (id === myId) {\r\n isPromise(other) && (other = observableFromPromise(other));\r\n subscription.setDisposable(other.subscribe(observer));\r\n }\r\n }));\r\n };\r\n\r\n createTimer();\r\n \r\n original.setDisposable(source.subscribe(function (x) {\r\n if (!switched) {\r\n id++;\r\n observer.onNext(x);\r\n createTimer();\r\n }\r\n }, function (e) {\r\n if (!switched) {\r\n id++;\r\n observer.onError(e);\r\n }\r\n }, function () {\r\n if (!switched) {\r\n id++;\r\n observer.onCompleted();\r\n }\r\n }));\r\n return new CompositeDisposable(subscription, timer);\r\n });\r\n };\r\n\r\n /**\r\n * Generates an observable sequence by iterating a state from an initial state until the condition fails.\r\n * \r\n * @example\r\n * res = source.generateWithAbsoluteTime(0, \r\n * function (x) { return return true; }, \r\n * function (x) { return x + 1; }, \r\n * function (x) { return x; }, \r\n * function (x) { return new Date(); }\r\n * });\r\n * \r\n * @param {Mixed} initialState Initial state.\r\n * @param {Function} condition Condition to terminate generation (upon returning false).\r\n * @param {Function} iterate Iteration step function.\r\n * @param {Function} resultSelector Selector function for results produced in the sequence.\r\n * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.\r\n * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} The generated sequence.\r\n */\r\n Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var first = true,\r\n hasResult = false,\r\n result,\r\n state = initialState,\r\n time;\r\n return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {\r\n hasResult && observer.onNext(result);\r\n \r\n try {\r\n if (first) {\r\n first = false;\r\n } else {\r\n state = iterate(state);\r\n }\r\n hasResult = condition(state);\r\n if (hasResult) {\r\n result = resultSelector(state);\r\n time = timeSelector(state);\r\n }\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (hasResult) {\r\n self(time);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Generates an observable sequence by iterating a state from an initial state until the condition fails.\r\n * \r\n * @example \r\n * res = source.generateWithRelativeTime(0, \r\n * function (x) { return return true; }, \r\n * function (x) { return x + 1; }, \r\n * function (x) { return x; }, \r\n * function (x) { return 500; }\r\n * );\r\n * \r\n * @param {Mixed} initialState Initial state.\r\n * @param {Function} condition Condition to terminate generation (upon returning false).\r\n * @param {Function} iterate Iteration step function.\r\n * @param {Function} resultSelector Selector function for results produced in the sequence.\r\n * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.\r\n * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} The generated sequence.\r\n */\r\n Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var first = true,\r\n hasResult = false,\r\n result,\r\n state = initialState,\r\n time;\r\n return scheduler.scheduleRecursiveWithRelative(0, function (self) {\r\n hasResult && observer.onNext(result);\r\n\r\n try {\r\n if (first) {\r\n first = false;\r\n } else {\r\n state = iterate(state);\r\n }\r\n hasResult = condition(state);\r\n if (hasResult) {\r\n result = resultSelector(state);\r\n time = timeSelector(state);\r\n }\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n if (hasResult) {\r\n self(time);\r\n } else {\r\n observer.onCompleted();\r\n }\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Time shifts the observable sequence by delaying the subscription.\r\n * \r\n * @example\r\n * 1 - res = source.delaySubscription(5000); // 5s\r\n * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds\r\n * \r\n * @param {Number} dueTime Absolute or relative time to perform the subscription at.\r\n * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.\r\n * @returns {Observable} Time-shifted sequence.\r\n */\r\n observableProto.delaySubscription = function (dueTime, scheduler) {\r\n return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);\r\n };\r\n\r\n /**\r\n * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.\r\n * \r\n * @example\r\n * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only\r\n * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector\r\n *\r\n * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. \r\n * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.\r\n * @returns {Observable} Time-shifted sequence.\r\n */\r\n observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {\r\n var source = this, subDelay, selector;\r\n if (typeof subscriptionDelay === 'function') {\r\n selector = subscriptionDelay;\r\n } else {\r\n subDelay = subscriptionDelay;\r\n selector = delayDurationSelector;\r\n }\r\n return new AnonymousObservable(function (observer) {\r\n var delays = new CompositeDisposable(), atEnd = false, done = function () {\r\n if (atEnd && delays.length === 0) {\r\n observer.onCompleted();\r\n }\r\n }, subscription = new SerialDisposable(), start = function () {\r\n subscription.setDisposable(source.subscribe(function (x) {\r\n var delay;\r\n try {\r\n delay = selector(x);\r\n } catch (error) {\r\n observer.onError(error);\r\n return;\r\n }\r\n var d = new SingleAssignmentDisposable();\r\n delays.add(d);\r\n d.setDisposable(delay.subscribe(function () {\r\n observer.onNext(x);\r\n delays.remove(d);\r\n done();\r\n }, observer.onError.bind(observer), function () {\r\n observer.onNext(x);\r\n delays.remove(d);\r\n done();\r\n }));\r\n }, observer.onError.bind(observer), function () {\r\n atEnd = true;\r\n subscription.dispose();\r\n done();\r\n }));\r\n };\r\n\r\n if (!subDelay) {\r\n start();\r\n } else {\r\n subscription.setDisposable(subDelay.subscribe(function () {\r\n start();\r\n }, observer.onError.bind(observer), function () { start(); }));\r\n }\r\n\r\n return new CompositeDisposable(subscription, delays);\r\n });\r\n };\r\n\r\n /**\r\n * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.\r\n * \r\n * @example\r\n * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); \r\n * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });\r\n * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));\r\n * \r\n * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().\r\n * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.\r\n * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). \r\n * @returns {Observable} The source sequence switching to the other sequence in case of a timeout.\r\n */\r\n observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {\r\n if (arguments.length === 1) {\r\n timeoutdurationSelector = firstTimeout;\r\n var firstTimeout = observableNever();\r\n }\r\n other || (other = observableThrow(new Error('Timeout')));\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();\r\n\r\n subscription.setDisposable(original);\r\n\r\n var id = 0, switched = false, setTimer = function (timeout) {\r\n var myId = id, timerWins = function () {\r\n return id === myId;\r\n };\r\n var d = new SingleAssignmentDisposable();\r\n timer.setDisposable(d);\r\n d.setDisposable(timeout.subscribe(function () {\r\n if (timerWins()) {\r\n subscription.setDisposable(other.subscribe(observer));\r\n }\r\n d.dispose();\r\n }, function (e) {\r\n if (timerWins()) {\r\n observer.onError(e);\r\n }\r\n }, function () {\r\n if (timerWins()) {\r\n subscription.setDisposable(other.subscribe(observer));\r\n }\r\n }));\r\n };\r\n\r\n setTimer(firstTimeout);\r\n var observerWins = function () {\r\n var res = !switched;\r\n if (res) {\r\n id++;\r\n }\r\n return res;\r\n };\r\n\r\n original.setDisposable(source.subscribe(function (x) {\r\n if (observerWins()) {\r\n observer.onNext(x);\r\n var timeout;\r\n try {\r\n timeout = timeoutdurationSelector(x);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n setTimer(timeout);\r\n }\r\n }, function (e) {\r\n if (observerWins()) {\r\n observer.onError(e);\r\n }\r\n }, function () {\r\n if (observerWins()) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n return new CompositeDisposable(subscription, timer);\r\n });\r\n };\r\n\r\n /**\r\n * Ignores values from an observable sequence which are followed by another value within a computed throttle duration.\r\n * \r\n * @example\r\n * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); \r\n * \r\n * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.\r\n * @returns {Observable} The throttled sequence.\r\n */\r\n observableProto.throttleWithSelector = function (throttleDurationSelector) {\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {\r\n var throttle;\r\n try {\r\n throttle = throttleDurationSelector(x);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n hasValue = true;\r\n value = x;\r\n id++;\r\n var currentid = id, d = new SingleAssignmentDisposable();\r\n cancelable.setDisposable(d);\r\n d.setDisposable(throttle.subscribe(function () {\r\n if (hasValue && id === currentid) {\r\n observer.onNext(value);\r\n }\r\n hasValue = false;\r\n d.dispose();\r\n }, observer.onError.bind(observer), function () {\r\n if (hasValue && id === currentid) {\r\n observer.onNext(value);\r\n }\r\n hasValue = false;\r\n d.dispose();\r\n }));\r\n }, function (e) {\r\n cancelable.dispose();\r\n observer.onError(e);\r\n hasValue = false;\r\n id++;\r\n }, function () {\r\n cancelable.dispose();\r\n if (hasValue) {\r\n observer.onNext(value);\r\n }\r\n observer.onCompleted();\r\n hasValue = false;\r\n id++;\r\n });\r\n return new CompositeDisposable(subscription, cancelable);\r\n });\r\n };\r\n\r\n /**\r\n * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.\r\n * \r\n * 1 - res = source.skipLastWithTime(5000); \r\n * 2 - res = source.skipLastWithTime(5000, scheduler); \r\n * \r\n * @description\r\n * This operator accumulates a queue with a length enough to store elements received during the initial duration window.\r\n * As more elements are received, elements older than the specified duration are taken from the queue and produced on the\r\n * result sequence. This causes elements to be delayed with duration. \r\n * @param {Number} duration Duration for skipping elements from the end of the sequence.\r\n * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout\r\n * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.\r\n */\r\n observableProto.skipLastWithTime = function (duration, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n var source = this;\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n return source.subscribe(function (x) {\r\n var now = scheduler.now();\r\n q.push({ interval: now, value: x });\r\n while (q.length > 0 && now - q[0].interval >= duration) {\r\n observer.onNext(q.shift().value);\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n var now = scheduler.now();\r\n while (q.length > 0 && now - q[0].interval >= duration) {\r\n observer.onNext(q.shift().value);\r\n }\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.\r\n * \r\n * @example\r\n * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); \r\n * @description\r\n * This operator accumulates a queue with a length enough to store elements received during the initial duration window.\r\n * As more elements are received, elements older than the specified duration are taken from the queue and produced on the\r\n * result sequence. This causes elements to be delayed with duration. \r\n * @param {Number} duration Duration for taking elements from the end of the sequence.\r\n * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.\r\n * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.\r\n */\r\n observableProto.takeLastWithTime = function (duration, scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n\r\n return source.subscribe(function (x) {\r\n var now = scheduler.now();\r\n q.push({ interval: now, value: x });\r\n while (q.length > 0 && now - q[0].interval >= duration) {\r\n q.shift();\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n var now = scheduler.now();\r\n while (q.length > 0) {\r\n var next = q.shift();\r\n if (now - next.interval <= duration) {\r\n observer.onNext(next.value);\r\n }\r\n }\r\n\r\n observer.onCompleted();\r\n });\r\n }); \r\n };\r\n\r\n /**\r\n * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.\r\n * \r\n * @example\r\n * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); \r\n * @description\r\n * This operator accumulates a queue with a length enough to store elements received during the initial duration window.\r\n * As more elements are received, elements older than the specified duration are taken from the queue and produced on the\r\n * result sequence. This causes elements to be delayed with duration. \r\n * @param {Number} duration Duration for taking elements from the end of the sequence.\r\n * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.\r\n * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.\r\n */\r\n observableProto.takeLastBufferWithTime = function (duration, scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var q = [];\r\n\r\n return source.subscribe(function (x) {\r\n var now = scheduler.now();\r\n q.push({ interval: now, value: x });\r\n while (q.length > 0 && now - q[0].interval >= duration) {\r\n q.shift();\r\n }\r\n }, observer.onError.bind(observer), function () {\r\n var now = scheduler.now(), res = [];\r\n while (q.length > 0) {\r\n var next = q.shift();\r\n if (now - next.interval <= duration) {\r\n res.push(next.value);\r\n }\r\n }\r\n\r\n observer.onNext(res);\r\n observer.onCompleted();\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.\r\n * \r\n * @example\r\n * 1 - res = source.takeWithTime(5000, [optional scheduler]); \r\n * @description\r\n * This operator accumulates a queue with a length enough to store elements received during the initial duration window.\r\n * As more elements are received, elements older than the specified duration are taken from the queue and produced on the\r\n * result sequence. This causes elements to be delayed with duration. \r\n * @param {Number} duration Duration for taking elements from the start of the sequence.\r\n * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.\r\n * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.\r\n */\r\n observableProto.takeWithTime = function (duration, scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer));\r\n });\r\n };\r\n\r\n /**\r\n * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.\r\n * \r\n * @example\r\n * 1 - res = source.skipWithTime(5000, [optional scheduler]); \r\n * \r\n * @description \r\n * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.\r\n * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded\r\n * may not execute immediately, despite the zero due time.\r\n * \r\n * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. \r\n * @param {Number} duration Duration for skipping elements from the start of the sequence.\r\n * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.\r\n * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.\r\n */\r\n observableProto.skipWithTime = function (duration, scheduler) {\r\n var source = this;\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n return new AnonymousObservable(function (observer) {\r\n var open = false;\r\n return new CompositeDisposable(\r\n scheduler.scheduleWithRelative(duration, function () { open = true; }), \r\n source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));\r\n });\r\n };\r\n\r\n /**\r\n * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.\r\n * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.\r\n * \r\n * @examples\r\n * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); \r\n * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); \r\n * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.\r\n * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.\r\n * @returns {Observable} An observable sequence with the elements skipped until the specified start time. \r\n */\r\n observableProto.skipUntilWithTime = function (startTime, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n var source = this, schedulerMethod = startTime instanceof Date ?\r\n 'scheduleWithAbsolute' :\r\n 'scheduleWithRelative';\r\n return new AnonymousObservable(function (observer) {\r\n var open = false;\r\n\r\n return new CompositeDisposable(\r\n scheduler[schedulerMethod](startTime, function () { open = true; }),\r\n source.subscribe(\r\n function (x) { open && observer.onNext(x); }, \r\n observer.onError.bind(observer),\r\n observer.onCompleted.bind(observer)));\r\n });\r\n };\r\n\r\n /**\r\n * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.\r\n * \r\n * @example\r\n * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);\r\n * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); \r\n * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.\r\n * @param {Scheduler} scheduler Scheduler to run the timer on.\r\n * @returns {Observable} An observable sequence with the elements taken until the specified end time.\r\n */\r\n observableProto.takeUntilWithTime = function (endTime, scheduler) {\r\n isScheduler(scheduler) || (scheduler = timeoutScheduler);\r\n var source = this, schedulerMethod = endTime instanceof Date ?\r\n 'scheduleWithAbsolute' :\r\n 'scheduleWithRelative';\r\n return new AnonymousObservable(function (observer) {\r\n return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {\r\n observer.onCompleted();\r\n }), source.subscribe(observer));\r\n });\r\n };\r\n\r\n /*\r\n * Performs a exclusive waiting for the first to finish before subscribing to another observable.\r\n * Observables that come in between subscriptions will be dropped on the floor.\r\n * @returns {Observable} A exclusive observable with only the results that happen when subscribed.\r\n */\r\n observableProto.exclusive = function () {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var hasCurrent = false,\r\n isStopped = false,\r\n m = new SingleAssignmentDisposable(),\r\n g = new CompositeDisposable();\r\n\r\n g.add(m);\r\n\r\n m.setDisposable(sources.subscribe(\r\n function (innerSource) {\r\n if (!hasCurrent) {\r\n hasCurrent = true;\r\n \r\n isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));\r\n\r\n var innerSubscription = new SingleAssignmentDisposable();\r\n g.add(innerSubscription);\r\n\r\n innerSubscription.setDisposable(innerSource.subscribe(\r\n observer.onNext.bind(observer),\r\n observer.onError.bind(observer),\r\n function () {\r\n g.remove(innerSubscription);\r\n hasCurrent = false;\r\n if (isStopped && g.length === 1) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n }\r\n },\r\n observer.onError.bind(observer),\r\n function () {\r\n isStopped = true;\r\n if (!hasCurrent && g.length === 1) { \r\n observer.onCompleted();\r\n }\r\n }));\r\n\r\n return g;\r\n });\r\n };\r\n /*\r\n * Performs a exclusive map waiting for the first to finish before subscribing to another observable.\r\n * Observables that come in between subscriptions will be dropped on the floor.\r\n * @param {Function} selector Selector to invoke for every item in the current subscription.\r\n * @param {Any} [thisArg] An optional context to invoke with the selector parameter.\r\n * @returns {Observable} An exclusive observable with only the results that happen when subscribed.\r\n */\r\n observableProto.exclusiveMap = function (selector, thisArg) {\r\n var sources = this;\r\n return new AnonymousObservable(function (observer) {\r\n var index = 0,\r\n hasCurrent = false,\r\n isStopped = true,\r\n m = new SingleAssignmentDisposable(),\r\n g = new CompositeDisposable();\r\n\r\n g.add(m);\r\n\r\n m.setDisposable(sources.subscribe(\r\n function (innerSource) {\r\n\r\n if (!hasCurrent) {\r\n hasCurrent = true; \r\n\r\n innerSubscription = new SingleAssignmentDisposable();\r\n g.add(innerSubscription);\r\n\r\n isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); \r\n\r\n innerSubscription.setDisposable(innerSource.subscribe(\r\n function (x) {\r\n var result;\r\n try {\r\n result = selector.call(thisArg, x, index++, innerSource);\r\n } catch (e) {\r\n observer.onError(e);\r\n return;\r\n }\r\n\r\n observer.onNext(result);\r\n },\r\n observer.onError.bind(observer),\r\n function () {\r\n g.remove(innerSubscription);\r\n hasCurrent = false;\r\n\r\n if (isStopped && g.length === 1) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n }\r\n }, \r\n observer.onError.bind(observer),\r\n function () {\r\n isStopped = true;\r\n if (g.length === 1 && !hasCurrent) {\r\n observer.onCompleted();\r\n }\r\n }));\r\n return g;\r\n });\r\n };\r\n /** Provides a set of extension methods for virtual time scheduling. */\r\n Rx.VirtualTimeScheduler = (function (__super__) {\r\n\r\n function notImplemented() {\r\n throw new Error('Not implemented');\r\n }\r\n\r\n function localNow() {\r\n return this.toDateTimeOffset(this.clock);\r\n }\r\n\r\n function scheduleNow(state, action) {\r\n return this.scheduleAbsoluteWithState(state, this.clock, action);\r\n }\r\n\r\n function scheduleRelative(state, dueTime, action) {\r\n return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);\r\n }\r\n\r\n function scheduleAbsolute(state, dueTime, action) {\r\n return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);\r\n }\r\n\r\n function invokeAction(scheduler, action) {\r\n action();\r\n return disposableEmpty;\r\n }\r\n\r\n inherits(VirtualTimeScheduler, __super__);\r\n\r\n /**\r\n * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.\r\n *\r\n * @constructor\r\n * @param {Number} initialClock Initial value for the clock.\r\n * @param {Function} comparer Comparer to determine causality of events based on absolute time.\r\n */\r\n function VirtualTimeScheduler(initialClock, comparer) {\r\n this.clock = initialClock;\r\n this.comparer = comparer;\r\n this.isEnabled = false;\r\n this.queue = new PriorityQueue(1024);\r\n __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);\r\n }\r\n\r\n var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;\r\n\r\n /**\r\n * Adds a relative time value to an absolute time value.\r\n * @param {Number} absolute Absolute virtual time value.\r\n * @param {Number} relative Relative virtual time value to add.\r\n * @return {Number} Resulting absolute virtual time sum value.\r\n */\r\n VirtualTimeSchedulerPrototype.add = notImplemented;\r\n\r\n /**\r\n * Converts an absolute time to a number \r\n * @param {Any} The absolute time.\r\n * @returns {Number} The absolute time in ms\r\n */\r\n VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;\r\n\r\n /**\r\n * Converts the TimeSpan value to a relative virtual time value. \r\n * @param {Number} timeSpan TimeSpan value to convert.\r\n * @return {Number} Corresponding relative virtual time value.\r\n */\r\n VirtualTimeSchedulerPrototype.toRelative = notImplemented;\r\n\r\n /**\r\n * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. \r\n * @param {Mixed} state Initial state passed to the action upon the first iteration.\r\n * @param {Number} period Period for running the work periodically.\r\n * @param {Function} action Action to be executed, potentially updating the state.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).\r\n */ \r\n VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {\r\n var s = new SchedulePeriodicRecursive(this, state, period, action);\r\n return s.start();\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed after dueTime.\r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Number} dueTime Relative time after which to execute the action.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */ \r\n VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {\r\n var runAt = this.add(this.clock, dueTime);\r\n return this.scheduleAbsoluteWithState(state, runAt, action);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed at dueTime. \r\n * @param {Number} dueTime Relative time after which to execute the action.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */ \r\n VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {\r\n return this.scheduleRelativeWithState(action, dueTime, invokeAction);\r\n }; \r\n\r\n /** \r\n * Starts the virtual time scheduler. \r\n */\r\n VirtualTimeSchedulerPrototype.start = function () {\r\n if (!this.isEnabled) {\r\n this.isEnabled = true;\r\n do {\r\n var next = this.getNext();\r\n if (next !== null) {\r\n this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);\r\n next.invoke();\r\n } else {\r\n this.isEnabled = false;\r\n }\r\n } while (this.isEnabled);\r\n }\r\n };\r\n\r\n /** \r\n * Stops the virtual time scheduler. \r\n */\r\n VirtualTimeSchedulerPrototype.stop = function () {\r\n this.isEnabled = false;\r\n };\r\n\r\n /**\r\n * Advances the scheduler's clock to the specified time, running all work till that point.\r\n * @param {Number} time Absolute time to advance the scheduler's clock to.\r\n */\r\n VirtualTimeSchedulerPrototype.advanceTo = function (time) {\r\n var dueToClock = this.comparer(this.clock, time);\r\n if (this.comparer(this.clock, time) > 0) {\r\n throw new Error(argumentOutOfRange);\r\n }\r\n if (dueToClock === 0) {\r\n return;\r\n }\r\n if (!this.isEnabled) {\r\n this.isEnabled = true;\r\n do {\r\n var next = this.getNext();\r\n if (next !== null && this.comparer(next.dueTime, time) <= 0) {\r\n this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);\r\n next.invoke();\r\n } else {\r\n this.isEnabled = false;\r\n }\r\n } while (this.isEnabled);\r\n this.clock = time;\r\n }\r\n };\r\n\r\n /**\r\n * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.\r\n * @param {Number} time Relative time to advance the scheduler's clock by.\r\n */\r\n VirtualTimeSchedulerPrototype.advanceBy = function (time) {\r\n var dt = this.add(this.clock, time),\r\n dueToClock = this.comparer(this.clock, dt);\r\n if (dueToClock > 0) { throw new Error(argumentOutOfRange); }\r\n if (dueToClock === 0) { return; }\r\n\r\n this.advanceTo(dt);\r\n }; \r\n\r\n /**\r\n * Advances the scheduler's clock by the specified relative time. \r\n * @param {Number} time Relative time to advance the scheduler's clock by.\r\n */\r\n VirtualTimeSchedulerPrototype.sleep = function (time) {\r\n var dt = this.add(this.clock, time);\r\n if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); }\r\n\r\n this.clock = dt;\r\n };\r\n\r\n /**\r\n * Gets the next scheduled item to be executed. \r\n * @returns {ScheduledItem} The next scheduled item.\r\n */ \r\n VirtualTimeSchedulerPrototype.getNext = function () {\r\n while (this.queue.length > 0) {\r\n var next = this.queue.peek();\r\n if (next.isCancelled()) {\r\n this.queue.dequeue();\r\n } else {\r\n return next;\r\n }\r\n }\r\n return null;\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed at dueTime. \r\n * @param {Scheduler} scheduler Scheduler to execute the action on.\r\n * @param {Number} dueTime Absolute time at which to execute the action.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */ \r\n VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {\r\n return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);\r\n };\r\n\r\n /**\r\n * Schedules an action to be executed at dueTime.\r\n * @param {Mixed} state State passed to the action to be executed.\r\n * @param {Number} dueTime Absolute time at which to execute the action.\r\n * @param {Function} action Action to be executed.\r\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\r\n */\r\n VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {\r\n var self = this;\r\n\r\n function run(scheduler, state1) {\r\n self.queue.remove(si);\r\n return action(scheduler, state1);\r\n }\r\n \r\n var si = new ScheduledItem(this, state, run, dueTime, this.comparer);\r\n this.queue.enqueue(si);\r\n \r\n return si.disposable;\r\n };\r\n\r\n return VirtualTimeScheduler;\r\n }(Scheduler));\r\n\r\n /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */\r\n Rx.HistoricalScheduler = (function (__super__) {\r\n inherits(HistoricalScheduler, __super__);\r\n\r\n /**\r\n * Creates a new historical scheduler with the specified initial clock value.\r\n * @constructor\r\n * @param {Number} initialClock Initial value for the clock.\r\n * @param {Function} comparer Comparer to determine causality of events based on absolute time.\r\n */\r\n function HistoricalScheduler(initialClock, comparer) {\r\n var clock = initialClock == null ? 0 : initialClock;\r\n var cmp = comparer || defaultSubComparer;\r\n __super__.call(this, clock, cmp);\r\n }\r\n\r\n var HistoricalSchedulerProto = HistoricalScheduler.prototype;\r\n\r\n /**\r\n * Adds a relative time value to an absolute time value.\r\n * @param {Number} absolute Absolute virtual time value.\r\n * @param {Number} relative Relative virtual time value to add.\r\n * @return {Number} Resulting absolute virtual time sum value.\r\n */\r\n HistoricalSchedulerProto.add = function (absolute, relative) {\r\n return absolute + relative;\r\n };\r\n\r\n HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {\r\n return new Date(absolute).getTime();\r\n };\r\n\r\n /**\r\n * Converts the TimeSpan value to a relative virtual time value.\r\n * @memberOf HistoricalScheduler \r\n * @param {Number} timeSpan TimeSpan value to convert.\r\n * @return {Number} Corresponding relative virtual time value.\r\n */\r\n HistoricalSchedulerProto.toRelative = function (timeSpan) {\r\n return timeSpan;\r\n };\r\n\r\n return HistoricalScheduler; \r\n }(Rx.VirtualTimeScheduler));\r\n var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {\r\n inherits(AnonymousObservable, __super__);\r\n\r\n // Fix subscriber to check for undefined or function returned to decorate as Disposable\r\n function fixSubscriber(subscriber) {\r\n if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }\r\n\r\n return typeof subscriber === 'function' ?\r\n disposableCreate(subscriber) :\r\n disposableEmpty;\r\n }\r\n\r\n function AnonymousObservable(subscribe) {\r\n if (!(this instanceof AnonymousObservable)) {\r\n return new AnonymousObservable(subscribe);\r\n }\r\n\r\n function s(observer) {\r\n var setDisposable = function () {\r\n try {\r\n autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));\r\n } catch (e) {\r\n if (!autoDetachObserver.fail(e)) {\r\n throw e;\r\n } \r\n }\r\n };\r\n\r\n var autoDetachObserver = new AutoDetachObserver(observer);\r\n if (currentThreadScheduler.scheduleRequired()) {\r\n currentThreadScheduler.schedule(setDisposable);\r\n } else {\r\n setDisposable();\r\n }\r\n\r\n return autoDetachObserver;\r\n }\r\n\r\n __super__.call(this, s);\r\n }\r\n\r\n return AnonymousObservable;\r\n\r\n }(Observable));\r\n\r\n /** @private */\r\n var AutoDetachObserver = (function (_super) {\r\n inherits(AutoDetachObserver, _super);\r\n\r\n function AutoDetachObserver(observer) {\r\n _super.call(this);\r\n this.observer = observer;\r\n this.m = new SingleAssignmentDisposable();\r\n }\r\n\r\n var AutoDetachObserverPrototype = AutoDetachObserver.prototype;\r\n\r\n AutoDetachObserverPrototype.next = function (value) {\r\n var noError = false;\r\n try {\r\n this.observer.onNext(value);\r\n noError = true;\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n if (!noError) {\r\n this.dispose();\r\n }\r\n }\r\n };\r\n\r\n AutoDetachObserverPrototype.error = function (exn) {\r\n try {\r\n this.observer.onError(exn);\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n this.dispose();\r\n }\r\n };\r\n\r\n AutoDetachObserverPrototype.completed = function () {\r\n try {\r\n this.observer.onCompleted();\r\n } catch (e) { \r\n throw e; \r\n } finally {\r\n this.dispose();\r\n }\r\n };\r\n\r\n AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };\r\n AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };\r\n /* @private */\r\n AutoDetachObserverPrototype.disposable = function (value) {\r\n return arguments.length ? this.getDisposable() : setDisposable(value);\r\n };\r\n\r\n AutoDetachObserverPrototype.dispose = function () {\r\n _super.prototype.dispose.call(this);\r\n this.m.dispose();\r\n };\r\n\r\n return AutoDetachObserver;\r\n }(AbstractObserver));\r\n\r\n /** @private */\r\n var GroupedObservable = (function (_super) {\r\n inherits(GroupedObservable, _super);\r\n\r\n function subscribe(observer) {\r\n return this.underlyingObservable.subscribe(observer);\r\n }\r\n\r\n /** \r\n * @constructor\r\n * @private\r\n */\r\n function GroupedObservable(key, underlyingObservable, mergedDisposable) {\r\n _super.call(this, subscribe);\r\n this.key = key;\r\n this.underlyingObservable = !mergedDisposable ?\r\n underlyingObservable :\r\n new AnonymousObservable(function (observer) {\r\n return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));\r\n });\r\n }\r\n\r\n return GroupedObservable;\r\n }(Observable));\r\n\r\n /**\r\n * Represents an object that is both an observable sequence as well as an observer.\r\n * Each notification is broadcasted to all subscribed observers.\r\n */\r\n var Subject = Rx.Subject = (function (_super) {\r\n function subscribe(observer) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.observers.push(observer);\r\n return new InnerSubscription(this, observer);\r\n }\r\n if (this.exception) {\r\n observer.onError(this.exception);\r\n return disposableEmpty;\r\n }\r\n observer.onCompleted();\r\n return disposableEmpty;\r\n }\r\n\r\n inherits(Subject, _super);\r\n\r\n /**\r\n * Creates a subject.\r\n * @constructor\r\n */ \r\n function Subject() {\r\n _super.call(this, subscribe);\r\n this.isDisposed = false,\r\n this.isStopped = false,\r\n this.observers = [];\r\n }\r\n\r\n addProperties(Subject.prototype, Observer, {\r\n /**\r\n * Indicates whether the subject has observers subscribed to it.\r\n * @returns {Boolean} Indicates whether the subject has observers subscribed to it.\r\n */ \r\n hasObservers: function () {\r\n return this.observers.length > 0;\r\n },\r\n /**\r\n * Notifies all subscribed observers about the end of the sequence.\r\n */ \r\n onCompleted: function () {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n this.isStopped = true;\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onCompleted();\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the exception.\r\n * @param {Mixed} error The exception to send to all observers.\r\n */ \r\n onError: function (exception) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n this.isStopped = true;\r\n this.exception = exception;\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onError(exception);\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the arrival of the specified element in the sequence.\r\n * @param {Mixed} value The value to send to all observers.\r\n */ \r\n onNext: function (value) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onNext(value);\r\n }\r\n }\r\n },\r\n /**\r\n * Unsubscribe all observers and release resources.\r\n */ \r\n dispose: function () {\r\n this.isDisposed = true;\r\n this.observers = null;\r\n }\r\n });\r\n\r\n /**\r\n * Creates a subject from the specified observer and observable.\r\n * @param {Observer} observer The observer used to send messages to the subject.\r\n * @param {Observable} observable The observable used to subscribe to messages sent from the subject.\r\n * @returns {Subject} Subject implemented using the given observer and observable.\r\n */\r\n Subject.create = function (observer, observable) {\r\n return new AnonymousSubject(observer, observable);\r\n };\r\n\r\n return Subject;\r\n }(Observable));\r\n\r\n /**\r\n * Represents the result of an asynchronous operation.\r\n * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.\r\n */ \r\n var AsyncSubject = Rx.AsyncSubject = (function (_super) {\r\n\r\n function subscribe(observer) {\r\n checkDisposed.call(this);\r\n \r\n if (!this.isStopped) {\r\n this.observers.push(observer);\r\n return new InnerSubscription(this, observer);\r\n }\r\n\r\n var ex = this.exception,\r\n hv = this.hasValue,\r\n v = this.value;\r\n\r\n if (ex) {\r\n observer.onError(ex);\r\n } else if (hv) {\r\n observer.onNext(v);\r\n observer.onCompleted();\r\n } else {\r\n observer.onCompleted();\r\n }\r\n\r\n return disposableEmpty;\r\n }\r\n\r\n inherits(AsyncSubject, _super);\r\n\r\n /**\r\n * Creates a subject that can only receive one value and that value is cached for all future observations.\r\n * @constructor\r\n */ \r\n function AsyncSubject() {\r\n _super.call(this, subscribe);\r\n\r\n this.isDisposed = false;\r\n this.isStopped = false;\r\n this.value = null;\r\n this.hasValue = false;\r\n this.observers = [];\r\n this.exception = null;\r\n }\r\n\r\n addProperties(AsyncSubject.prototype, Observer, {\r\n /**\r\n * Indicates whether the subject has observers subscribed to it.\r\n * @returns {Boolean} Indicates whether the subject has observers subscribed to it.\r\n */ \r\n hasObservers: function () {\r\n checkDisposed.call(this);\r\n return this.observers.length > 0;\r\n },\r\n /**\r\n * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).\r\n */ \r\n onCompleted: function () {\r\n var o, i, len;\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.isStopped = true;\r\n var os = this.observers.slice(0),\r\n v = this.value,\r\n hv = this.hasValue;\r\n\r\n if (hv) {\r\n for (i = 0, len = os.length; i < len; i++) {\r\n o = os[i];\r\n o.onNext(v);\r\n o.onCompleted();\r\n }\r\n } else {\r\n for (i = 0, len = os.length; i < len; i++) {\r\n os[i].onCompleted();\r\n }\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Notifies all subscribed observers about the exception.\r\n * @param {Mixed} error The exception to send to all observers.\r\n */ \r\n onError: function (exception) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n var os = this.observers.slice(0);\r\n this.isStopped = true;\r\n this.exception = exception;\r\n\r\n for (var i = 0, len = os.length; i < len; i++) {\r\n os[i].onError(exception);\r\n }\r\n\r\n this.observers = [];\r\n }\r\n },\r\n /**\r\n * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.\r\n * @param {Mixed} value The value to store in the subject.\r\n */ \r\n onNext: function (value) {\r\n checkDisposed.call(this);\r\n if (!this.isStopped) {\r\n this.value = value;\r\n this.hasValue = true;\r\n }\r\n },\r\n /**\r\n * Unsubscribe all observers and release resources.\r\n */\r\n dispose: function () {\r\n this.isDisposed = true;\r\n this.observers = null;\r\n this.exception = null;\r\n this.value = null;\r\n }\r\n });\r\n\r\n return AsyncSubject;\r\n }(Observable));\r\n\r\n var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {\r\n inherits(AnonymousSubject, __super__);\r\n\r\n function AnonymousSubject(observer, observable) {\r\n this.observer = observer;\r\n this.observable = observable; \r\n __super__.call(this, this.observable.subscribe.bind(this.observable));\r\n }\r\n\r\n addProperties(AnonymousSubject.prototype, Observer, {\r\n onCompleted: function () {\r\n this.observer.onCompleted();\r\n }, \r\n onError: function (exception) {\r\n this.observer.onError(exception);\r\n }, \r\n onNext: function (value) {\r\n this.observer.onNext(value);\r\n }\r\n });\r\n\r\n return AnonymousSubject;\r\n }(Observable));\r\n\r\n if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {\r\n root.Rx = Rx;\r\n\r\n define(function() {\r\n return Rx;\r\n });\r\n } else if (freeExports && freeModule) {\r\n // in Node.js or RingoJS\r\n if (moduleExports) {\r\n (freeModule.exports = Rx).Rx = Rx;\r\n } else {\r\n freeExports.Rx = Rx;\r\n }\r\n } else {\r\n // in a browser or Rhino\r\n root.Rx = Rx;\r\n }\r\n}.call(this));"}}},{"rowIdx":362,"cells":{"target":{"kind":"string","value":"src/components/Feedback/Feedback.js"},"feat_repo_name":{"kind":"string","value":"louisukiri/react-starter-kit"},"text":{"kind":"string","value":"/**\n * React Starter Kit (https://www.reactstarterkit.com/)\n *\n * Copyright © 2014-present Kriasoft, LLC. All rights reserved.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nimport React from 'react';\nimport withStyles from 'isomorphic-style-loader/lib/withStyles';\nimport s from './Feedback.css';\n\nclass Feedback extends React.Component {\n render() {\n return (\n
\n
\n \n Ask a question\n \n |\n \n Report an issue\n \n
\n
\n );\n }\n}\n\nexport default withStyles(s)(Feedback);\n"}}},{"rowIdx":363,"cells":{"target":{"kind":"string","value":"ajax/libs/analytics.js/1.5.0/analytics.js"},"feat_repo_name":{"kind":"string","value":"snorpey/cdnjs"},"text":{"kind":"string","value":";(function(){\n\n/**\n * Require the given path.\n *\n * @param {String} path\n * @return {Object} exports\n * @api public\n */\n\nfunction require(path, parent, orig) {\n var resolved = require.resolve(path);\n\n // lookup failed\n if (null == resolved) {\n orig = orig || path;\n parent = parent || 'root';\n var err = new Error('Failed to require \"' + orig + '\" from \"' + parent + '\"');\n err.path = orig;\n err.parent = parent;\n err.require = true;\n throw err;\n }\n\n var module = require.modules[resolved];\n\n // perform real require()\n // by invoking the module's\n // registered function\n if (!module._resolving && !module.exports) {\n var mod = {};\n mod.exports = {};\n mod.client = mod.component = true;\n module._resolving = true;\n module.call(this, mod.exports, require.relative(resolved), mod);\n delete module._resolving;\n module.exports = mod.exports;\n }\n\n return module.exports;\n}\n\n/**\n * Registered modules.\n */\n\nrequire.modules = {};\n\n/**\n * Registered aliases.\n */\n\nrequire.aliases = {};\n\n/**\n * Resolve `path`.\n *\n * Lookup:\n *\n * - PATH/index.js\n * - PATH.js\n * - PATH\n *\n * @param {String} path\n * @return {String} path or null\n * @api private\n */\n\nrequire.resolve = function(path) {\n if (path.charAt(0) === '/') path = path.slice(1);\n\n var paths = [\n path,\n path + '.js',\n path + '.json',\n path + '/index.js',\n path + '/index.json'\n ];\n\n for (var i = 0; i < paths.length; i++) {\n var path = paths[i];\n if (require.modules.hasOwnProperty(path)) return path;\n if (require.aliases.hasOwnProperty(path)) return require.aliases[path];\n }\n};\n\n/**\n * Normalize `path` relative to the current path.\n *\n * @param {String} curr\n * @param {String} path\n * @return {String}\n * @api private\n */\n\nrequire.normalize = function(curr, path) {\n var segs = [];\n\n if ('.' != path.charAt(0)) return path;\n\n curr = curr.split('/');\n path = path.split('/');\n\n for (var i = 0; i < path.length; ++i) {\n if ('..' == path[i]) {\n curr.pop();\n } else if ('.' != path[i] && '' != path[i]) {\n segs.push(path[i]);\n }\n }\n\n return curr.concat(segs).join('/');\n};\n\n/**\n * Register module at `path` with callback `definition`.\n *\n * @param {String} path\n * @param {Function} definition\n * @api private\n */\n\nrequire.register = function(path, definition) {\n require.modules[path] = definition;\n};\n\n/**\n * Alias a module definition.\n *\n * @param {String} from\n * @param {String} to\n * @api private\n */\n\nrequire.alias = function(from, to) {\n if (!require.modules.hasOwnProperty(from)) {\n throw new Error('Failed to alias \"' + from + '\", it does not exist');\n }\n require.aliases[to] = from;\n};\n\n/**\n * Return a require function relative to the `parent` path.\n *\n * @param {String} parent\n * @return {Function}\n * @api private\n */\n\nrequire.relative = function(parent) {\n var p = require.normalize(parent, '..');\n\n /**\n * lastIndexOf helper.\n */\n\n function lastIndexOf(arr, obj) {\n var i = arr.length;\n while (i--) {\n if (arr[i] === obj) return i;\n }\n return -1;\n }\n\n /**\n * The relative require() itself.\n */\n\n function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }\n\n /**\n * Resolve relative to the parent.\n */\n\n localRequire.resolve = function(path) {\n var c = path.charAt(0);\n if ('/' == c) return path.slice(1);\n if ('.' == c) return require.normalize(p, path);\n\n // resolve deps by returning\n // the dep in the nearest \"deps\"\n // directory\n var segs = parent.split('/');\n var i = lastIndexOf(segs, 'deps') + 1;\n if (!i) i = 0;\n path = segs.slice(0, i + 1).join('/') + '/deps/' + path;\n return path;\n };\n\n /**\n * Check if module is defined at `path`.\n */\n\n localRequire.exists = function(path) {\n return require.modules.hasOwnProperty(localRequire.resolve(path));\n };\n\n return localRequire;\n};\nrequire.register(\"avetisk-defaults/index.js\", function(exports, require, module){\n'use strict';\n\n/**\n * Merge default values.\n *\n * @param {Object} dest\n * @param {Object} defaults\n * @return {Object}\n * @api public\n */\nvar defaults = function (dest, src, recursive) {\n for (var prop in src) {\n if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {\n dest[prop] = defaults(dest[prop], src[prop], true);\n } else if (! (prop in dest)) {\n dest[prop] = src[prop];\n }\n }\n\n return dest;\n};\n\n/**\n * Expose `defaults`.\n */\nmodule.exports = defaults;\n\n});\nrequire.register(\"component-type/index.js\", function(exports, require, module){\n/**\n * toString ref.\n */\n\nvar toString = Object.prototype.toString;\n\n/**\n * Return the type of `val`.\n *\n * @param {Mixed} val\n * @return {String}\n * @api public\n */\n\nmodule.exports = function(val){\n switch (toString.call(val)) {\n case '[object Date]': return 'date';\n case '[object RegExp]': return 'regexp';\n case '[object Arguments]': return 'arguments';\n case '[object Array]': return 'array';\n case '[object Error]': return 'error';\n }\n\n if (val === null) return 'null';\n if (val === undefined) return 'undefined';\n if (val !== val) return 'nan';\n if (val && val.nodeType === 1) return 'element';\n\n val = val.valueOf\n ? val.valueOf()\n : Object.prototype.valueOf.apply(val)\n\n return typeof val;\n};\n\n});\nrequire.register(\"component-clone/index.js\", function(exports, require, module){\n\n/**\n * Module dependencies.\n */\n\nvar type;\n\ntry {\n type = require('type');\n} catch(e){\n type = require('type-component');\n}\n\n/**\n * Module exports.\n */\n\nmodule.exports = clone;\n\n/**\n * Clones objects.\n *\n * @param {Mixed} any object\n * @api public\n */\n\nfunction clone(obj){\n switch (type(obj)) {\n case 'object':\n var copy = {};\n for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n copy[key] = clone(obj[key]);\n }\n }\n return copy;\n\n case 'array':\n var copy = new Array(obj.length);\n for (var i = 0, l = obj.length; i < l; i++) {\n copy[i] = clone(obj[i]);\n }\n return copy;\n\n case 'regexp':\n // from millermedeiros/amd-utils - MIT\n var flags = '';\n flags += obj.multiline ? 'm' : '';\n flags += obj.global ? 'g' : '';\n flags += obj.ignoreCase ? 'i' : '';\n return new RegExp(obj.source, flags);\n\n case 'date':\n return new Date(obj.getTime());\n\n default: // string, number, boolean, …\n return obj;\n }\n}\n\n});\nrequire.register(\"component-cookie/index.js\", function(exports, require, module){\n/**\n * Encode.\n */\n\nvar encode = encodeURIComponent;\n\n/**\n * Decode.\n */\n\nvar decode = decodeURIComponent;\n\n/**\n * Set or get cookie `name` with `value` and `options` object.\n *\n * @param {String} name\n * @param {String} value\n * @param {Object} options\n * @return {Mixed}\n * @api public\n */\n\nmodule.exports = function(name, value, options){\n switch (arguments.length) {\n case 3:\n case 2:\n return set(name, value, options);\n case 1:\n return get(name);\n default:\n return all();\n }\n};\n\n/**\n * Set cookie `name` to `value`.\n *\n * @param {String} name\n * @param {String} value\n * @param {Object} options\n * @api private\n */\n\nfunction set(name, value, options) {\n options = options || {};\n var str = encode(name) + '=' + encode(value);\n\n if (null == value) options.maxage = -1;\n\n if (options.maxage) {\n options.expires = new Date(+new Date + options.maxage);\n }\n\n if (options.path) str += '; path=' + options.path;\n if (options.domain) str += '; domain=' + options.domain;\n if (options.expires) str += '; expires=' + options.expires.toGMTString();\n if (options.secure) str += '; secure';\n\n document.cookie = str;\n}\n\n/**\n * Return all cookies.\n *\n * @return {Object}\n * @api private\n */\n\nfunction all() {\n return parse(document.cookie);\n}\n\n/**\n * Get cookie `name`.\n *\n * @param {String} name\n * @return {String}\n * @api private\n */\n\nfunction get(name) {\n return all()[name];\n}\n\n/**\n * Parse cookie `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parse(str) {\n var obj = {};\n var pairs = str.split(/ *; */);\n var pair;\n if ('' == pairs[0]) return obj;\n for (var i = 0; i < pairs.length; ++i) {\n pair = pairs[i].split('=');\n obj[decode(pair[0])] = decode(pair[1]);\n }\n return obj;\n}\n\n});\nrequire.register(\"component-each/index.js\", function(exports, require, module){\n\n/**\n * Module dependencies.\n */\n\nvar type = require('type');\n\n/**\n * HOP reference.\n */\n\nvar has = Object.prototype.hasOwnProperty;\n\n/**\n * Iterate the given `obj` and invoke `fn(val, i)`.\n *\n * @param {String|Array|Object} obj\n * @param {Function} fn\n * @api public\n */\n\nmodule.exports = function(obj, fn){\n switch (type(obj)) {\n case 'array':\n return array(obj, fn);\n case 'object':\n if ('number' == typeof obj.length) return array(obj, fn);\n return object(obj, fn);\n case 'string':\n return string(obj, fn);\n }\n};\n\n/**\n * Iterate string chars.\n *\n * @param {String} obj\n * @param {Function} fn\n * @api private\n */\n\nfunction string(obj, fn) {\n for (var i = 0; i < obj.length; ++i) {\n fn(obj.charAt(i), i);\n }\n}\n\n/**\n * Iterate object keys.\n *\n * @param {Object} obj\n * @param {Function} fn\n * @api private\n */\n\nfunction object(obj, fn) {\n for (var key in obj) {\n if (has.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Iterate array-ish.\n *\n * @param {Array|Object} obj\n * @param {Function} fn\n * @api private\n */\n\nfunction array(obj, fn) {\n for (var i = 0; i < obj.length; ++i) {\n fn(obj[i], i);\n }\n}\n});\nrequire.register(\"component-indexof/index.js\", function(exports, require, module){\nmodule.exports = function(arr, obj){\n if (arr.indexOf) return arr.indexOf(obj);\n for (var i = 0; i < arr.length; ++i) {\n if (arr[i] === obj) return i;\n }\n return -1;\n};\n});\nrequire.register(\"component-emitter/index.js\", function(exports, require, module){\n\n/**\n * Module dependencies.\n */\n\nvar index = require('indexof');\n\n/**\n * Expose `Emitter`.\n */\n\nmodule.exports = Emitter;\n\n/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nfunction Emitter(obj) {\n if (obj) return mixin(obj);\n};\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks[event] = this._callbacks[event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n var self = this;\n this._callbacks = this._callbacks || {};\n\n function on() {\n self.off(event, on);\n fn.apply(this, arguments);\n }\n\n fn._off = on;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks[event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks[event];\n return this;\n }\n\n // remove specific handler\n var i = index(callbacks, fn._off || fn);\n if (~i) callbacks.splice(i, 1);\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n var args = [].slice.call(arguments, 1)\n , callbacks = this._callbacks[event];\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks[event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n\n});\nrequire.register(\"component-event/index.js\", function(exports, require, module){\n\n/**\n * Bind `el` event `type` to `fn`.\n *\n * @param {Element} el\n * @param {String} type\n * @param {Function} fn\n * @param {Boolean} capture\n * @return {Function}\n * @api public\n */\n\nexports.bind = function(el, type, fn, capture){\n if (el.addEventListener) {\n el.addEventListener(type, fn, capture || false);\n } else {\n el.attachEvent('on' + type, fn);\n }\n return fn;\n};\n\n/**\n * Unbind `el` event `type`'s callback `fn`.\n *\n * @param {Element} el\n * @param {String} type\n * @param {Function} fn\n * @param {Boolean} capture\n * @return {Function}\n * @api public\n */\n\nexports.unbind = function(el, type, fn, capture){\n if (el.removeEventListener) {\n el.removeEventListener(type, fn, capture || false);\n } else {\n el.detachEvent('on' + type, fn);\n }\n return fn;\n};\n\n});\nrequire.register(\"component-inherit/index.js\", function(exports, require, module){\n\nmodule.exports = function(a, b){\n var fn = function(){};\n fn.prototype = b.prototype;\n a.prototype = new fn;\n a.prototype.constructor = a;\n};\n});\nrequire.register(\"component-object/index.js\", function(exports, require, module){\n\n/**\n * HOP ref.\n */\n\nvar has = Object.prototype.hasOwnProperty;\n\n/**\n * Return own keys in `obj`.\n *\n * @param {Object} obj\n * @return {Array}\n * @api public\n */\n\nexports.keys = Object.keys || function(obj){\n var keys = [];\n for (var key in obj) {\n if (has.call(obj, key)) {\n keys.push(key);\n }\n }\n return keys;\n};\n\n/**\n * Return own values in `obj`.\n *\n * @param {Object} obj\n * @return {Array}\n * @api public\n */\n\nexports.values = function(obj){\n var vals = [];\n for (var key in obj) {\n if (has.call(obj, key)) {\n vals.push(obj[key]);\n }\n }\n return vals;\n};\n\n/**\n * Merge `b` into `a`.\n *\n * @param {Object} a\n * @param {Object} b\n * @return {Object} a\n * @api public\n */\n\nexports.merge = function(a, b){\n for (var key in b) {\n if (has.call(b, key)) {\n a[key] = b[key];\n }\n }\n return a;\n};\n\n/**\n * Return length of `obj`.\n *\n * @param {Object} obj\n * @return {Number}\n * @api public\n */\n\nexports.length = function(obj){\n return exports.keys(obj).length;\n};\n\n/**\n * Check if `obj` is empty.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api public\n */\n\nexports.isEmpty = function(obj){\n return 0 == exports.length(obj);\n};\n});\nrequire.register(\"component-trim/index.js\", function(exports, require, module){\n\nexports = module.exports = trim;\n\nfunction trim(str){\n if (str.trim) return str.trim();\n return str.replace(/^\\s*|\\s*$/g, '');\n}\n\nexports.left = function(str){\n if (str.trimLeft) return str.trimLeft();\n return str.replace(/^\\s*/, '');\n};\n\nexports.right = function(str){\n if (str.trimRight) return str.trimRight();\n return str.replace(/\\s*$/, '');\n};\n\n});\nrequire.register(\"component-querystring/index.js\", function(exports, require, module){\n\n/**\n * Module dependencies.\n */\n\nvar encode = encodeURIComponent;\nvar decode = decodeURIComponent;\nvar trim = require('trim');\nvar type = require('type');\n\n/**\n * Parse the given query `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api public\n */\n\nexports.parse = function(str){\n if ('string' != typeof str) return {};\n\n str = trim(str);\n if ('' == str) return {};\n if ('?' == str.charAt(0)) str = str.slice(1);\n\n var obj = {};\n var pairs = str.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var parts = pairs[i].split('=');\n var key = decode(parts[0]);\n var m;\n\n if (m = /(\\w+)\\[(\\d+)\\]/.exec(key)) {\n obj[m[1]] = obj[m[1]] || [];\n obj[m[1]][m[2]] = decode(parts[1]);\n continue;\n }\n\n obj[parts[0]] = null == parts[1]\n ? ''\n : decode(parts[1]);\n }\n\n return obj;\n};\n\n/**\n * Stringify the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api public\n */\n\nexports.stringify = function(obj){\n if (!obj) return '';\n var pairs = [];\n\n for (var key in obj) {\n var value = obj[key];\n\n if ('array' == type(value)) {\n for (var i = 0; i < value.length; ++i) {\n pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));\n }\n continue;\n }\n\n pairs.push(encode(key) + '=' + encode(obj[key]));\n }\n\n return pairs.join('&');\n};\n\n});\nrequire.register(\"component-url/index.js\", function(exports, require, module){\n\n/**\n * Parse the given `url`.\n *\n * @param {String} str\n * @return {Object}\n * @api public\n */\n\nexports.parse = function(url){\n var a = document.createElement('a');\n a.href = url;\n return {\n href: a.href,\n host: a.host,\n port: a.port,\n hash: a.hash,\n hostname: a.hostname,\n pathname: a.pathname,\n protocol: a.protocol,\n search: a.search,\n query: a.search.slice(1)\n }\n};\n\n/**\n * Check if `url` is absolute.\n *\n * @param {String} url\n * @return {Boolean}\n * @api public\n */\n\nexports.isAbsolute = function(url){\n if (0 == url.indexOf('//')) return true;\n if (~url.indexOf('://')) return true;\n return false;\n};\n\n/**\n * Check if `url` is relative.\n *\n * @param {String} url\n * @return {Boolean}\n * @api public\n */\n\nexports.isRelative = function(url){\n return ! exports.isAbsolute(url);\n};\n\n/**\n * Check if `url` is cross domain.\n *\n * @param {String} url\n * @return {Boolean}\n * @api public\n */\n\nexports.isCrossDomain = function(url){\n url = exports.parse(url);\n return url.hostname != location.hostname\n || url.port != location.port\n || url.protocol != location.protocol;\n};\n});\nrequire.register(\"component-bind/index.js\", function(exports, require, module){\n/**\n * Slice reference.\n */\n\nvar slice = [].slice;\n\n/**\n * Bind `obj` to `fn`.\n *\n * @param {Object} obj\n * @param {Function|String} fn or string\n * @return {Function}\n * @api public\n */\n\nmodule.exports = function(obj, fn){\n if ('string' == typeof fn) fn = obj[fn];\n if ('function' != typeof fn) throw new Error('bind() requires a function');\n var args = slice.call(arguments, 2);\n return function(){\n return fn.apply(obj, args.concat(slice.call(arguments)));\n }\n};\n\n});\nrequire.register(\"segmentio-bind-all/index.js\", function(exports, require, module){\n\ntry {\n var bind = require('bind');\n var type = require('type');\n} catch (e) {\n var bind = require('bind-component');\n var type = require('type-component');\n}\n\nmodule.exports = function (obj) {\n for (var key in obj) {\n var val = obj[key];\n if (type(val) === 'function') obj[key] = bind(obj, obj[key]);\n }\n return obj;\n};\n});\nrequire.register(\"ianstormtaylor-bind/index.js\", function(exports, require, module){\n\ntry {\n var bind = require('bind');\n} catch (e) {\n var bind = require('bind-component');\n}\n\nvar bindAll = require('bind-all');\n\n\n/**\n * Expose `bind`.\n */\n\nmodule.exports = exports = bind;\n\n\n/**\n * Expose `bindAll`.\n */\n\nexports.all = bindAll;\n\n\n/**\n * Expose `bindMethods`.\n */\n\nexports.methods = bindMethods;\n\n\n/**\n * Bind `methods` on `obj` to always be called with the `obj` as context.\n *\n * @param {Object} obj\n * @param {String} methods...\n */\n\nfunction bindMethods (obj, methods) {\n methods = [].slice.call(arguments, 1);\n for (var i = 0, method; method = methods[i]; i++) {\n obj[method] = bind(obj, obj[method]);\n }\n return obj;\n}\n});\nrequire.register(\"timoxley-next-tick/index.js\", function(exports, require, module){\n\"use strict\"\n\nif (typeof setImmediate == 'function') {\n module.exports = function(f){ setImmediate(f) }\n}\n// legacy node.js\nelse if (typeof process != 'undefined' && typeof process.nextTick == 'function') {\n module.exports = process.nextTick\n}\n// fallback for other environments / postMessage behaves badly on IE8\nelse if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {\n module.exports = function(f){ setTimeout(f) };\n} else {\n var q = [];\n\n window.addEventListener('message', function(){\n var i = 0;\n while (i < q.length) {\n try { q[i++](); }\n catch (e) {\n q = q.slice(i);\n window.postMessage('tic!', '*');\n throw e;\n }\n }\n q.length = 0;\n }, true);\n\n module.exports = function(fn){\n if (!q.length) window.postMessage('tic!', '*');\n q.push(fn);\n }\n}\n\n});\nrequire.register(\"ianstormtaylor-callback/index.js\", function(exports, require, module){\nvar next = require('next-tick');\n\n\n/**\n * Expose `callback`.\n */\n\nmodule.exports = callback;\n\n\n/**\n * Call an `fn` back synchronously if it exists.\n *\n * @param {Function} fn\n */\n\nfunction callback (fn) {\n if ('function' === typeof fn) fn();\n}\n\n\n/**\n * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the\n * `fn` will be called on next tick.\n *\n * @param {Function} fn\n * @param {Number} wait (optional)\n */\n\ncallback.async = function (fn, wait) {\n if ('function' !== typeof fn) return;\n if (!wait) return next(fn);\n setTimeout(fn, wait);\n};\n\n\n/**\n * Symmetry.\n */\n\ncallback.sync = callback;\n\n});\nrequire.register(\"ianstormtaylor-is-empty/index.js\", function(exports, require, module){\n\n/**\n * Expose `isEmpty`.\n */\n\nmodule.exports = isEmpty;\n\n\n/**\n * Has.\n */\n\nvar has = Object.prototype.hasOwnProperty;\n\n\n/**\n * Test whether a value is \"empty\".\n *\n * @param {Mixed} val\n * @return {Boolean}\n */\n\nfunction isEmpty (val) {\n if (null == val) return true;\n if ('number' == typeof val) return 0 === val;\n if (undefined !== val.length) return 0 === val.length;\n for (var key in val) if (has.call(val, key)) return false;\n return true;\n}\n});\nrequire.register(\"ianstormtaylor-is/index.js\", function(exports, require, module){\n\nvar isEmpty = require('is-empty');\n\ntry {\n var typeOf = require('type');\n} catch (e) {\n var typeOf = require('component-type');\n}\n\n\n/**\n * Types.\n */\n\nvar types = [\n 'arguments',\n 'array',\n 'boolean',\n 'date',\n 'element',\n 'function',\n 'null',\n 'number',\n 'object',\n 'regexp',\n 'string',\n 'undefined'\n];\n\n\n/**\n * Expose type checkers.\n *\n * @param {Mixed} value\n * @return {Boolean}\n */\n\nfor (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);\n\n\n/**\n * Add alias for `function` for old browsers.\n */\n\nexports.fn = exports['function'];\n\n\n/**\n * Expose `empty` check.\n */\n\nexports.empty = isEmpty;\n\n\n/**\n * Expose `nan` check.\n */\n\nexports.nan = function (val) {\n return exports.number(val) && val != val;\n};\n\n\n/**\n * Generate a type checker.\n *\n * @param {String} type\n * @return {Function}\n */\n\nfunction generate (type) {\n return function (value) {\n return type === typeOf(value);\n };\n}\n});\nrequire.register(\"segmentio-after/index.js\", function(exports, require, module){\n\nmodule.exports = function after (times, func) {\n // After 0, really?\n if (times <= 0) return func();\n\n // That's more like it.\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n};\n});\nrequire.register(\"component-domify/index.js\", function(exports, require, module){\n\n/**\n * Expose `parse`.\n */\n\nmodule.exports = parse;\n\n/**\n * Wrap map from jquery.\n */\n\nvar map = {\n legend: [1, '
', '
'],\n tr: [2, '', '
'],\n col: [2, '', '
'],\n _default: [0, '', '']\n};\n\nmap.td =\nmap.th = [3, '', '
'];\n\nmap.option =\nmap.optgroup = [1, ''];\n\nmap.thead =\nmap.tbody =\nmap.colgroup =\nmap.caption =\nmap.tfoot = [1, '', '
'];\n\nmap.text =\nmap.circle =\nmap.ellipse =\nmap.line =\nmap.path =\nmap.polygon =\nmap.polyline =\nmap.rect = [1, '',''];\n\n/**\n * Parse `html` and return the children.\n *\n * @param {String} html\n * @return {Array}\n * @api private\n */\n\nfunction parse(html) {\n if ('string' != typeof html) throw new TypeError('String expected');\n\n html = html.replace(/^\\s+|\\s+$/g, ''); // Remove leading/trailing whitespace\n\n // tag name\n var m = /<([\\w:]+)/.exec(html);\n if (!m) return document.createTextNode(html);\n var tag = m[1];\n\n // body support\n if (tag == 'body') {\n var el = document.createElement('html');\n el.innerHTML = html;\n return el.removeChild(el.lastChild);\n }\n\n // wrap map\n var wrap = map[tag] || map._default;\n var depth = wrap[0];\n var prefix = wrap[1];\n var suffix = wrap[2];\n var el = document.createElement('div');\n el.innerHTML = prefix + html + suffix;\n while (depth--) el = el.lastChild;\n\n // one element\n if (el.firstChild == el.lastChild) {\n return el.removeChild(el.firstChild);\n }\n\n // several elements\n var fragment = document.createDocumentFragment();\n while (el.firstChild) {\n fragment.appendChild(el.removeChild(el.firstChild));\n }\n\n return fragment;\n}\n\n});\nrequire.register(\"component-once/index.js\", function(exports, require, module){\n\n/**\n * Identifier.\n */\n\nvar n = 0;\n\n/**\n * Global.\n */\n\nvar global = (function(){ return this })();\n\n/**\n * Make `fn` callable only once.\n *\n * @param {Function} fn\n * @return {Function}\n * @api public\n */\n\nmodule.exports = function(fn) {\n var id = n++;\n\n function once(){\n // no receiver\n if (this == global) {\n if (once.called) return;\n once.called = true;\n return fn.apply(this, arguments);\n }\n\n // receiver\n var key = '__called_' + id + '__';\n if (this[key]) return;\n this[key] = true;\n return fn.apply(this, arguments);\n }\n\n return once;\n};\n\n});\nrequire.register(\"segmentio-alias/index.js\", function(exports, require, module){\n\nvar type = require('type');\n\ntry {\n var clone = require('clone');\n} catch (e) {\n var clone = require('clone-component');\n}\n\n\n/**\n * Expose `alias`.\n */\n\nmodule.exports = alias;\n\n\n/**\n * Alias an `object`.\n *\n * @param {Object} obj\n * @param {Mixed} method\n */\n\nfunction alias (obj, method) {\n switch (type(method)) {\n case 'object': return aliasByDictionary(clone(obj), method);\n case 'function': return aliasByFunction(clone(obj), method);\n }\n}\n\n\n/**\n * Convert the keys in an `obj` using a dictionary of `aliases`.\n *\n * @param {Object} obj\n * @param {Object} aliases\n */\n\nfunction aliasByDictionary (obj, aliases) {\n for (var key in aliases) {\n if (undefined === obj[key]) continue;\n obj[aliases[key]] = obj[key];\n delete obj[key];\n }\n return obj;\n}\n\n\n/**\n * Convert the keys in an `obj` using a `convert` function.\n *\n * @param {Object} obj\n * @param {Function} convert\n */\n\nfunction aliasByFunction (obj, convert) {\n // have to create another object so that ie8 won't infinite loop on keys\n var output = {};\n for (var key in obj) output[convert(key)] = obj[key];\n return output;\n}\n});\nrequire.register(\"ianstormtaylor-to-no-case/index.js\", function(exports, require, module){\n\n/**\n * Expose `toNoCase`.\n */\n\nmodule.exports = toNoCase;\n\n\n/**\n * Test whether a string is camel-case.\n */\n\nvar hasSpace = /\\s/;\nvar hasCamel = /[a-z][A-Z]/;\nvar hasSeparator = /[\\W_]/;\n\n\n/**\n * Remove any starting case from a `string`, like camel or snake, but keep\n * spaces and punctuation that may be important otherwise.\n *\n * @param {String} string\n * @return {String}\n */\n\nfunction toNoCase (string) {\n if (hasSpace.test(string)) return string.toLowerCase();\n\n if (hasSeparator.test(string)) string = unseparate(string);\n if (hasCamel.test(string)) string = uncamelize(string);\n return string.toLowerCase();\n}\n\n\n/**\n * Separator splitter.\n */\n\nvar separatorSplitter = /[\\W_]+(.|$)/g;\n\n\n/**\n * Un-separate a `string`.\n *\n * @param {String} string\n * @return {String}\n */\n\nfunction unseparate (string) {\n return string.replace(separatorSplitter, function (m, next) {\n return next ? ' ' + next : '';\n });\n}\n\n\n/**\n * Camelcase splitter.\n */\n\nvar camelSplitter = /(.)([A-Z]+)/g;\n\n\n/**\n * Un-camelcase a `string`.\n *\n * @param {String} string\n * @return {String}\n */\n\nfunction uncamelize (string) {\n return string.replace(camelSplitter, function (m, previous, uppers) {\n return previous + ' ' + uppers.toLowerCase().split('').join(' ');\n });\n}\n});\nrequire.register(\"segmentio-analytics.js-integration/lib/index.js\", function(exports, require, module){\n\nvar bind = require('bind');\nvar callback = require('callback');\nvar clone = require('clone');\nvar debug = require('debug');\nvar defaults = require('defaults');\nvar protos = require('./protos');\nvar slug = require('slug');\nvar statics = require('./statics');\n\n\n/**\n * Expose `createIntegration`.\n */\n\nmodule.exports = createIntegration;\n\n\n/**\n * Create a new Integration constructor.\n *\n * @param {String} name\n */\n\nfunction createIntegration (name) {\n\n /**\n * Initialize a new `Integration`.\n *\n * @param {Object} options\n */\n\n function Integration (options) {\n this.debug = debug('analytics:integration:' + slug(name));\n this.options = defaults(clone(options) || {}, this.defaults);\n this._queue = [];\n this.once('ready', bind(this, this.flush));\n\n Integration.emit('construct', this);\n this._wrapInitialize();\n this._wrapLoad();\n this._wrapPage();\n this._wrapTrack();\n }\n\n Integration.prototype.defaults = {};\n Integration.prototype.globals = [];\n Integration.prototype.name = name;\n for (var key in statics) Integration[key] = statics[key];\n for (var key in protos) Integration.prototype[key] = protos[key];\n return Integration;\n}\n\n});\nrequire.register(\"segmentio-analytics.js-integration/lib/protos.js\", function(exports, require, module){\n\n/**\n * Module dependencies.\n */\n\nvar normalize = require('to-no-case');\nvar after = require('after');\nvar callback = require('callback');\nvar Emitter = require('emitter');\nvar tick = require('next-tick');\nvar events = require('./events');\nvar type = require('type');\n\n\n/**\n * Mixin emitter.\n */\n\nEmitter(exports);\n\n/**\n * Initialize.\n */\n\nexports.initialize = function () {\n this.load();\n};\n\n\n/**\n * Loaded?\n *\n * @return {Boolean}\n * @api private\n */\n\nexports.loaded = function () {\n return false;\n};\n\n\n/**\n * Load.\n *\n * @param {Function} cb\n */\n\nexports.load = function (cb) {\n callback.async(cb);\n};\n\n\n/**\n * Page.\n *\n * @param {Page} page\n */\n\nexports.page = function(page){};\n\n/**\n * Track.\n *\n * @param {Track} track\n */\n\nexports.track = function(track){};\n\n/**\n * Get events that match `str`.\n * \n * Examples:\n * \n * events = { my_event: 'a4991b88' }\n * .map(events, 'My Event');\n * // => [\"a4991b88\"]\n * .map(events, 'whatever');\n * // => []\n * \n * events = [{ key: 'my event', value: '9b5eb1fa' }]\n * .map(events, 'my_event');\n * // => [\"9b5eb1fa\"]\n * .map(events, 'whatever');\n * // => []\n * \n * @param {String} str\n * @return {Array}\n * @api public\n */\n\nexports.map = function(obj, str){\n var a = normalize(str);\n var ret = [];\n\n // noop\n if (!obj) return ret;\n\n // object\n if ('object' == type(obj)) {\n for (var k in obj) {\n var item = obj[k];\n var b = normalize(k);\n if (b == a) ret.push(item);\n }\n }\n\n // array\n if ('array' == type(obj)) {\n if (!obj.length) return ret;\n if (!obj[0].key) return ret;\n\n for (var i = 0; i < obj.length; ++i) {\n var item = obj[i];\n var b = normalize(item.key);\n if (b == a) ret.push(item.value);\n }\n }\n\n return ret;\n};\n\n/**\n * Invoke a `method` that may or may not exist on the prototype with `args`,\n * queueing or not depending on whether the integration is \"ready\". Don't\n * trust the method call, since it contains integration party code.\n *\n * @param {String} method\n * @param {Mixed} args...\n * @api private\n */\n\nexports.invoke = function (method) {\n if (!this[method]) return;\n var args = [].slice.call(arguments, 1);\n if (!this._ready) return this.queue(method, args);\n var ret;\n\n try {\n this.debug('%s with %o', method, args);\n ret = this[method].apply(this, args);\n } catch (e) {\n this.debug('error %o calling %s with %o', e, method, args);\n }\n\n return ret;\n};\n\n\n/**\n * Queue a `method` with `args`. If the integration assumes an initial\n * pageview, then let the first call to `page` pass through.\n *\n * @param {String} method\n * @param {Array} args\n * @api private\n */\n\nexports.queue = function (method, args) {\n if ('page' == method && this._assumesPageview && !this._initialized) {\n return this.page.apply(this, args);\n }\n\n this._queue.push({ method: method, args: args });\n};\n\n\n/**\n * Flush the internal queue.\n *\n * @api private\n */\n\nexports.flush = function () {\n this._ready = true;\n var call;\n while (call = this._queue.shift()) this[call.method].apply(this, call.args);\n};\n\n\n/**\n * Reset the integration, removing its global variables.\n *\n * @api private\n */\n\nexports.reset = function () {\n for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;\n};\n\n\n/**\n * Wrap the initialize method in an exists check, so we don't have to do it for\n * every single integration.\n *\n * @api private\n */\n\nexports._wrapInitialize = function () {\n var initialize = this.initialize;\n this.initialize = function () {\n this.debug('initialize');\n this._initialized = true;\n var ret = initialize.apply(this, arguments);\n this.emit('initialize');\n\n var self = this;\n if (this._readyOnInitialize) {\n tick(function () {\n self.emit('ready');\n });\n }\n \n return ret;\n };\n\n if (this._assumesPageview) this.initialize = after(2, this.initialize);\n};\n\n\n/**\n * Wrap the load method in `debug` calls, so every integration gets them\n * automatically.\n *\n * @api private\n */\n\nexports._wrapLoad = function () {\n var load = this.load;\n this.load = function (callback) {\n var self = this;\n this.debug('loading');\n\n if (this.loaded()) {\n this.debug('already loaded');\n tick(function () {\n if (self._readyOnLoad) self.emit('ready');\n callback && callback();\n });\n return;\n }\n\n return load.call(this, function (err, e) {\n self.debug('loaded');\n self.emit('load');\n if (self._readyOnLoad) self.emit('ready');\n callback && callback(err, e);\n });\n };\n};\n\n\n/**\n * Wrap the page method to call `initialize` instead if the integration assumes\n * a pageview.\n *\n * @api private\n */\n\nexports._wrapPage = function () {\n var page = this.page;\n this.page = function () {\n if (this._assumesPageview && !this._initialized) {\n return this.initialize.apply(this, arguments);\n }\n \n return page.apply(this, arguments);\n };\n};\n\n/**\n * Wrap the track method to call other ecommerce methods if\n * available depending on the `track.event()`.\n *\n * @api private\n */\n\nexports._wrapTrack = function(){\n var t = this.track;\n this.track = function(track){\n var event = track.event();\n var called;\n var ret;\n\n for (var method in events) {\n var regexp = events[method];\n if (!this[method]) continue;\n if (!regexp.test(event)) continue;\n ret = this[method].apply(this, arguments);\n called = true;\n break;\n }\n\n if (!called) ret = t.apply(this, arguments);\n return ret;\n };\n};\n\n});\nrequire.register(\"segmentio-analytics.js-integration/lib/events.js\", function(exports, require, module){\n\n/**\n * Expose `events`\n */\n\nmodule.exports = {\n removedProduct: /removed[ _]?product/i,\n viewedProduct: /viewed[ _]?product/i,\n addedProduct: /added[ _]?product/i,\n completedOrder: /completed[ _]?order/i\n};\n\n});\nrequire.register(\"segmentio-analytics.js-integration/lib/statics.js\", function(exports, require, module){\n\nvar after = require('after');\nvar Emitter = require('emitter');\n\n\n/**\n * Mixin emitter.\n */\n\nEmitter(exports);\n\n\n/**\n * Add a new option to the integration by `key` with default `value`.\n *\n * @param {String} key\n * @param {Mixed} value\n * @return {Integration}\n */\n\nexports.option = function (key, value) {\n this.prototype.defaults[key] = value;\n return this;\n};\n\n/**\n * Add a new mapping option.\n * \n * the method will create a method `name` that will return a mapping\n * for you to use.\n * \n * Example:\n * \n * Integration('My Integration')\n * .mapping('events');\n * \n * new MyIntegration().track('My Event');\n * \n * .track = function(track){\n * var events = this.events(track.event());\n * each(events, send);\n * };\n * \n * @param {String} name\n * @return {Integration}\n * @api public\n */\n\nexports.mapping = function(name){\n this.option(name, []);\n this.prototype[name] = function(str){\n return this.map(this.options[name], str);\n };\n return this;\n};\n\n/**\n * Register a new global variable `key` owned by the integration, which will be\n * used to test whether the integration is already on the page.\n *\n * @param {String} global\n * @return {Integration}\n */\n\nexports.global = function (key) {\n this.prototype.globals.push(key);\n return this;\n};\n\n\n/**\n * Mark the integration as assuming an initial pageview, so to defer loading\n * the script until the first `page` call, noop the first `initialize`.\n *\n * @return {Integration}\n */\n\nexports.assumesPageview = function () {\n this.prototype._assumesPageview = true;\n return this;\n};\n\n\n/**\n * Mark the integration as being \"ready\" once `load` is called.\n *\n * @return {Integration}\n */\n\nexports.readyOnLoad = function () {\n this.prototype._readyOnLoad = true;\n return this;\n};\n\n\n/**\n * Mark the integration as being \"ready\" once `load` is called.\n *\n * @return {Integration}\n */\n\nexports.readyOnInitialize = function () {\n this.prototype._readyOnInitialize = true;\n return this;\n};\n\n});\nrequire.register(\"segmentio-convert-dates/index.js\", function(exports, require, module){\n\nvar is = require('is');\n\ntry {\n var clone = require('clone');\n} catch (e) {\n var clone = require('clone-component');\n}\n\n\n/**\n * Expose `convertDates`.\n */\n\nmodule.exports = convertDates;\n\n\n/**\n * Recursively convert an `obj`'s dates to new values.\n *\n * @param {Object} obj\n * @param {Function} convert\n * @return {Object}\n */\n\nfunction convertDates (obj, convert) {\n obj = clone(obj);\n for (var key in obj) {\n var val = obj[key];\n if (is.date(val)) obj[key] = convert(val);\n if (is.object(val)) obj[key] = convertDates(val, convert);\n }\n return obj;\n}\n});\nrequire.register(\"segmentio-global-queue/index.js\", function(exports, require, module){\n\n/**\n * Expose `generate`.\n */\n\nmodule.exports = generate;\n\n\n/**\n * Generate a global queue pushing method with `name`.\n *\n * @param {String} name\n * @param {Object} options\n * @property {Boolean} wrap\n * @return {Function}\n */\n\nfunction generate (name, options) {\n options = options || {};\n\n return function (args) {\n args = [].slice.call(arguments);\n window[name] || (window[name] = []);\n options.wrap === false\n ? window[name].push.apply(window[name], args)\n : window[name].push(args);\n };\n}\n});\nrequire.register(\"segmentio-load-date/index.js\", function(exports, require, module){\n\n\n/*\n * Load date.\n *\n * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/\n */\n\nvar time = new Date()\n , perf = window.performance;\n\nif (perf && perf.timing && perf.timing.responseEnd) {\n time = new Date(perf.timing.responseEnd);\n}\n\nmodule.exports = time;\n});\nrequire.register(\"segmentio-load-script/index.js\", function(exports, require, module){\nvar type = require('type');\n\n\nmodule.exports = function loadScript (options, callback) {\n if (!options) throw new Error('Cant load nothing...');\n\n // Allow for the simplest case, just passing a `src` string.\n if (type(options) === 'string') options = { src : options };\n\n var https = document.location.protocol === 'https:' ||\n document.location.protocol === 'chrome-extension:';\n\n // If you use protocol relative URLs, third-party scripts like Google\n // Analytics break when testing with `file:` so this fixes that.\n if (options.src && options.src.indexOf('//') === 0) {\n options.src = https ? 'https:' + options.src : 'http:' + options.src;\n }\n\n // Allow them to pass in different URLs depending on the protocol.\n if (https && options.https) options.src = options.https;\n else if (!https && options.http) options.src = options.http;\n\n // Make the `