<commit_before>(function() {
  'use strict';

  function listenToClick(element, name, fn) {
    if (document.addEventListener) {
      element.addEventListener(name, fn, false);
    } else {
      element.attachEvent((name === 'click') ? 'onclick' : name, fn);
    }
  }

  function handleClicks(elem, fn) {

    if (document.addEventListener) {
      // For all major browsers, except IE 8 and earlier
      elem.addEventListener("click", fn, false);
      elem.addEventListener("touchstart", fn, false);
    } else if (document.attachEvent) {
      // For IE 8 and earlier versions
      elem.attachEvent("onclick", fn, false);
      elem.attachEvent("touchstart", fn, false);
    }
  };

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  }

  domready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        my_removeClass(element, 'disabled');
      } else {
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    each(document.querySelectorAll('[data-clipboard-target]'), function(el) {
      var
        clipboard,
        notification;

      clipboard = new Clipboard(el);

      var notify = function(clipboardNotification, notificationText) {
        notification = document.getElementById(clipboardNotification.slice(1));
        notification.textContent = notificationText;
        my_addClass(notification, 'in');
        setTimeout(function() {
          my_removeClass(notification, 'in');
        }, 1400);
      };

      var notifySuccess = function(e) {
        notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
        //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
        notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
      handleClicks(el, function(e) {
        if (window.parent.squatch.eventBus) {
          window.parent.squatch.eventBus.dispatch('copy_btn_clicked', e.type);
        }
      });
    });

    each(scrollElements, function(el) {
      var
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      listenToClick(el, 'click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    });

    each(document.querySelectorAll('[data-moment]'), function(el) {
      var time = moment(parseInt(el.textContent));
      el.textContent = time.fromNow();
    });

    each(document.getElementsByClassName('squatch-header-close'), function(el) {
      handleClicks(el, function(e) {
        if (window.parent.squatch.eventBus) {
          window.parent.squatch.eventBus.dispatch('close_popup', e.type);
        }
      });
    });

    // Popup stuff
    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    each(document.querySelectorAll('[data-scroll-reset]'), function(el) {
      var element = document.getElementById(el.dataset.scrollReset.slice(1));
      console.log(element);

      element.onclick = function() {
        console.log("clicked", element);
      }
    })

    var setContainerHeight = function(containerEl) {
      // TODO: Refactor this to make simpler
      var
        bodyEl,
        bodyHeight,
        bodyHeightWithoutTitle,
        titleEl,
        titleStyle,
        panelEl,
        referralsEl,
        referralsTitleEl,
        panelHeight,
        css,
        stylesheet;

      bodyEl           = document.getElementsByClassName('squatch-body')[0];
      titleEl          = document.getElementsByClassName('squatch-title')[0];
      titleStyle       = getComputedStyle(titleEl);
      panelEl          = document.getElementById('squatch-panel');
      referralsEl      = document.getElementsByClassName('squatch-referrals')[0];
      referralsTitleEl = document.getElementsByClassName('squatch-referrals-title')[0];

      bodyHeight = bodyEl.offsetHeight;
      bodyHeightWithoutTitle = bodyHeight - titleEl.offsetHeight - parseInt(titleStyle.marginTop) - parseInt(titleStyle.marginBottom) - titleEl.offsetTop;
      panelHeight = panelEl.offsetHeight;

      if (referralsEl.style.display !== 'none') {
        panelHeight -= referralsEl.offsetHeight;
      }

      if (referralsTitleEl.style.display !== 'none') {
        panelHeight -= referralsTitleEl.offsetHeight;
      }

      // containerEl.css('height', bodyHeight + panelHeight);
      containerEl.style.height = bodyHeight + panelHeight;

      stylesheet = document.createElement('style');
      stylesheet.type = 'text/css';

      css = '#squatch-panel.open {' +
        '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '}' +
        'html.lt-ie9 #squatch-panel.open {' +
        'top: -' + bodyHeightWithoutTitle + 'px;' +
        '}';

      if (stylesheet.styleSheet){
        // IE
        stylesheet.styleSheet.cssText = css;
      } else {
        // W3C Standard
        stylesheet.appendChild(document.createTextNode(css));
      }

      document.querySelector('head').appendChild(stylesheet);
    };

    var containerEl = $('.squatch-container-popup');
    if (containerEl.length) {
     var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
     var windowEl = $(window);

     windowEl.on('load', function () {
       setContainerHeightForPopup();
     });

    }
  });

})();
<commit_msg>Start translating to javascript<commit_after>(function() {
  'use strict';

  function listenToClick(element, name, fn) {
    if (document.addEventListener) {
      element.addEventListener(name, fn, false);
    } else {
      element.attachEvent((name === 'click') ? 'onclick' : name, fn);
    }
  }

  function handleClicks(elem, fn) {

    if (document.addEventListener) {
      // For all major browsers, except IE 8 and earlier
      elem.addEventListener("click", fn, false);
      elem.addEventListener("touchstart", fn, false);
    } else if (document.attachEvent) {
      // For IE 8 and earlier versions
      elem.attachEvent("onclick", fn, false);
      elem.attachEvent("touchstart", fn, false);
    }
  };

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  }

  domready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        my_removeClass(element, 'disabled');
      } else {
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    each(document.querySelectorAll('[data-clipboard-target]'), function(el) {
      var
        clipboard,
        notification;

      clipboard = new Clipboard(el);

      var notify = function(clipboardNotification, notificationText) {
        notification = document.getElementById(clipboardNotification.slice(1));
        notification.textContent = notificationText;
        my_addClass(notification, 'in');
        setTimeout(function() {
          my_removeClass(notification, 'in');
        }, 1400);
      };

      var notifySuccess = function(e) {
        notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
        //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
        notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
      handleClicks(el, function(e) {
        if (window.parent.squatch.eventBus) {
          window.parent.squatch.eventBus.dispatch('copy_btn_clicked', e.type);
        }
      });
    });

    each(scrollElements, function(el) {
      var
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      listenToClick(el, 'click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    });

    each(document.querySelectorAll('[data-moment]'), function(el) {
      var time = moment(parseInt(el.textContent));
      el.textContent = time.fromNow();
    });

    each(document.getElementsByClassName('squatch-header-close'), function(el) {
      handleClicks(el, function(e) {
        if (window.parent.squatch.eventBus) {
          window.parent.squatch.eventBus.dispatch('close_popup', e.type);
        }
      });
    });

    // Popup stuff
    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    each(document.querySelectorAll('[data-scroll-reset]'), function(el) {
      var element = document.getElementById(el.dataset.scrollReset.slice(1));
      console.log(element);

      element.onclick = function() {
        console.log("clicked", element);
      }
    })

    var setContainerHeight = function(containerEl) {
      // TODO: Refactor this to make simpler
      var
        bodyEl,
        bodyHeight,
        bodyHeightWithoutTitle,
        titleEl,
        titleStyle,
        panelEl,
        referralsEl,
        referralsTitleEl,
        panelHeight,
        css,
        stylesheet;

      bodyEl           = document.getElementsByClassName('squatch-body')[0];
      titleEl          = document.getElementsByClassName('squatch-title')[0];
      titleStyle       = getComputedStyle(titleEl);
      panelEl          = document.getElementById('squatch-panel');
      referralsEl      = document.getElementsByClassName('squatch-referrals')[0];
      referralsTitleEl = document.getElementsByClassName('squatch-referrals-title')[0];

      bodyHeight = bodyEl.offsetHeight;
      bodyHeightWithoutTitle = bodyHeight - titleEl.offsetHeight - parseInt(titleStyle.marginTop) - parseInt(titleStyle.marginBottom) - titleEl.offsetTop;
      panelHeight = panelEl.offsetHeight;

      if (referralsEl.style.display !== 'none') {
        panelHeight -= referralsEl.offsetHeight;
      }

      if (referralsTitleEl.style.display !== 'none') {
        panelHeight -= referralsTitleEl.offsetHeight;
      }

      // containerEl.css('height', bodyHeight + panelHeight);
      console.log(containerEl);
      containerEl.style.height = bodyHeight + panelHeight;

      stylesheet = document.createElement('style');
      stylesheet.type = 'text/css';

      css = '#squatch-panel.open {' +
        '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
        '}' +
        'html.lt-ie9 #squatch-panel.open {' +
        'top: -' + bodyHeightWithoutTitle + 'px;' +
        '}';

      if (stylesheet.styleSheet){
        // IE
        stylesheet.styleSheet.cssText = css;
      } else {
        // W3C Standard
        stylesheet.appendChild(document.createTextNode(css));
      }

      document.querySelector('head').appendChild(stylesheet);
    };

    var containerEl = $('.squatch-container-popup');
    if (containerEl.length) {
     var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
     var windowEl = $(window);

     windowEl.on('load', function () {
       setContainerHeightForPopup();
     });

    }
  });

})();
<|endoftext|>


<commit_before>// Adapted from code by Matt Walters https://www.mattwalters.net/posts/hugo-and-lunr/

(function ($) {
    'use strict';

    $(document).ready(function () {
        const $searchInput = $('.td-search-input');

        //
        // Options for popover
        //

        $searchInput.data('html', true);
        $searchInput.data('placement', 'bottom');
        $searchInput.data(
            'template',
            '

'
        );

        //
        // Register handler
        //

        $searchInput.on('change', (event) => {
            render($(event.target));

            // Hide keyboard on mobile browser
            $searchInput.blur();
        });

        // Prevent reloading page by enter key on sidebar search.
        $searchInput.closest('form').on('submit', () => {
            return false;
        });

        //
        // Lunr
        //

        let idx = null; // Lunr index
        const resultDetails = new Map(); // Will hold the data for the search results (titles and summaries)

        // Set up for an Ajax call to request the JSON data file that is created by Hugo's build process
        $.ajax($searchInput.data('offline-search-index-json-src')).then(
            (data) => {
                idx = lunr(function () {
                    this.ref('ref');
                    this.field('title', { boost: 2 });
                    this.field('body');

                    data.forEach((doc) => {
                        this.add(doc);

                        resultDetails.set(doc.ref, {
                            title: doc.title,
                            excerpt: doc.excerpt,
                        });
                    });
                });

                $searchInput.trigger('change');
            }
        );

        const render = ($targetSearchInput) => {
            // Dispose the previous result
            $targetSearchInput.popover('dispose');

            //
            // Search
            //

            if (idx === null) {
                return;
            }

            const searchQuery = $targetSearchInput.val();
            if (searchQuery === '') {
                return;
            }

            const results = idx
                .query((q) => {
                    const tokens = lunr.tokenizer(searchQuery.toLowerCase());
                    tokens.forEach((token) => {
                        const queryString = token.toString();
                        q.term(queryString, {
                            boost: 100,
                        });
                        q.term(queryString, {
                            wildcard:
                                lunr.Query.wildcard.LEADING |
                                lunr.Query.wildcard.TRAILING,
                            boost: 10,
                        });
                        q.term(queryString, {
                            editDistance: 2,
                        });
                    });
                })
                .slice(0, 10);

            //
            // Make result html
            //

            const $html = $('
');

            $html.append(
                $('
')
                    .css({
                        display: 'flex',
                        justifyContent: 'space-between',
                        marginBottom: '1em',
                    })
                    .append(
                        $('')
                            .text('Search results')
                            .css({ fontWeight: 'bold' })
                    )
                    .append(
                        $('')
                            .addClass('fas fa-times search-result-close-button')
                            .css({
                                cursor: 'pointer',
                            })
                    )
            );

            const $searchResultBody = $('
').css({
                maxHeight: `calc(100vh - ${
                    $targetSearchInput.offset().top -
                    $(window).scrollTop() +
                    180
                }px)`,
                overflowY: 'auto',
            });
            $html.append($searchResultBody);

            if (results.length === 0) {
                $searchResultBody.append(
                    $('
').text(`No results found for query "${searchQuery}"`)
                );
            } else {
                results.forEach((r) => {
                    const $cardHeader = $('
').addClass('card-header');
                    const doc = resultDetails.get(r.ref);
                    const href =
                        $searchInput.data('offline-search-base-href') +
                        r.ref.replace(/^\//, '');

                    $cardHeader.append(
                        $('').attr('href', href).text(doc.title)
                    );

                    const $cardBody = $('
').addClass('card-body');
                    $cardBody.append(
                        $('
')
                            .addClass('card-text text-muted')
                            .text(doc.excerpt)
                    );

                    const $card = $('
').addClass('card');
                    $card.append($cardHeader).append($cardBody);

                    $searchResultBody.append($card);
                });
            }

            $targetSearchInput.on('shown.bs.popover', () => {
                $('.search-result-close-button').on('click', () => {
                    $targetSearchInput.val('');
                    $targetSearchInput.trigger('change');
                });
            });

            $targetSearchInput
                .data('content', $html[0].outerHTML)
                .popover('show');
        };
    });
})(jQuery);
<commit_msg>Update offline search result design<commit_after>// Adapted from code by Matt Walters https://www.mattwalters.net/posts/hugo-and-lunr/

(function ($) {
    'use strict';

    $(document).ready(function () {
        const $searchInput = $('.td-search-input');

        //
        // Options for popover
        //

        $searchInput.data('html', true);
        $searchInput.data('placement', 'bottom');
        $searchInput.data(
            'template',
            '

'
        );

        //
        // Register handler
        //

        $searchInput.on('change', (event) => {
            render($(event.target));

            // Hide keyboard on mobile browser
            $searchInput.blur();
        });

        // Prevent reloading page by enter key on sidebar search.
        $searchInput.closest('form').on('submit', () => {
            return false;
        });

        //
        // Lunr
        //

        let idx = null; // Lunr index
        const resultDetails = new Map(); // Will hold the data for the search results (titles and summaries)

        // Set up for an Ajax call to request the JSON data file that is created by Hugo's build process
        $.ajax($searchInput.data('offline-search-index-json-src')).then(
            (data) => {
                idx = lunr(function () {
                    this.ref('ref');
                    this.field('title', { boost: 2 });
                    this.field('body');

                    data.forEach((doc) => {
                        this.add(doc);

                        resultDetails.set(doc.ref, {
                            title: doc.title,
                            excerpt: doc.excerpt,
                        });
                    });
                });

                $searchInput.trigger('change');
            }
        );

        const render = ($targetSearchInput) => {
            // Dispose the previous result
            $targetSearchInput.popover('dispose');

            //
            // Search
            //

            if (idx === null) {
                return;
            }

            const searchQuery = $targetSearchInput.val();
            if (searchQuery === '') {
                return;
            }

            const results = idx
                .query((q) => {
                    const tokens = lunr.tokenizer(searchQuery.toLowerCase());
                    tokens.forEach((token) => {
                        const queryString = token.toString();
                        q.term(queryString, {
                            boost: 100,
                        });
                        q.term(queryString, {
                            wildcard:
                                lunr.Query.wildcard.LEADING |
                                lunr.Query.wildcard.TRAILING,
                            boost: 10,
                        });
                        q.term(queryString, {
                            editDistance: 2,
                        });
                    });
                })
                .slice(0, 10);

            //
            // Make result html
            //

            const $html = $('
');

            $html.append(
                $('
')
                    .css({
                        display: 'flex',
                        justifyContent: 'space-between',
                        marginBottom: '1em',
                    })
                    .append(
                        $('')
                            .text('Search results')
                            .css({ fontWeight: 'bold' })
                    )
                    .append(
                        $('')
                            .addClass('fas fa-times search-result-close-button')
                            .css({
                                cursor: 'pointer',
                            })
                    )
            );

            const $searchResultBody = $('
').css({
                maxHeight: `calc(100vh - ${
                    $targetSearchInput.offset().top -
                    $(window).scrollTop() +
                    180
                }px)`,
                overflowY: 'auto',
            });
            $html.append($searchResultBody);

            if (results.length === 0) {
                $searchResultBody.append(
                    $('
').text(`No results found for query "${searchQuery}"`)
                );
            } else {
                results.forEach((r) => {
                    const doc = resultDetails.get(r.ref);
                    const href =
                        $searchInput.data('offline-search-base-href') +
                        r.ref.replace(/^\//, '');

                    const $entry = $('
').addClass('mt-4');

                    $entry.append(
                        $('').addClass('d-block text-muted').text(r.ref)
                    );

                    $entry.append(
                        $('')
                            .addClass('d-block')
                            .css({
                                fontSize: '1.2rem',
                            })
                            .attr('href', href)
                            .text(doc.title)
                    );

                    $entry.append($('
').text(doc.excerpt));

                    $searchResultBody.append($entry);
                });
            }

            $targetSearchInput.on('shown.bs.popover', () => {
                $('.search-result-close-button').on('click', () => {
                    $targetSearchInput.val('');
                    $targetSearchInput.trigger('change');
                });
            });

            $targetSearchInput
                .data('content', $html[0].outerHTML)
                .popover('show');
        };
    });
})(jQuery);
<|endoftext|>


<commit_before>// Functions for the mobile version
$(document).on("click", '#open_main_menu', open_mobile_menu);
var menu_open = false
function open_mobile_menu () {
  if (menu_open) {
    $('aside').css({'left': '-250px'});
    menu_open = false;
  } else {
    $('aside').css({'left': '0px'});
    menu_open = true
  }
}

var scrolled;
var mainSectionHeight;
var headerHeight;

// always initiate the scroll at the top
$(window).on('beforeunload', function() {
  $(window).scrollTop(0);
});

// get the height of the browser screen
$(window).on('resize', function() {
  headerHeight = $('header').outerHeight();
  mainSectionHeight = $('#opensuse-os').outerHeight() - headerHeight;
  //remove the height in the container of the main section 'home'
  $('#opensuse-os').css('height', '')
  containerHeight = $('#opensuse-os').outerHeight() + 30
})

$(window).bind('scroll',function(e){
  getScrolledData();
});

$(function() {
  $mainMenu = $('#main-menu').html()
  $('aside').html($mainMenu)
  headerHeight = $('header').outerHeight();
  mainSectionHeight = $('#opensuse-os').outerHeight() - headerHeight;
})

var scrolledDown = false;

function getScrolledData() {
  scrolled = $(window).scrollTop();

  // detect if the user has scrolled more than the first section (height) to reduce the size of the menu
  if (scrolled > mainSectionHeight) {
    console.log(mainSectionHeight)
    headerChanges()
    scrolledDown = true;
  }

  if (scrolledDown && scrolled < mainSectionHeight) {
    headerReset()
  }
}

function headerChanges() {
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f',
    top: '0px',
    height: '45px',
    padding: '8px',
    'z-index': '1000'
  })
  $('#opensuseLogo').css({
    height: '25px'
  })
  $('header ul li a').css({
    'font-size': '14px',
    'color': '#fff'
  })

}
function headerReset() {
  $('header').removeAttr('style')
  //but always keep the color applied from the scrolling
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f'
  })
  $('#opensuseLogo').removeAttr('style')
  $('header ul li a').removeAttr('style')
  $('header ul li a').css({
    'color': moreInfoOpened ? '#fff' : ''
  })
}

// init WOW.js
wow = new WOW(
  {
    offset: 30
  }
)
wow.init();

// init OWL slider

$(document).ready(function() {
  $("#owl-slide-news").owlCarousel({

  navigation : true,
  slideSpeed : 300,
  paginationSpeed : 400,
  singleItem : true,
  navigationText : ["",""]
  });
});

// tumbleweed opensuse more information

var moreInfoOpened = false;

$(function() {
  $('#tumbleweed').on('click', function() {
    osMoreInformation($(this))
  })
  $('#openSUSE').on('click', function() {
    osMoreInformation($(this))
  })
})

function osMoreInformation(os) {
  moreInfoOpened = true
  //get the height of the main container
  containerHeight = $('#opensuse-os').outerHeight()

  //find the information of the selected distribution
  $osSelected = os
  title = $osSelected.find("h1").html()
  text = $osSelected.find(".hidden-content").html()
  icon = $osSelected.find(".distributions-icon").html()

  // animation
  $('#opensuse-os .container-fluid').addClass('animated bounceOut')
  $('#opensuse-os').css({
    background: '#4bb67a'
  })
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f'
  })
  console.log(moreInfoOpened ? '#4bb67a' : '#173f4f')
  $('header ul li a').css({
    color: "#fff"
  })

  setTimeout(hideLandingPageInfo, 800)
  setTimeout(createMoreInformationArea, 1300)

  function hideLandingPageInfo () {
    $('#opensuse-os').css({
      height: containerHeight + 'px'
    })
    $('#opensuse-os .container-fluid').hide()
  }
  function createMoreInformationArea () {
    information = '
'
                  + '

'
                  + '
'
                  + title
                  + '
'
                  + '
'
                  + text
                  + '
'
                  + '
'
                  + '
'
                  + ' Back to main page'
                  + '
'
                  + '
'
    $('#opensuse-os').append(information)
    $('.os-icon').html(icon)

    $('.back-to-main-page').on('click', function() {
      backToMainPageOs()
    })
  }
}

function backToMainPageOs () {
  moreInfoOpened = false;
  $('#more-information-os').addClass('animated bounceOut')
  $('header').removeAttr('style')
  $('header ul li a').removeAttr('style')
  $('#opensuse-os').removeAttr('style').css({
      height: containerHeight + 'px'
    })

  setTimeout(hideMoreInformation, 800)
  setTimeout(showMainInformation, 1300)

  function hideMoreInformation () {
    $('#more-information-os').hide()
    $('#more-information-os').remove()

  }

  function showMainInformation () {
    $('#opensuse-os .container-fluid').removeClass('animated bounceOut').show().addClass('animated bounceIn')
  }

}

<commit_msg>Fix: console.logs removed<commit_after>// Functions for the mobile version
$(document).on("click", '#open_main_menu', open_mobile_menu);
var menu_open = false
function open_mobile_menu () {
  if (menu_open) {
    $('aside').css({'left': '-250px'});
    menu_open = false;
  } else {
    $('aside').css({'left': '0px'});
    menu_open = true
  }
}

var scrolled;
var mainSectionHeight;
var headerHeight;

// always initiate the scroll at the top
$(window).on('beforeunload', function() {
  $(window).scrollTop(0);
});

// get the height of the browser screen
$(window).on('resize', function() {
  headerHeight = $('header').outerHeight();
  mainSectionHeight = $('#opensuse-os').outerHeight() - headerHeight;
  //remove the height in the container of the main section 'home'
  $('#opensuse-os').css('height', '')
  containerHeight = $('#opensuse-os').outerHeight() + 30
})

$(window).bind('scroll',function(e){
  getScrolledData();
});

$(function() {
  $mainMenu = $('#main-menu').html()
  $('aside').html($mainMenu)
  headerHeight = $('header').outerHeight();
  mainSectionHeight = $('#opensuse-os').outerHeight() - headerHeight;
})

var scrolledDown = false;

function getScrolledData() {
  scrolled = $(window).scrollTop();

  // detect if the user has scrolled more than the first section (height) to reduce the size of the menu
  if (scrolled > mainSectionHeight) {
    headerChanges()
    scrolledDown = true;
  }

  if (scrolledDown && scrolled < mainSectionHeight) {
    headerReset()
  }
}

function headerChanges() {
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f',
    top: '0px',
    height: '45px',
    padding: '8px',
    'z-index': '1000'
  })
  $('#opensuseLogo').css({
    height: '25px'
  })
  $('header ul li a').css({
    'font-size': '14px',
    'color': '#fff'
  })

}
function headerReset() {
  $('header').removeAttr('style')
  //but always keep the color applied from the scrolling
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f'
  })
  $('#opensuseLogo').removeAttr('style')
  $('header ul li a').removeAttr('style')
  $('header ul li a').css({
    'color': moreInfoOpened ? '#fff' : ''
  })
}

// init WOW.js
wow = new WOW(
  {
    offset: 30
  }
)
wow.init();

// init OWL slider

$(document).ready(function() {
  $("#owl-slide-news").owlCarousel({

  navigation : true,
  slideSpeed : 300,
  paginationSpeed : 400,
  singleItem : true,
  navigationText : ["",""]
  });
});

// tumbleweed opensuse more information

var moreInfoOpened = false;

$(function() {
  $('#tumbleweed').on('click', function() {
    osMoreInformation($(this))
  })
  $('#openSUSE').on('click', function() {
    osMoreInformation($(this))
  })
})

function osMoreInformation(os) {
  moreInfoOpened = true
  //get the height of the main container
  containerHeight = $('#opensuse-os').outerHeight()

  //find the information of the selected distribution
  $osSelected = os
  title = $osSelected.find("h1").html()
  text = $osSelected.find(".hidden-content").html()
  icon = $osSelected.find(".distributions-icon").html()

  // animation
  $('#opensuse-os .container-fluid').addClass('animated bounceOut')
  $('#opensuse-os').css({
    background: '#4bb67a'
  })
  $('header').css({
    background: moreInfoOpened ? '#4bb67a' : '#173f4f'
  })
  $('header ul li a').css({
    color: "#fff"
  })

  setTimeout(hideLandingPageInfo, 800)
  setTimeout(createMoreInformationArea, 1300)

  function hideLandingPageInfo () {
    $('#opensuse-os').css({
      height: containerHeight + 'px'
    })
    $('#opensuse-os .container-fluid').hide()
  }
  function createMoreInformationArea () {
    information = '
'
                  + '

'
                  + '
'
                  + title
                  + '
'
                  + '
'
                  + text
                  + '
'
                  + '
'
                  + '
'
                  + ' Back to main page'
                  + '
'
                  + '
'
    $('#opensuse-os').append(information)
    $('.os-icon').html(icon)

    $('.back-to-main-page').on('click', function() {
      backToMainPageOs()
    })
  }
}

function backToMainPageOs () {
  moreInfoOpened = false;
  $('#more-information-os').addClass('animated bounceOut')
  $('header').removeAttr('style')
  $('header ul li a').removeAttr('style')
  $('#opensuse-os').removeAttr('style').css({
      height: containerHeight + 'px'
    })

  setTimeout(hideMoreInformation, 800)
  setTimeout(showMainInformation, 1300)

  function hideMoreInformation () {
    $('#more-information-os').hide()
    $('#more-information-os').remove()

  }

  function showMainInformation () {
    $('#opensuse-os .container-fluid').removeClass('animated bounceOut').show().addClass('animated bounceIn')
  }

}

<|endoftext|>


<commit_before>define(['knockout', 'knockout-router'], function(ko) {

  function run() {
    var vm = {
      router: ko.router.vm,
      moduleToShow: ko.observable()
    };

    // Can attach a global subscription to be notified for all route changes.
    function notify() {
      console.log(arguments, new Date());
    }

    // Can attach a 'route not found' handler, which will be passed a url fragment and query string.
    function notFoundHandler(fragment, query) {
      console.log(fragment, query);
    }

    // Configure routing options before defining routes
    ko.router.configure({ hashPrefix: '#/', debug: true, notify: notify, pushState: true });

    // Configure module loader
    ko.bindingHandlers.module.baseDir = 'js';

    // Define the routes before ko.applyBindings()
    ko.router.map([
      { route: '', name: 'home', template: 'home', title: 'Welcome', nav: true },
      { route: 'who-we-are', name: 'about', title: 'About Us', nav: true },
      { route: 'contact-us', name: 'contact', title: 'Contact Us', nav: true },
      { route: 'content/news/:articleId', module: 'news' }
      //{ route: 'blog(/:slug)', name: 'blog', title: 'Crazy Blog' },
      //{ route: '*notfound', name: 'notfound', callback: notFoundHandler }
    ]).mapNotFound({ callback: notFoundHandler }); // can specify a module/template/callback/title

    // Bind the view model
    ko.applyBindings(vm);

    // Should call ko.router.init() after ko.applyBindings() when using
    // the route bindingHandler. otherwise could safely call ko.router.init()
    // once the routes have been defined.
    ko.router.init(); //calls ko.history.start() behind the scenes
  }

  return {
    run: run
  };

});<commit_msg>add root path for gh-pages site<commit_after>define(['knockout', 'knockout-router'], function(ko) {

  function run() {
    var vm = {
      router: ko.router.vm,
      moduleToShow: ko.observable()
    };

    // Can attach a global subscription to be notified for all route changes.
    function notify() {
      console.log(arguments, new Date());
    }

    // Can attach a 'route not found' handler, which will be passed a url fragment and query string.
    function notFoundHandler(fragment, query) {
      console.log(fragment, query);
    }

    // Configure routing options before defining routes
    ko.router.configure({ hashPrefix: '#/', debug: true, notify: notify, pushState: true, root: '/knockout-router/' });

    // Configure module loader
    ko.bindingHandlers.module.baseDir = 'js';

    // Define the routes before ko.applyBindings()
    ko.router.map([
      { route: '', name: 'home', template: 'home', title: 'Welcome', nav: true },
      { route: 'who-we-are', name: 'about', title: 'About Us', nav: true },
      { route: 'contact-us', name: 'contact', title: 'Contact Us', nav: true },
      { route: 'content/news/:articleId', module: 'news' }
      //{ route: 'blog(/:slug)', name: 'blog', title: 'Crazy Blog' },
      //{ route: '*notfound', name: 'notfound', callback: notFoundHandler }
    ]).mapNotFound({ callback: notFoundHandler }); // can specify a module/template/callback/title

    // Bind the view model
    ko.applyBindings(vm);

    // Should call ko.router.init() after ko.applyBindings() when using
    // the route bindingHandler. otherwise could safely call ko.router.init()
    // once the routes have been defined.
    ko.router.init(); //calls ko.history.start() behind the scenes
  }

  return {
    run: run
  };

});
<|endoftext|>


<commit_before>"use strict";

//-----------------------------------------------------------------------------

let [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
    , verbose = process.argv.includes ('--verbose')
    , debug = process.argv.includes ('--debug')
    , poll = process.argv.includes ('--poll')
    , no_send = process.argv.includes ('--no-send')
    , no_load_markets = process.argv.includes ('--no-load-markets')
    , details = process.argv.includes ('--details')
    , no_table = process.argv.includes ('--no-table')
    , table = process.argv.includes ('--table')
    , iso8601 = process.argv.includes ('--iso8601')
    , cors = process.argv.includes ('--cors')
    , cache_markets = process.argv.includes ('--cache-markets')
    , testnet =
        process.argv.includes ('--test') ||
        process.argv.includes ('--testnet') ||
        process.argv.includes ('--sandbox')
    , signIn = process.argv.includes ('--sign-in') || process.argv.includes ('--signIn')
    , isSpot = process.argv.includes ('--spot')
    , isSwap = process.argv.includes ('--swap')
    , isFuture = process.argv.includes ('--future')

//-----------------------------------------------------------------------------

const ccxt         = require ('../../ccxt.js')
    , fs           = require ('fs')
    , path         = require ('path')
    , ansi         = require ('ansicolor').nice
    , asTable      = require ('as-table').configure ({

        delimiter: ' | '.lightGray.dim,
        right: true,
        title: x => String (x).lightGray,
        dash: '-'.lightGray.dim,
        print: x => {
            if (typeof x === 'object') {
                const j = JSON.stringify (x).trim ()
                if (j.length < 100) return j
            }
            return String (x)
        }
    })
    , util         = require ('util')
    , { execSync } = require ('child_process')
    , log          = require ('ololog').configure ({ locate: false }).unlimited
    , fsPromises   = require ('fs/promises')
    , { ExchangeError, NetworkError } = ccxt

//-----------------------------------------------------------------------------

console.log (new Date ())
console.log ('Node.js:', process.version)
console.log ('CCXT v' + ccxt.version)

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); log.red.error (e.message); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); log.red.error (e.message); process.exit (1) })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

//-----------------------------------------------------------------------------

const timeout = 30000
let exchange = undefined
const enableRateLimit = true

const { Agent } = require ('https')

const httpsAgent = new Agent ({
    ecdhCurve: 'auto',
    keepAlive: true,
})

try {

    exchange = new (ccxt)[exchangeId] ({
        timeout,
        enableRateLimit,
        httpsAgent,
        ... settings,
    })

    if (isSpot) {
        exchange.options['defaultType'] = 'spot';
    } else if (isSwap) {
        exchange.options['defaultType'] = 'swap';
    } else if (isFuture) {
        exchange.options['defaultType'] = 'future';
    }

    // check auth keys in env var
    const requiredCredentials = exchange.requiredCredentials;
    for (const [credential, isRequired] of Object.entries (requiredCredentials)) {
        if (isRequired && exchange[credential] === undefined) {
            const credentialEnvName = (exchangeId + '_' + credential).toUpperCase () // example: KRAKEN_APIKEY
            const credentialValue = process.env[credentialEnvName]
            if (credentialValue) {
                exchange[credential] = credentialValue
            }
        }
    }

    if (testnet) {
        exchange.setSandboxMode (true)
    }

} catch (e) {

    log.red (e)
    printUsage ()
    process.exit ()
}

//-----------------------------------------------------------------------------

function printSupportedExchanges () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoin fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
    log ('Supported options:')
    log ('--verbose         Print verbose output')
    log ('--debug           Print debugging output')
    log ('--poll            Repeat continuously in rate-limited mode')
    log ('--no-send         Print the request but do not actually send it to the exchange (sets verbose and load-markets)')
    log ('--no-load-markets Do not pre-load markets (for debugging)')
    log ('--details         Print detailed fetch responses')
    log ('--no-table        Do not print the fetch response as a table')
    log ('--table           Print the fetch response as a table')
    log ('--iso8601         Print timestamps as ISO8601 datetimes')
    log ('--cors            use CORS proxy for debugging')
    log ('--sign-in         Call signIn() if any')
    log ('--sandbox         Use the exchange sandbox if available, same as --testnet')
    log ('--testnet         Use the exchange testnet if available, same as --sandbox')
    log ('--test            Use the exchange testnet if available, same as --sandbox')
    log ('--cache-markets   Cache the loaded markets in the .cache folder in the current directory')
}

//-----------------------------------------------------------------------------

const printHumanReadable = (exchange, result) => {
    if (!no_table && Array.isArray (result) || table) {
        result = Object.values (result)
        let arrayOfObjects = (typeof result[0] === 'object')

        if (details)
            result.forEach (object => {
                if (arrayOfObjects)
                    log ('-------------------------------------------')
                log (object)
            })

        if (arrayOfObjects || table && Array.isArray (result)) {
            log (result.length > 0 ? asTable (result.map (element => {
                let keys = Object.keys (element)
                delete element['info']
                keys.forEach (key => {
                    if (!iso8601)
                        return element[key]
                    try {
                        const iso8601 = exchange.iso8601 (element[key])
                        if (iso8601.match (/^20[0-9]{2}[-]?/))
                            element[key] = iso8601
                        else
                            throw new Error ('wrong date')
                    } catch (e) {
                        return element[key]
                    }
                })
                return element
            })) : result)
            log (result.length, 'objects');
        } else {
            console.dir (result, { depth: null })
            log (result.length, 'objects');
        }
    } else {
        console.dir (result, { depth: null, maxArrayLength: null })
    }
}

//-----------------------------------------------------------------------------

async function main () {

    if (!exchangeId) {

        printUsage ()

    } else {

        let args = params
            .map (s => s.match (/^[0-9]{4}[-]?[0-9]{2}[-]?[0-9]{2}[T\s]?[0-9]{2}[:]?[0-9]{2}[:]?[0-9]{2}/g) ? exchange.parse8601 (s) : s)
            .map (s => (() => { try { return eval ('(() => (' + s + ')) ()') } catch (e) { return s } }) ())

        const www = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www

        if (cors) {
            exchange.proxy = 'https://cors-anywhere.herokuapp.com/';
            exchange.origin = exchange.uuid ()
        }

        no_load_markets = no_send ? true : no_load_markets

        if (debug) {
            exchange.verbose = verbose
        }

        const path = '.cache/' + exchangeId + '-markets.json'

        if (!no_load_markets) {
            try {
                await fsPromises.access (path, fs.constants.R_OK)
                exchange.markets = JSON.parse (await fsPromises.readFile (path))
            } catch {
                await exchange.loadMarkets ()
                if (cache_markets) {
                    await fsPromises.writeFile (path, JSON.stringify (exchange.markets))
                }
            }
        }

        if (signIn && exchange.has.signIn) {
            await exchange.signIn ()
        }

        exchange.verbose = verbose

        if (no_send) {

            exchange.verbose = no_send
            exchange.fetch = function fetch (url, method = 'GET', headers = undefined, body = undefined) {
                log.dim.noLocate ('-------------------------------------------')
                log.dim.noLocate (exchange.iso8601 (exchange.milliseconds ()))
                log.green.unlimited ({
                    url,
                    method,
                    headers,
                    body,
                })
                process.exit ()
            }
        }

        if (methodName) {

            if (typeof exchange[methodName] === 'function') {

                log (exchange.id + '.' + methodName, '(' + args.join (', ') + ')')

                let start = exchange.milliseconds ()
                let end = exchange.milliseconds ()

                let i = 0;

                while (true) {
                    try {
                        const result = await exchange[methodName] (... args)
                        end = exchange.milliseconds ()
                        console.log (exchange.iso8601 (end), 'iteration', i++, 'passed in', end - start, 'ms\n')
                        start = end
                        printHumanReadable (exchange, result)
                    } catch (e) {
                        if (e instanceof ExchangeError) {
                            log.red (e.constructor.name, e.message)
                        } else if (e instanceof NetworkError) {
                            log.yellow (e.constructor.name, e.message)
                        }

                        log.dim ('---------------------------------------------------')

                        // rethrow for call-stack // other errors
                        throw e

                    }

                    if (debug) {
                        const keys = Object.keys (httpsAgent.freeSockets)
                        const firstKey = keys[0]
                        console.log (firstKey, httpsAgent.freeSockets[firstKey].length)
                    }

                    if (!poll){
                        break
                    }
                }

            } else if (exchange[methodName] === undefined) {
                log.red (exchange.id + '.' + methodName + ': no such property')
            } else {
                printHumanReadable (exchange, exchange[methodName])
            }
        } else {
            console.log (exchange)
        }
    }

}

//-----------------------------------------------------------------------------

main ()
<commit_msg>cli minor edits<commit_after>"use strict";

//-----------------------------------------------------------------------------

let [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
    , verbose = process.argv.includes ('--verbose')
    , debug = process.argv.includes ('--debug')
    , poll = process.argv.includes ('--poll')
    , no_send = process.argv.includes ('--no-send')
    , no_load_markets = process.argv.includes ('--no-load-markets')
    , details = process.argv.includes ('--details')
    , no_table = process.argv.includes ('--no-table')
    , table = process.argv.includes ('--table')
    , iso8601 = process.argv.includes ('--iso8601')
    , cors = process.argv.includes ('--cors')
    , cache_markets = process.argv.includes ('--cache-markets')
    , testnet =
        process.argv.includes ('--test') ||
        process.argv.includes ('--testnet') ||
        process.argv.includes ('--sandbox')
    , signIn = process.argv.includes ('--sign-in') || process.argv.includes ('--signIn')
    , isSpot = process.argv.includes ('--spot')
    , isSwap = process.argv.includes ('--swap')
    , isFuture = process.argv.includes ('--future')

//-----------------------------------------------------------------------------

const ccxt         = require ('../../ccxt.js')
    , fs           = require ('fs')
    , path         = require ('path')
    , ansi         = require ('ansicolor').nice
    , asTable      = require ('as-table').configure ({

        delimiter: ' | '.lightGray.dim,
        right: true,
        title: x => String (x).lightGray,
        dash: '-'.lightGray.dim,
        print: x => {
            if (typeof x === 'object') {
                const j = JSON.stringify (x).trim ()
                if (j.length < 100) return j
            }
            return String (x)
        }
    })
    , util         = require ('util')
    , { execSync } = require ('child_process')
    , log          = require ('ololog').configure ({ locate: false }).unlimited
    , fsPromises   = require ('fs/promises')
    , { ExchangeError, NetworkError } = ccxt

//-----------------------------------------------------------------------------

console.log (new Date ())
console.log ('Node.js:', process.version)
console.log ('CCXT v' + ccxt.version)

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); log.red.error (e.message); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); log.red.error (e.message); process.exit (1) })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

//-----------------------------------------------------------------------------

const timeout = 30000
let exchange = undefined

const { Agent } = require ('https')

const httpsAgent = new Agent ({
    ecdhCurve: 'auto',
    keepAlive: true,
})

try {

    exchange = new (ccxt)[exchangeId] ({ timeout, httpsAgent, ... settings })

    if (isSpot) {
        exchange.options['defaultType'] = 'spot';
    } else if (isSwap) {
        exchange.options['defaultType'] = 'swap';
    } else if (isFuture) {
        exchange.options['defaultType'] = 'future';
    }

    // check auth keys in env var
    const requiredCredentials = exchange.requiredCredentials;
    for (const [credential, isRequired] of Object.entries (requiredCredentials)) {
        if (isRequired && exchange[credential] === undefined) {
            const credentialEnvName = (exchangeId + '_' + credential).toUpperCase () // example: KRAKEN_APIKEY
            const credentialValue = process.env[credentialEnvName]
            if (credentialValue) {
                exchange[credential] = credentialValue
            }
        }
    }

    if (testnet) {
        exchange.setSandboxMode (true)
    }

} catch (e) {

    log.red (e)
    printUsage ()
    process.exit ()
}

//-----------------------------------------------------------------------------

function printSupportedExchanges () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoin fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
    log ('Supported options:')
    log ('--verbose         Print verbose output')
    log ('--debug           Print debugging output')
    log ('--poll            Repeat continuously in rate-limited mode')
    log ('--no-send         Print the request but do not actually send it to the exchange (sets verbose and load-markets)')
    log ('--no-load-markets Do not pre-load markets (for debugging)')
    log ('--details         Print detailed fetch responses')
    log ('--no-table        Do not print the fetch response as a table')
    log ('--table           Print the fetch response as a table')
    log ('--iso8601         Print timestamps as ISO8601 datetimes')
    log ('--cors            use CORS proxy for debugging')
    log ('--sign-in         Call signIn() if any')
    log ('--sandbox         Use the exchange sandbox if available, same as --testnet')
    log ('--testnet         Use the exchange testnet if available, same as --sandbox')
    log ('--test            Use the exchange testnet if available, same as --sandbox')
    log ('--cache-markets   Cache the loaded markets in the .cache folder in the current directory')
}

//-----------------------------------------------------------------------------

const printHumanReadable = (exchange, result) => {
    if (!no_table && Array.isArray (result) || table) {
        result = Object.values (result)
        let arrayOfObjects = (typeof result[0] === 'object')

        if (details)
            result.forEach (object => {
                if (arrayOfObjects)
                    log ('-------------------------------------------')
                log (object)
            })

        if (arrayOfObjects || table && Array.isArray (result)) {
            log (result.length > 0 ? asTable (result.map (element => {
                let keys = Object.keys (element)
                delete element['info']
                keys.forEach (key => {
                    if (!iso8601)
                        return element[key]
                    try {
                        const iso8601 = exchange.iso8601 (element[key])
                        if (iso8601.match (/^20[0-9]{2}[-]?/))
                            element[key] = iso8601
                        else
                            throw new Error ('wrong date')
                    } catch (e) {
                        return element[key]
                    }
                })
                return element
            })) : result)
            log (result.length, 'objects');
        } else {
            console.dir (result, { depth: null })
            log (result.length, 'objects');
        }
    } else {
        console.dir (result, { depth: null, maxArrayLength: null })
    }
}

//-----------------------------------------------------------------------------

async function main () {

    if (!exchangeId) {

        printUsage ()

    } else {

        let args = params
            .map (s => s.match (/^[0-9]{4}[-]?[0-9]{2}[-]?[0-9]{2}[T\s]?[0-9]{2}[:]?[0-9]{2}[:]?[0-9]{2}/g) ? exchange.parse8601 (s) : s)
            .map (s => (() => { try { return eval ('(() => (' + s + ')) ()') } catch (e) { return s } }) ())

        const www = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www

        if (cors) {
            exchange.proxy = 'https://cors-anywhere.herokuapp.com/';
            exchange.origin = exchange.uuid ()
        }

        no_load_markets = no_send ? true : no_load_markets

        if (debug) {
            exchange.verbose = verbose
        }

        const path = '.cache/' + exchangeId + '-markets.json'

        if (!no_load_markets) {
            try {
                await fsPromises.access (path, fs.constants.R_OK)
                exchange.markets = JSON.parse (await fsPromises.readFile (path))
            } catch {
                await exchange.loadMarkets ()
                if (cache_markets) {
                    await fsPromises.writeFile (path, JSON.stringify (exchange.markets))
                }
            }
        }

        if (signIn && exchange.has.signIn) {
            await exchange.signIn ()
        }

        exchange.verbose = verbose

        if (no_send) {

            exchange.verbose = no_send
            exchange.fetch = function fetch (url, method = 'GET', headers = undefined, body = undefined) {
                log.dim.noLocate ('-------------------------------------------')
                log.dim.noLocate (exchange.iso8601 (exchange.milliseconds ()))
                log.green.unlimited ({
                    url,
                    method,
                    headers,
                    body,
                })
                process.exit ()
            }
        }

        if (methodName) {

            if (typeof exchange[methodName] === 'function') {

                log (exchange.id + '.' + methodName, '(' + args.join (', ') + ')')

                let start = exchange.milliseconds ()
                let end = exchange.milliseconds ()

                let i = 0;

                while (true) {
                    try {
                        const result = await exchange[methodName] (... args)
                        end = exchange.milliseconds ()
                        console.log (exchange.iso8601 (end), 'iteration', i++, 'passed in', end - start, 'ms\n')
                        start = end
                        printHumanReadable (exchange, result)
                    } catch (e) {
                        if (e instanceof ExchangeError) {
                            log.red (e.constructor.name, e.message)
                        } else if (e instanceof NetworkError) {
                            log.yellow (e.constructor.name, e.message)
                        }

                        log.dim ('---------------------------------------------------')

                        // rethrow for call-stack // other errors
                        throw e

                    }

                    if (debug) {
                        const keys = Object.keys (httpsAgent.freeSockets)
                        const firstKey = keys[0]
                        console.log (firstKey, httpsAgent.freeSockets[firstKey].length)
                    }

                    if (!poll){
                        break
                    }
                }

            } else if (exchange[methodName] === undefined) {
                log.red (exchange.id + '.' + methodName + ': no such property')
            } else {
                printHumanReadable (exchange, exchange[methodName])
            }
        } else {
            console.log (exchange)
        }
    }

}

//-----------------------------------------------------------------------------

main ()
<|endoftext|>


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

goog.provide('org_apache_flex_binding_ViewBaseDataBinding');

goog.require('org_apache_flex_binding_ConstantBinding');
goog.require('org_apache_flex_binding_GenericBinding');
goog.require('org_apache_flex_binding_PropertyWatcher');
goog.require('org_apache_flex_binding_SimpleBinding');
goog.require('org_apache_flex_events_Event');
goog.require('org_apache_flex_events_ValueChangeEvent');

/**
 * @constructor
 */
org_apache_flex_binding_ViewBaseDataBinding = function() {

  /**
   * @private
   * @type {Object}
   */
  this.strand_ = null;

  /**
   * @protected
   * @type {Object}
   */
  this.deferredBindings = {};

};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ViewBaseDataBinding',
                qName: 'org_apache_flex_binding_ViewBaseDataBinding'}] };

Object.defineProperties(org_apache_flex_binding_ViewBaseDataBinding.prototype, {
    /** @expose */
    strand: {
        /** @this {org_apache_flex_binding_ViewBaseDataBinding} */
        set: function(value) {
            if (this.strand_ !== value) {
              this.strand_ = value;
              this.strand_.addEventListener('initComplete',
              goog.bind(this.initCompleteHandler, this));
            }
        }
    }
});

/**
 * @protected
 * @param {Object} event The event.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.initCompleteHandler =
    function(event) {

  var prop;
  var fieldWatcher;
  var sb;
  var bindingData = this.strand_._bindings;
  var n = bindingData[0];
  var bindings = [];
  var i;
  var binding;
  var destination;
  var index = 1;
  for (i = 0; i < n; i++)
  {
    binding = {};
    binding.source = bindingData[index++];
    binding.destFunc = bindingData[index++];
    binding.destination = bindingData[index++];
    bindings.push(binding);
  }
  var watchers = this.decodeWatcher(bindingData.slice(index));
  for (i = 0; i < n; i++)
  {
    binding = bindings[i];
    // try to determine if it is an array
    if (typeof(binding.source) == 'object' &&
            typeof(binding.source.slice) == 'function')
    {
      if (binding.source[0] == 'applicationModel')
      {
        if (binding.source.length == 2 &&
            binding.destination.length == 2)
        {
          // can be simplebinding or constantbinding
          var modelWatcher =
              watchers.watcherMap.applicationModel;
          var childMap = modelWatcher.children.watcherMap;
          fieldWatcher = childMap[binding.source[1]];
          if (typeof(fieldWatcher.eventNames) == 'string')
          {
            sb = new org_apache_flex_binding_SimpleBinding();
            sb.destinationPropertyName =
                binding.destination[1];
            sb.eventName = fieldWatcher.eventNames;
            sb.sourceID = binding.source[0];
            sb.sourcePropertyName = binding.source[1];
            sb.setDocument(this.strand_);
            prop = binding.destination[0];

            destination = this.strand_[prop];

            if (destination)
              destination.addBead(sb);
            else
            {
              this.deferredBindings[prop] =
                  sb;
              this.strand_.addEventListener('valueChange',
                  goog.bind(this.deferredBindingsHandler, this));
            }
          }
          else if (fieldWatcher.eventNames == null)
          {
            var cb;
            cb = org_apache_flex_binding_ConstantBinding;
            cb = new cb();
            cb.destinationPropertyName =
                binding.destination[1];
            cb.sourceID = binding.source[0];
            cb.sourcePropertyName = binding.source[1];
            cb.setDocument(this.strand_);
            prop = binding.destination[0];
            destination = this.strand_[prop];

            if (destination)
              destination.addBead(cb);
            else
            {
              this.deferredBindings[prop] =
                  cb;
              this.strand_.addEventListener('valueChange',
                  this.deferredBindingsHandler);
            }
          }
        }
      }
    }
    else if (typeof(binding.source) == 'string')
    {
      fieldWatcher = watchers.watcherMap[binding.source];
      if (typeof(fieldWatcher.eventNames) == 'string')
      {
        sb = new org_apache_flex_binding_SimpleBinding();
        sb.destinationPropertyName = binding.destination[1];
        sb.eventName = fieldWatcher.eventNames;
        sb.sourcePropertyName = binding.source;
        sb.setDocument(this.strand_);
        prop = binding.destination[0];
        destination = this.strand_[prop];

        if (destination)
          destination.addBead(sb);
        else
        {
          this.deferredBindings[prop] = sb;
          this.strand_.addEventListener('valueChange',
              this.deferredBindingsHandler);
        }
      }
    }
    else
    {
      this.makeGenericBinding(binding, i, watchers);
    }
  }
};

/**
 * @protected
 * @param {Object} binding The binding object.
 * @param {number} index The offset in the Binding database.
 * @param {Object} watchers The database of Watchers.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.makeGenericBinding =
    function(binding, index, watchers) {
  var gb = new org_apache_flex_binding_GenericBinding();
  gb.setDocument(this.strand_);
  gb.destinationData = binding.destination;
  gb.destinationFunction = binding.destFunc;
  gb.source = binding.source;
  this.setupWatchers(gb, index, watchers.watchers, null);
};

/**
 * @protected
 * @param {Object} gb The generic binding object.
 * @param {number} index The offset in the Binding database.
 * @param {Object} watchers The array of Watchers.
 * @param {Object} parentWatcher The parent Watcher or null if top.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.setupWatchers =
    function(gb, index, watchers, parentWatcher) {
  var i, n;
  n = watchers.length;
  for (i = 0; i < n; i++)
  {
    var watcher = watchers[i];
    if (watcher.bindings.indexOf(index) != -1)
    {
      var type = watcher.type;
      switch (type)
      {
        case 'property':
          {
            var pw = new org_apache_flex_binding_PropertyWatcher(
                this,
                watcher.propertyName,
                watcher.eventNames,
                watcher.getterFunction);
            watcher.watcher = pw;
            if (parentWatcher)
              pw.parentChanged(parentWatcher.value);
            else
              pw.parentChanged(this.strand_);
            if (parentWatcher)
              parentWatcher.addChild(pw);
            if (watcher.children == null)
              pw.addBinding(gb);
            break;
          }
      }
      if (watcher.children)
      {
        this.setupWatchers(gb, index, watcher.children,
            watcher.watcher);
      }
    }
  }
};

/**
 * @protected
 * @param {Object} bindingData The watcher data to decode.
 * @return {Object} The watcher tree structure.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.decodeWatcher =
    function(bindingData) {
  var watcherMap = {};
  var watchers = [];
  var n = bindingData.length - 1; // there is an extra null because
  // it is easier for the compiler
  var index = 0;
  var watcherData;
  while (index < n)
  {
    var watcherIndex = bindingData[index++];
    var type = bindingData[index++];
    switch (type)
    {
      case 0:
        {
          watcherData = { type: 'function' };
          watcherData.functionName = bindingData[index++];
          watcherData.paramFunction = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          break;
        }
      case 1:
        {
          watcherData = { type: 'static' };
          watcherData.propertyName = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherData.getterFunction = bindingData[index++];
          watcherData.parentObj = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
      case 2:
        {
          watcherData = { type: 'property' };
          watcherData.propertyName = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherData.getterFunction = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
      case 3:
        {
          watcherData = { type: 'xml' };
          watcherData.propertyName = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
    }
    watcherData.children = bindingData[index++];
    if (watcherData.children != null)
    {
      watcherData.children = this.decodeWatcher(watcherData.children);
    }
    watcherData.index = watcherIndex;
    watchers.push(watcherData);
  }
  return { watchers: watchers, watcherMap: watcherMap };
};

/**
 * @protected
 * @param {org_apache_flex_events_ValueChangeEvent} event The event.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.deferredBindingsHandler =
    function(event) {
  var p;
  var destination;
  for (p in this.deferredBindings)
  {
    if (p != event.propertyName) continue;
    destination = this.strand_[p];
    destination.addBead(this.deferredBindings[p]);
    delete this.deferredBindings[p];
  }
};

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

goog.provide('org_apache_flex_binding_ViewBaseDataBinding');

goog.require('org_apache_flex_binding_ConstantBinding');
goog.require('org_apache_flex_binding_GenericBinding');
goog.require('org_apache_flex_binding_PropertyWatcher');
goog.require('org_apache_flex_binding_SimpleBinding');
goog.require('org_apache_flex_events_Event');
goog.require('org_apache_flex_events_ValueChangeEvent');

/**
 * @constructor
 */
org_apache_flex_binding_ViewBaseDataBinding = function() {

  /**
   * @private
   * @type {Object}
   */
  this.strand_ = null;

  /**
   * @protected
   * @type {Object}
   */
  this.deferredBindings = {};

};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ViewBaseDataBinding',
                qName: 'org_apache_flex_binding_ViewBaseDataBinding'}] };

Object.defineProperties(org_apache_flex_binding_ViewBaseDataBinding.prototype, {
    /** @expose */
    strand: {
        /** @this {org_apache_flex_binding_ViewBaseDataBinding} */
        set: function(value) {
            if (this.strand_ !== value) {
              this.strand_ = value;
              this.strand_.addEventListener('initComplete',
              goog.bind(this.initCompleteHandler, this));
            }
        }
    }
});

/**
 * @protected
 * @param {Object} event The event.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.initCompleteHandler =
    function(event) {

  var prop;
  var fieldWatcher;
  var sb;
  var bindingData = this.strand_._bindings;
  var n = bindingData[0];
  var bindings = [];
  var i;
  var binding;
  var destination;
  var index = 1;
  for (i = 0; i < n; i++)
  {
    binding = {};
    binding.source = bindingData[index++];
    binding.destFunc = bindingData[index++];
    binding.destination = bindingData[index++];
    bindings.push(binding);
  }
  var watchers = this.decodeWatcher(bindingData.slice(index));
  for (i = 0; i < n; i++)
  {
    binding = bindings[i];
    // try to determine if it is an array
    if (typeof(binding.source) == 'object' &&
            typeof(binding.source.slice) == 'function')
    {
      if (binding.source[0] == 'applicationModel')
      {
        if (binding.source.length == 2 &&
            binding.destination.length == 2)
        {
          // can be simplebinding or constantbinding
          var modelWatcher =
              watchers.watcherMap.applicationModel;
          var childMap = modelWatcher.children.watcherMap;
          fieldWatcher = childMap[binding.source[1]];
          if (typeof(fieldWatcher.eventNames) == 'string')
          {
            sb = new org_apache_flex_binding_SimpleBinding();
            sb.destinationPropertyName =
                binding.destination[1];
            sb.eventName = fieldWatcher.eventNames;
            sb.sourceID = binding.source[0];
            sb.sourcePropertyName = binding.source[1];
            sb.setDocument(this.strand_);
            prop = binding.destination[0];

            destination = this.strand_[prop];

            if (destination)
              destination.addBead(sb);
            else
            {
              this.deferredBindings[prop] =
                  sb;
              this.strand_.addEventListener('valueChange',
                  goog.bind(this.deferredBindingsHandler, this));
            }
          }
          else if (fieldWatcher.eventNames == null)
          {
            var cb;
            cb = org_apache_flex_binding_ConstantBinding;
            cb = new cb();
            cb.destinationPropertyName =
                binding.destination[1];
            cb.sourceID = binding.source[0];
            cb.sourcePropertyName = binding.source[1];
            cb.setDocument(this.strand_);
            prop = binding.destination[0];
            destination = this.strand_[prop];

            if (destination)
              destination.addBead(cb);
            else
            {
              this.deferredBindings[prop] =
                  cb;
              this.strand_.addEventListener('valueChange',
                  this.deferredBindingsHandler);
            }
          }
        }
      }
    }
    else if (typeof(binding.source) == 'string')
    {
      fieldWatcher = watchers.watcherMap[binding.source];
      if (typeof(fieldWatcher.eventNames) == 'string')
      {
        sb = new org_apache_flex_binding_SimpleBinding();
        sb.destinationPropertyName = binding.destination[1];
        sb.eventName = fieldWatcher.eventNames;
        sb.sourcePropertyName = binding.source;
        sb.setDocument(this.strand_);
        prop = binding.destination[0];
        destination = this.strand_[prop];

        if (destination)
          destination.addBead(sb);
        else
        {
          this.deferredBindings[prop] = sb;
          this.strand_.addEventListener('valueChange',
              this.deferredBindingsHandler);
        }
      }
    }
    else
    {
      this.makeGenericBinding(binding, i, watchers);
    }
  }
};

/**
 * @protected
 * @param {Object} binding The binding object.
 * @param {number} index The offset in the Binding database.
 * @param {Object} watchers The database of Watchers.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.makeGenericBinding =
    function(binding, index, watchers) {
  var gb = new org_apache_flex_binding_GenericBinding();
  gb.setDocument(this.strand_);
  gb.destinationData = binding.destination;
  gb.destinationFunction = binding.destFunc;
  gb.source = binding.source;
  this.setupWatchers(gb, index, watchers.watchers, null);
};

/**
 * @protected
 * @param {Object} gb The generic binding object.
 * @param {number} index The offset in the Binding database.
 * @param {Object} watchers The array of Watchers.
 * @param {Object} parentWatcher The parent Watcher or null if top.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.setupWatchers =
    function(gb, index, watchers, parentWatcher) {
  var i, n;
  n = watchers.length;
  for (i = 0; i < n; i++)
  {
    var watcher = watchers[i];
    var isValidWatcher = false;
    if (typeof(watcher.bindings) === 'number')
      isValidWatcher = (watcher.bindings == index);
    else
      isValidWatcher = (watcher.bindings.indexOf(index) != -1);
    if (isValidWatcher) {
      var type = watcher.type;
      switch (type)
      {
        case 'property':
          {
            var pw = new org_apache_flex_binding_PropertyWatcher(
                this,
                watcher.propertyName,
                watcher.eventNames,
                watcher.getterFunction);
            watcher.watcher = pw;
            if (parentWatcher)
              pw.parentChanged(parentWatcher.value);
            else
              pw.parentChanged(this.strand_);
            if (parentWatcher)
              parentWatcher.addChild(pw);
            if (watcher.children == null)
              pw.addBinding(gb);
            break;
          }
      }
      if (watcher.children)
      {
        this.setupWatchers(gb, index, watcher.children.watchers,
            watcher.watcher);
      }
    }
  }
};

/**
 * @protected
 * @param {Object} bindingData The watcher data to decode.
 * @return {Object} The watcher tree structure.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.decodeWatcher =
    function(bindingData) {
  var watcherMap = {};
  var watchers = [];
  var n = bindingData.length - 1; // there is an extra null because
  // it is easier for the compiler
  var index = 0;
  var watcherData;
  while (index < n)
  {
    var watcherIndex = bindingData[index++];
    var type = bindingData[index++];
    switch (type)
    {
      case 0:
        {
          watcherData = { type: 'function' };
          watcherData.functionName = bindingData[index++];
          watcherData.paramFunction = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          break;
        }
      case 1:
        {
          watcherData = { type: 'static' };
          watcherData.propertyName = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherData.getterFunction = bindingData[index++];
          watcherData.parentObj = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
      case 2:
        {
          watcherData = { type: 'property' };
          watcherData.propertyName = bindingData[index++];
          watcherData.eventNames = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherData.getterFunction = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
      case 3:
        {
          watcherData = { type: 'xml' };
          watcherData.propertyName = bindingData[index++];
          watcherData.bindings = bindingData[index++];
          watcherMap[watcherData.propertyName] = watcherData;
          break;
        }
    }
    watcherData.children = bindingData[index++];
    if (watcherData.children != null)
    {
      watcherData.children = this.decodeWatcher(watcherData.children);
    }
    watcherData.index = watcherIndex;
    watchers.push(watcherData);
  }
  return { watchers: watchers, watcherMap: watcherMap };
};

/**
 * @protected
 * @param {org_apache_flex_events_ValueChangeEvent} event The event.
 */
org_apache_flex_binding_ViewBaseDataBinding.prototype.deferredBindingsHandler =
    function(event) {
  var p;
  var destination;
  for (p in this.deferredBindings)
  {
    if (p != event.propertyName) continue;
    destination = this.strand_[p];
    destination.addBead(this.deferredBindings[p]);
    delete this.deferredBindings[p];
  }
};

<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
// TODO: move this to a higher level package than chronograf?
import AutoRefresh from 'shared/components/AutoRefresh';
import LineGraph from 'shared/components/LineGraph';
import FlashMessages from 'shared/components/FlashMessages';

const RefreshingLineGraph = AutoRefresh(LineGraph);

export const HostPage = React.createClass({
  propTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
    params: PropTypes.shape({
      hostID: PropTypes.string.isRequired,
    }).isRequired,
  },

  render() {
    const autoRefreshMs = 15000;
    const source = this.props.source.links.proxy;
    const queries = [
      {
        text: `SELECT "usage_user" FROM "telegraf"."default"."cpu" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: 'CPU',
      },
      {
        text: `SELECT "used_percent" FROM "telegraf"."default"."mem" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Memory",
      },
      {
        text: `SELECT "load1" FROM "telegraf"."default"."system" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Load",
      },
      {
        text: `SELECT "bytes_recv", "bytes_sent" FROM "telegraf"."default"."net" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Network",
      },
      {
        text: `SELECT "io_time" FROM "telegraf"."default"."diskio" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Disk IO",
      },
      {
        text: `SELECT "used_percent" FROM "telegraf"."default"."disk" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Disk usage",
      },
    ];

    return (

          {
          queries.map((query) => {
            const q = Object.assign({}, query, {host: source});
            return (

{q.name}

                <RefreshingLineGraph
                  queries={[q]}
                  autoRefresh={autoRefreshMs}
                />

            );
          })
        }

    );
  },
});

export default FlashMessages(HostPage);
<commit_msg>Remove explicit "default" from RP in query<commit_after>import React, {PropTypes} from 'react';
// TODO: move this to a higher level package than chronograf?
import AutoRefresh from 'shared/components/AutoRefresh';
import LineGraph from 'shared/components/LineGraph';
import FlashMessages from 'shared/components/FlashMessages';

const RefreshingLineGraph = AutoRefresh(LineGraph);

export const HostPage = React.createClass({
  propTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
    params: PropTypes.shape({
      hostID: PropTypes.string.isRequired,
    }).isRequired,
  },

  render() {
    const autoRefreshMs = 15000;
    const source = this.props.source.links.proxy;
    const queries = [
      {
        text: `SELECT "usage_user" FROM "telegraf".."cpu" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: 'CPU',
      },
      {
        text: `SELECT "used_percent" FROM "telegraf".."mem" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Memory",
      },
      {
        text: `SELECT "load1" FROM "telegraf".."system" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Load",
      },
      {
        text: `SELECT "bytes_recv", "bytes_sent" FROM "telegraf".."net" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Network",
      },
      {
        text: `SELECT "io_time" FROM "telegraf".."diskio" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Disk IO",
      },
      {
        text: `SELECT "used_percent" FROM "telegraf".."disk" WHERE host = '${this.props.params.hostID}' AND time > now() - 15m`,
        name: "Disk usage",
      },
    ];

    return (

          {
          queries.map((query) => {
            const q = Object.assign({}, query, {host: source});
            return (

{q.name}

                <RefreshingLineGraph
                  queries={[q]}
                  autoRefresh={autoRefreshMs}
                />

            );
          })
        }

    );
  },
});

export default FlashMessages(HostPage);
<|endoftext|>