<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name abs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/abs}
*/
setReadOnly( ns, 'abs', require( '@stdlib/math/strided/special/abs' ) );

/**
* @name abs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/abs2}
*/
setReadOnly( ns, 'abs2', require( '@stdlib/math/strided/special/abs2' ) );

/**
* @name cbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/cbrt}
*/
setReadOnly( ns, 'cbrt', require( '@stdlib/math/strided/special/cbrt' ) );

/**
* @name dabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dabs}
*/
setReadOnly( ns, 'dabs', require( '@stdlib/math/strided/special/dabs' ) );

/**
* @name dabs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dabs2}
*/
setReadOnly( ns, 'dabs2', require( '@stdlib/math/strided/special/dabs2' ) );

/**
* @name dcbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dcbrt}
*/
setReadOnly( ns, 'dcbrt', require( '@stdlib/math/strided/special/dcbrt' ) );

/**
* @name dceil
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dceil}
*/
setReadOnly( ns, 'dceil', require( '@stdlib/math/strided/special/dceil' ) );

/**
* @name ddeg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/ddeg2rad}
*/
setReadOnly( ns, 'ddeg2rad', require( '@stdlib/math/strided/special/ddeg2rad' ) );

/**
* @name deg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/deg2rad}
*/
setReadOnly( ns, 'deg2rad', require( '@stdlib/math/strided/special/deg2rad' ) );

/**
* @name dfloor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dfloor}
*/
setReadOnly( ns, 'dfloor', require( '@stdlib/math/strided/special/dfloor' ) );

/**
* @name dinv
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dinv}
*/
setReadOnly( ns, 'dinv', require( '@stdlib/math/strided/special/dinv' ) );

/**
* @name dramp
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dramp}
*/
setReadOnly( ns, 'dramp', require( '@stdlib/math/strided/special/dramp' ) );

/**
* @name drsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/drsqrt}
*/
setReadOnly( ns, 'drsqrt', require( '@stdlib/math/strided/special/drsqrt' ) );

/**
* @name dsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dsqrt}
*/
setReadOnly( ns, 'dsqrt', require( '@stdlib/math/strided/special/dsqrt' ) );

/**
* @name dtrunc
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dtrunc}
*/
setReadOnly( ns, 'dtrunc', require( '@stdlib/math/strided/special/dtrunc' ) );

/**
* @name sabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sabs}
*/
setReadOnly( ns, 'sabs', require( '@stdlib/math/strided/special/sabs' ) );

/**
* @name sabs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sabs2}
*/
setReadOnly( ns, 'sabs2', require( '@stdlib/math/strided/special/sabs2' ) );

/**
* @name scbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/scbrt}
*/
setReadOnly( ns, 'scbrt', require( '@stdlib/math/strided/special/scbrt' ) );

/**
* @name sceil
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sceil}
*/
setReadOnly( ns, 'sceil', require( '@stdlib/math/strided/special/sceil' ) );

/**
* @name sdeg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sdeg2rad}
*/
setReadOnly( ns, 'sdeg2rad', require( '@stdlib/math/strided/special/sdeg2rad' ) );

/**
* @name sfloor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sfloor}
*/
setReadOnly( ns, 'sfloor', require( '@stdlib/math/strided/special/sfloor' ) );

/**
* @name sinv
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sinv}
*/
setReadOnly( ns, 'sinv', require( '@stdlib/math/strided/special/sinv' ) );

/**
* @name sqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sqrt}
*/
setReadOnly( ns, 'sqrt', require( '@stdlib/math/strided/special/sqrt' ) );

/**
* @name sramp
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sramp}
*/
setReadOnly( ns, 'sramp', require( '@stdlib/math/strided/special/sramp' ) );

/**
* @name srsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/srsqrt}
*/
setReadOnly( ns, 'srsqrt', require( '@stdlib/math/strided/special/srsqrt' ) );

/**
* @name ssqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/ssqrt}
*/
setReadOnly( ns, 'ssqrt', require( '@stdlib/math/strided/special/ssqrt' ) );

/**
* @name strunc
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/strunc}
*/
setReadOnly( ns, 'strunc', require( '@stdlib/math/strided/special/strunc' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name abs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/abs}
*/
setReadOnly( ns, 'abs', require( '@stdlib/math/strided/special/abs' ) );

/**
* @name abs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/abs2}
*/
setReadOnly( ns, 'abs2', require( '@stdlib/math/strided/special/abs2' ) );

/**
* @name cbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/cbrt}
*/
setReadOnly( ns, 'cbrt', require( '@stdlib/math/strided/special/cbrt' ) );

/**
* @name dabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dabs}
*/
setReadOnly( ns, 'dabs', require( '@stdlib/math/strided/special/dabs' ) );

/**
* @name dabs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dabs2}
*/
setReadOnly( ns, 'dabs2', require( '@stdlib/math/strided/special/dabs2' ) );

/**
* @name dcbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dcbrt}
*/
setReadOnly( ns, 'dcbrt', require( '@stdlib/math/strided/special/dcbrt' ) );

/**
* @name dceil
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dceil}
*/
setReadOnly( ns, 'dceil', require( '@stdlib/math/strided/special/dceil' ) );

/**
* @name ddeg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/ddeg2rad}
*/
setReadOnly( ns, 'ddeg2rad', require( '@stdlib/math/strided/special/ddeg2rad' ) );

/**
* @name deg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/deg2rad}
*/
setReadOnly( ns, 'deg2rad', require( '@stdlib/math/strided/special/deg2rad' ) );

/**
* @name dfloor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dfloor}
*/
setReadOnly( ns, 'dfloor', require( '@stdlib/math/strided/special/dfloor' ) );

/**
* @name dinv
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dinv}
*/
setReadOnly( ns, 'dinv', require( '@stdlib/math/strided/special/dinv' ) );

/**
* @name dramp
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dramp}
*/
setReadOnly( ns, 'dramp', require( '@stdlib/math/strided/special/dramp' ) );

/**
* @name drsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/drsqrt}
*/
setReadOnly( ns, 'drsqrt', require( '@stdlib/math/strided/special/drsqrt' ) );

/**
* @name dsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dsqrt}
*/
setReadOnly( ns, 'dsqrt', require( '@stdlib/math/strided/special/dsqrt' ) );

/**
* @name dtrunc
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/dtrunc}
*/
setReadOnly( ns, 'dtrunc', require( '@stdlib/math/strided/special/dtrunc' ) );

/**
* @name inv
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/inv}
*/
setReadOnly( ns, 'inv', require( '@stdlib/math/strided/special/inv' ) );

/**
* @name sabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sabs}
*/
setReadOnly( ns, 'sabs', require( '@stdlib/math/strided/special/sabs' ) );

/**
* @name sabs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sabs2}
*/
setReadOnly( ns, 'sabs2', require( '@stdlib/math/strided/special/sabs2' ) );

/**
* @name scbrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/scbrt}
*/
setReadOnly( ns, 'scbrt', require( '@stdlib/math/strided/special/scbrt' ) );

/**
* @name sceil
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sceil}
*/
setReadOnly( ns, 'sceil', require( '@stdlib/math/strided/special/sceil' ) );

/**
* @name sdeg2rad
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sdeg2rad}
*/
setReadOnly( ns, 'sdeg2rad', require( '@stdlib/math/strided/special/sdeg2rad' ) );

/**
* @name sfloor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sfloor}
*/
setReadOnly( ns, 'sfloor', require( '@stdlib/math/strided/special/sfloor' ) );

/**
* @name sinv
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sinv}
*/
setReadOnly( ns, 'sinv', require( '@stdlib/math/strided/special/sinv' ) );

/**
* @name sqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sqrt}
*/
setReadOnly( ns, 'sqrt', require( '@stdlib/math/strided/special/sqrt' ) );

/**
* @name sramp
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/sramp}
*/
setReadOnly( ns, 'sramp', require( '@stdlib/math/strided/special/sramp' ) );

/**
* @name srsqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/srsqrt}
*/
setReadOnly( ns, 'srsqrt', require( '@stdlib/math/strided/special/srsqrt' ) );

/**
* @name ssqrt
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/ssqrt}
*/
setReadOnly( ns, 'ssqrt', require( '@stdlib/math/strided/special/ssqrt' ) );

/**
* @name strunc
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/strided/special/strunc}
*/
setReadOnly( ns, 'strunc', require( '@stdlib/math/strided/special/strunc' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


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

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = $('[data-scroll-element]');

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

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        element.removeClass('disabled');
      } else {
        element.addClass('disabled');
      }
    };

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

      elements.each(function() {
        $this      = $(this);
        increment  = $this.data('scroll-increment');
        nextOffset = newOffset + increment;
        limit      = $this.data('scroll-limit');

        setVisibility($this, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element[0].scrollTop = 0;
      element.data('scroll-offset', 0);
    };

    $('[data-clipboard-target]').each(function() {
      var
        zeroClipboard,
        notification;

      ZeroClipboard.config({
        hoverClass : 'hover',
        activeClass: 'active'
      });

      zeroClipboard = new ZeroClipboard(this);
      zeroClipboard.on('ready', function() {
        zeroClipboard.on('aftercopy', function(e) {
          notification = $($(e.target).data('clipboard-notification'));
          notification.addClass('in').delay(1400).queue(function() {
            notification.removeClass('in');
            $(this).dequeue();
          });
        });
      });
    });

    scrollElements.each(function() {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      $this     = $(this);
      element   = $($this.data('scroll-element'));
      increment = $this.data('scroll-increment');
      limit     = element.data('scroll-limit');
      offset    = element.data('scroll-offset');

      $this.data('scroll-limit', limit);

      nextOffset = offset + increment;
      setVisibility($this, nextOffset, limit);

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

      $this.on('click', function() {
        offset = element.data('scroll-offset');

        newOffset = offset + increment;
        if (inValidRange(newOffset, limit)) {
          element.animate({
              scrollTop: $('#' + newOffset).position().top
          }, 400);
          element.data('scroll-offset', newOffset);

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

    $('[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);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  $(window).on('load', function() {
    var containerEl = $('.squatch-container-popup');
    if (!containerEl.length) { return; }

    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      statsEl,
      referralsEl,
      statsHeight,
      css,
      stylesheet;

    bodyEl      = $('.squatch-body');
    titleEl     = bodyEl.find('.squatch-title');
    statsEl     = $('.squatch-stats');
    referralsEl = $('.squatch-referrals-container');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    statsHeight = statsEl.outerHeight();

    if (referralsEl.is(':visible')) {
      statsHeight -= referralsEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + statsHeight);

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

    css = '.squatch-stats.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-stats.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

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

    document.querySelector('head').appendChild(stylesheet);
  });
})();
<commit_msg>Fix compatibility comment<commit_after>(function() {
  'use strict';

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = $('[data-scroll-element]');

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

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        element.removeClass('disabled');
      } else {
        element.addClass('disabled');
      }
    };

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

      elements.each(function() {
        $this      = $(this);
        increment  = $this.data('scroll-increment');
        nextOffset = newOffset + increment;
        limit      = $this.data('scroll-limit');

        setVisibility($this, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element[0].scrollTop = 0;
      element.data('scroll-offset', 0);
    };

    $('[data-clipboard-target]').each(function() {
      var
        zeroClipboard,
        notification;

      ZeroClipboard.config({
        hoverClass : 'hover',
        activeClass: 'active'
      });

      zeroClipboard = new ZeroClipboard(this);
      zeroClipboard.on('ready', function() {
        zeroClipboard.on('aftercopy', function(e) {
          notification = $($(e.target).data('clipboard-notification'));
          notification.addClass('in').delay(1400).queue(function() {
            notification.removeClass('in');
            $(this).dequeue();
          });
        });
      });
    });

    scrollElements.each(function() {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      $this     = $(this);
      element   = $($this.data('scroll-element'));
      increment = $this.data('scroll-increment');
      limit     = element.data('scroll-limit');
      offset    = element.data('scroll-offset');

      $this.data('scroll-limit', limit);

      nextOffset = offset + increment;
      setVisibility($this, nextOffset, limit);

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

      $this.on('click', function() {
        offset = element.data('scroll-offset');

        newOffset = offset + increment;
        if (inValidRange(newOffset, limit)) {
          element.animate({
              scrollTop: $('#' + newOffset).position().top
          }, 400);
          element.data('scroll-offset', newOffset);

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

    $('[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);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  $(window).on('load', function() {
    var containerEl = $('.squatch-container-popup');
    if (!containerEl.length) { return; }

    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      statsEl,
      referralsEl,
      statsHeight,
      css,
      stylesheet;

    bodyEl      = $('.squatch-body');
    titleEl     = bodyEl.find('.squatch-title');
    statsEl     = $('.squatch-stats');
    referralsEl = $('.squatch-referrals-container');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    statsHeight = statsEl.outerHeight();

    if (referralsEl.is(':visible')) {
      statsHeight -= referralsEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + statsHeight);

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

    css = '.squatch-stats.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-stats.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);
  });
})();
<|endoftext|>


<commit_before>import endsWith from 'lodash/endsWith';
import mapKeys from 'lodash/mapKeys';
import sha1 from 'sha1';
import log from '../lib/log';

const root = window.root;

console.assert(typeof root.app.config === 'object', 'root.app.config is not an object');

const settings = {
    version: root.app.config.version,
    webroot: root.app.config.webroot,
    name: 'cnc',
    log: {
        level: 'warn', // trace, debug, info, warn, error
        logger: 'console', // console
        prefix: ''
    },
    i18next: {
        lowerCaseLng: true,

        // logs out more info (console)
        debug: false,

        // language to lookup key if not found on set language
        fallbackLng: 'en',

        // string or array of namespaces
        ns: [
            'locale', // locale: language, timezone, ...
            'resource' // default
        ],
        // default namespace used if not passed to translation function
        defaultNS: 'resource',

        whitelist: [
            'en', // default language
            'de',
            'es',
            'fr',
            'it',
            'ja',
            'zh-cn',
            'zh-tw'
        ],

        // array of languages to preload
        preload: [],

        // language codes to lookup, given set language is 'en-US':
        // 'all' --> ['en-US', 'en', 'dev']
        // 'currentOnly' --> 'en-US'
        // 'languageOnly' --> 'en'
        load: 'currentOnly',

        // char to separate keys
        keySeparator: '.',

        // char to split namespace from key
        nsSeparator: ':',

        interpolation: {
            prefix: '{{',
            suffix: '}}'
        },

        // options for language detection
        // https://github.com/i18next/i18next-browser-languageDetector
        detection: {
            // order and from where user language should be detected
            order: ['querystring', 'cookie', 'localStorage'],

            // keys or params to lookup language from
            lookupQuerystring: 'lang',
            lookupCookie: 'lang',
            lookupLocalStorage: 'lang',

            // cache user language on
            caches: ['localStorage', 'cookie']
        },
        // options for backend
        // https://github.com/i18next/i18next-xhr-backend
        backend: {
            // path where resources get loaded from
            loadPath: root.app.config.webroot + 'i18n/{{lng}}/{{ns}}.json',

            // path to post missing resources
            addPath: 'api/i18n/sendMissing/{{lng}}/{{ns}}',

            // your backend server supports multiloading
            // /locales/resources.json?lng=de+en&ns=ns1+ns2
            allowMultiLoading: false,

            parse: function(data, url) {
                if (endsWith(url, '/resource.json')) {
                    const source = JSON.parse(data);
                    const target = mapKeys(source, (value, key) => sha1(key));
                    data = JSON.stringify(target, null, 2);
                }

                log.trace(`Loading resource: url="${url}"`);

                return data;
            },

            // allow cross domain requests
            crossDomain: false
        }
    }
};

export default settings;
<commit_msg>The parse function should return a JSON object instead of JSON string<commit_after>import endsWith from 'lodash/endsWith';
import mapKeys from 'lodash/mapKeys';
import sha1 from 'sha1';
import log from '../lib/log';

const root = window.root;

console.assert(typeof root.app.config === 'object', 'root.app.config is not an object');

const settings = {
    version: root.app.config.version,
    webroot: root.app.config.webroot,
    name: 'cnc',
    log: {
        level: 'warn', // trace, debug, info, warn, error
        logger: 'console', // console
        prefix: ''
    },
    i18next: {
        lowerCaseLng: true,

        // logs out more info (console)
        debug: false,

        // language to lookup key if not found on set language
        fallbackLng: 'en',

        // string or array of namespaces
        ns: [
            'locale', // locale: language, timezone, ...
            'resource' // default
        ],
        // default namespace used if not passed to translation function
        defaultNS: 'resource',

        whitelist: [
            'en', // default language
            'de',
            'es',
            'fr',
            'it',
            'ja',
            'zh-cn',
            'zh-tw'
        ],

        // array of languages to preload
        preload: [],

        // language codes to lookup, given set language is 'en-US':
        // 'all' --> ['en-US', 'en', 'dev']
        // 'currentOnly' --> 'en-US'
        // 'languageOnly' --> 'en'
        load: 'currentOnly',

        // char to separate keys
        keySeparator: '.',

        // char to split namespace from key
        nsSeparator: ':',

        interpolation: {
            prefix: '{{',
            suffix: '}}'
        },

        // options for language detection
        // https://github.com/i18next/i18next-browser-languageDetector
        detection: {
            // order and from where user language should be detected
            order: ['querystring', 'cookie', 'localStorage'],

            // keys or params to lookup language from
            lookupQuerystring: 'lang',
            lookupCookie: 'lang',
            lookupLocalStorage: 'lang',

            // cache user language on
            caches: ['localStorage', 'cookie']
        },
        // options for backend
        // https://github.com/i18next/i18next-xhr-backend
        backend: {
            // path where resources get loaded from
            loadPath: root.app.config.webroot + 'i18n/{{lng}}/{{ns}}.json',

            // path to post missing resources
            addPath: 'api/i18n/sendMissing/{{lng}}/{{ns}}',

            // your backend server supports multiloading
            // /locales/resources.json?lng=de+en&ns=ns1+ns2
            allowMultiLoading: false,

            // parse data after it has been fetched
            parse: function(data, url) {
                log.debug(`Loading resource: url="${url}"`);

                if (endsWith(url, '/resource.json')) {
                    return mapKeys(JSON.parse(data), (value, key) => sha1(key));
                }

                return JSON.parse(data);
            },

            // allow cross domain requests
            crossDomain: false
        }
    }
};

export default settings;
<|endoftext|>


<commit_before>
var N = require('libnested')
module.exports = function (deps) {
  var files = {}
  var apis = {}
  for(var k in deps) {
    if(deps[k] && deps[k].gives)
      delete deps[k].gives
  }
  N.each(deps, function (v, path) {
    var file = path[0]
    var api = path.slice(2).join('.')
    if(api)
      ;(files[file] = files[file] || []).push(api)

    if(file)
      ;(apis[api] = apis[api] || []).push(file)

  })

  return toDot(apis, files)
}

function dot (s) {
  return s.replace('.js', '_JS').replace(/-/g, '_').replace(/\.|\//g, '_')
}

function toDot(a, b, name) {
  name = name || ''
  var s = ''
  function log () {
    var args = [].slice.call(arguments)
    s += args.join(' ') + '\n'
  }

  log('digraph ' + (name || 'depject') + ' {')

  for(var k in a) log('  ', dot(k), '[label="'+dot(k)+'"]')
  for(var k in b) log('  ', dot(k), '[label="'+dot(k)+'", shape="box"]')
  for(var k in a)
    for(var i = 0; i < a[k].length; i++)
      if(k && a[k][i])
        log(dot(k)+'->'+dot(a[k][i]))
  for(var k in b)
    for(var i = 0; i < b[k].length; i++)
      if(k && b[k][i])
        log(dot(k)+'->'+dot(b[k][i]))

  log('}')

  return s
}

if(!module.parent) {
  var dirs = process.argv.slice(2)
  if(!dirs.length) dirs = [process.cwd()]
  var log = console.log

  console.log = function () {}
  log(module.exports(require('./')(dirs)))
  process.exit(0)
}

<commit_msg>dot supports "" strings<commit_after>
var N = require('libnested')
module.exports = function (deps) {
  var files = {}
  var apis = {}
  for(var k in deps) {
    if(deps[k] && deps[k].gives)
      delete deps[k].gives
  }
  N.each(deps, function (v, path) {
    var file = path[0]
    var api = path.slice(2).join('.')
    if(api)
      ;(files[file] = files[file] || []).push(api)

    if(file)
      ;(apis[api] = apis[api] || []).push(file)

  })

  return toDot(apis, files)
}

function dot (s) {
  return JSON.stringify(s)
  return s.replace('.js', '_JS').replace(/-/g, '_').replace(/\.|\//g, '_')
}

function toDot(a, b, name) {
  name = name || ''
  var s = ''
  function log () {
    var args = [].slice.call(arguments)
    s += args.join(' ') + '\n'
  }

  log('digraph ' + (name || 'depject') + ' {')

  for(var k in a) log('  ', dot(k), '[label='+dot(k)+']')
  for(var k in b) log('  ', dot(k), '[label='+dot(k)+', shape="box"]')
  for(var k in a)
    for(var i = 0; i < a[k].length; i++)
      if(k && a[k][i])
        log(dot(k)+'->'+dot(a[k][i]))
  for(var k in b)
    for(var i = 0; i < b[k].length; i++)
      if(k && b[k][i])
        log(dot(k)+'->'+dot(b[k][i]))

  log('}')

  return s
}

if(!module.parent) {
  var dirs = process.argv.slice(2)
  if(!dirs.length) dirs = [process.cwd()]
  var log = console.log

  console.log = function () {}
  log(module.exports(require('./')(dirs)))
  process.exit(0)
}

<|endoftext|>


<commit_before>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  git = require('gulp-git'),
  sourcemaps = require('gulp-sourcemaps'),
  tag_version = require('gulp-tag-version'),
  tslint = require('gulp-tslint'),
  ts = require('gulp-typescript'),
  PluginError = require('plugin-error'),
  minimist = require('minimist'),
  path = require('path');

const exec = require('child_process').exec;
const spawn = require('child_process').spawn;

const releaseOptions = {
  semver: '',
  gitHubToken: '',
};

// prettier
function runPrettier(command, done) {
  exec(command, function(err, stdout) {
    if (err) {
      return done(new PluginError('runPrettier', { message: err }));
    }

    if (!stdout) {
      return done();
    }

    var files = stdout
      .split(/\r?\n/)
      .filter(f => {
        return f.endsWith('.ts') || f.endsWith('.js');
      })
      .join(' ');

    if (!files) {
      return done();
    }

    const prettierPath = path.normalize('./node_modules/.bin/prettier');
    exec(
      `${prettierPath} --write --print-width 100 --single-quote --trailing-comma es5 ${files}`,
      function(err) {
        if (err) {
          return done(new PluginError('runPrettier', { message: err }));
        }
        return done();
      }
    );
  });
}

function validateArgs(done) {
  const options = minimist(process.argv.slice(2), releaseOptions);
  if (!options.semver) {
    return done(
      new PluginError('updateVersion', {
        message: 'Missing `--semver` option. Possible values: patch, minor, major',
      })
    );
  }

  const gitHubToken = options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN;
  if (!gitHubToken) {
    return done(
      new PluginError('createChangelog', {
        message:
          'Missing GitHub API Token. Supply token using `--gitHubToken` option or `CHANGELOG_GITHUB_TOKEN` environment variable.',
      })
    );
  }

  done();
}

function createChangelog(done) {
  const imageName = 'jpoon/github-changelog-generator';
  const version = require('./package.json').version;

  const options = minimist(process.argv.slice(2), releaseOptions);
  const gitHubToken = options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN;

  var dockerRunCmd = spawn(
    'docker',
    [
      'run',
      '-it',
      '--rm',
      '-v',
      process.cwd() + ':/usr/local/src/your-app',
      imageName,
      '--user',
      'vscodevim',
      '--project',
      'vim',
      '--token',
      gitHubToken,
      '--future-release',
      'v' + version,
    ],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerRunCmd.on('exit', function(exitCode) {
    done(exitCode);
  });
}

function createGitTag() {
  return gulp.src(['./package.json']).pipe(tag_version());
}

function createGitCommit() {
  return gulp
    .src(['./package.json', './package-lock.json', 'CHANGELOG.md'])
    .pipe(git.commit('bump version'));
}

function updateVersion(done) {
  var options = minimist(process.argv.slice(2), releaseOptions);

  return gulp
    .src(['./package.json', './package-lock.json'])
    .pipe(bump({ type: options.semver }))
    .pipe(gulp.dest('./'))
    .on('end', () => {
      done();
    });
}

gulp.task('tsc', function() {
  var isError = false;

  var tsProject = ts.createProject('tsconfig.json', { noEmitOnError: true });
  var tsResult = tsProject
    .src()
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .on('error', () => {
      isError = true;
    })
    .on('finish', () => {
      isError && process.exit(1);
    });

  return tsResult.js
    .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '' }))
    .pipe(gulp.dest('out'));
});

gulp.task('tslint', function() {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp
    .src(['**/*.ts', '!node_modules/**', '!typings/**'])
    .pipe(
      tslint({
        formatter: 'prose',
        program: program,
      })
    )
    .pipe(tslint.report({ summarizeFailureOutput: true }));
});

gulp.task('prettier', function(done) {
  // files changed
  runPrettier('git diff --name-only HEAD', done);
});

gulp.task('forceprettier', function(done) {
  // files managed by git
  runPrettier('git ls-files', done);
});

// test
gulp.task('test', function(done) {
  var knownOptions = {
    string: 'grep',
    default: { grep: '' },
  };
  var options = minimist(process.argv.slice(2), knownOptions);

  var spawn = require('child_process').spawn;
  const dockerTag = 'vscodevim';

  console.log('Building container...');
  var dockerBuildCmd = spawn(
    'docker',
    ['build', '-f', './build/Dockerfile', '.', '-t', dockerTag],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerBuildCmd.on('exit', function(exitCode) {
    if (exitCode !== 0) {
      return done(
        new PluginError('test', {
          message: 'Docker build failed.',
        })
      );
    }

    console.log('Running tests inside container...');
    var dockerRunCmd = spawn(
      'docker',
      [
        'run',
        '-it',
        '--env',
        `MOCHA_GREP=${options.grep}`,
        '-v',
        process.cwd() + ':/app',
        dockerTag,
      ],
      {
        cwd: process.cwd(),
        stdio: 'inherit',
      }
    );

    dockerRunCmd.on('exit', function(exitCode) {
      done(exitCode);
    });
  });
});

gulp.task('build', gulp.series('prettier', gulp.parallel('tsc', 'tslint')));
gulp.task('changelog', gulp.series(validateArgs, createChangelog));
gulp.task(
  'release',
  gulp.series(validateArgs, updateVersion, createChangelog, createGitCommit, createGitTag)
);
gulp.task('default', gulp.series('build', 'test'));
<commit_msg>Add comment describing --grep flag for gulp test task<commit_after>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  git = require('gulp-git'),
  sourcemaps = require('gulp-sourcemaps'),
  tag_version = require('gulp-tag-version'),
  tslint = require('gulp-tslint'),
  ts = require('gulp-typescript'),
  PluginError = require('plugin-error'),
  minimist = require('minimist'),
  path = require('path');

const exec = require('child_process').exec;
const spawn = require('child_process').spawn;

const releaseOptions = {
  semver: '',
  gitHubToken: '',
};

// prettier
function runPrettier(command, done) {
  exec(command, function(err, stdout) {
    if (err) {
      return done(new PluginError('runPrettier', { message: err }));
    }

    if (!stdout) {
      return done();
    }

    var files = stdout
      .split(/\r?\n/)
      .filter(f => {
        return f.endsWith('.ts') || f.endsWith('.js');
      })
      .join(' ');

    if (!files) {
      return done();
    }

    const prettierPath = path.normalize('./node_modules/.bin/prettier');
    exec(
      `${prettierPath} --write --print-width 100 --single-quote --trailing-comma es5 ${files}`,
      function(err) {
        if (err) {
          return done(new PluginError('runPrettier', { message: err }));
        }
        return done();
      }
    );
  });
}

function validateArgs(done) {
  const options = minimist(process.argv.slice(2), releaseOptions);
  if (!options.semver) {
    return done(
      new PluginError('updateVersion', {
        message: 'Missing `--semver` option. Possible values: patch, minor, major',
      })
    );
  }

  const gitHubToken = options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN;
  if (!gitHubToken) {
    return done(
      new PluginError('createChangelog', {
        message:
          'Missing GitHub API Token. Supply token using `--gitHubToken` option or `CHANGELOG_GITHUB_TOKEN` environment variable.',
      })
    );
  }

  done();
}

function createChangelog(done) {
  const imageName = 'jpoon/github-changelog-generator';
  const version = require('./package.json').version;

  const options = minimist(process.argv.slice(2), releaseOptions);
  const gitHubToken = options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN;

  var dockerRunCmd = spawn(
    'docker',
    [
      'run',
      '-it',
      '--rm',
      '-v',
      process.cwd() + ':/usr/local/src/your-app',
      imageName,
      '--user',
      'vscodevim',
      '--project',
      'vim',
      '--token',
      gitHubToken,
      '--future-release',
      'v' + version,
    ],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerRunCmd.on('exit', function(exitCode) {
    done(exitCode);
  });
}

function createGitTag() {
  return gulp.src(['./package.json']).pipe(tag_version());
}

function createGitCommit() {
  return gulp
    .src(['./package.json', './package-lock.json', 'CHANGELOG.md'])
    .pipe(git.commit('bump version'));
}

function updateVersion(done) {
  var options = minimist(process.argv.slice(2), releaseOptions);

  return gulp
    .src(['./package.json', './package-lock.json'])
    .pipe(bump({ type: options.semver }))
    .pipe(gulp.dest('./'))
    .on('end', () => {
      done();
    });
}

gulp.task('tsc', function() {
  var isError = false;

  var tsProject = ts.createProject('tsconfig.json', { noEmitOnError: true });
  var tsResult = tsProject
    .src()
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .on('error', () => {
      isError = true;
    })
    .on('finish', () => {
      isError && process.exit(1);
    });

  return tsResult.js
    .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '' }))
    .pipe(gulp.dest('out'));
});

gulp.task('tslint', function() {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp
    .src(['**/*.ts', '!node_modules/**', '!typings/**'])
    .pipe(
      tslint({
        formatter: 'prose',
        program: program,
      })
    )
    .pipe(tslint.report({ summarizeFailureOutput: true }));
});

gulp.task('prettier', function(done) {
  // files changed
  runPrettier('git diff --name-only HEAD', done);
});

gulp.task('forceprettier', function(done) {
  // files managed by git
  runPrettier('git ls-files', done);
});

// test
gulp.task('test', function(done) {
  // the flag --grep takes js regex as a string and filters by test and test suite names
  var knownOptions = {
    string: 'grep',
    default: { grep: '' },
  };
  var options = minimist(process.argv.slice(2), knownOptions);

  var spawn = require('child_process').spawn;
  const dockerTag = 'vscodevim';

  console.log('Building container...');
  var dockerBuildCmd = spawn(
    'docker',
    ['build', '-f', './build/Dockerfile', '.', '-t', dockerTag],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerBuildCmd.on('exit', function(exitCode) {
    if (exitCode !== 0) {
      return done(
        new PluginError('test', {
          message: 'Docker build failed.',
        })
      );
    }

    console.log('Running tests inside container...');
    var dockerRunCmd = spawn(
      'docker',
      [
        'run',
        '-it',
        '--env',
        `MOCHA_GREP=${options.grep}`,
        '-v',
        process.cwd() + ':/app',
        dockerTag,
      ],
      {
        cwd: process.cwd(),
        stdio: 'inherit',
      }
    );

    dockerRunCmd.on('exit', function(exitCode) {
      done(exitCode);
    });
  });
});

gulp.task('build', gulp.series('prettier', gulp.parallel('tsc', 'tslint')));
gulp.task('changelog', gulp.series(validateArgs, createChangelog));
gulp.task(
  'release',
  gulp.series(validateArgs, updateVersion, createChangelog, createGitCommit, createGitTag)
);
gulp.task('default', gulp.series('build', 'test'));
<|endoftext|>


<commit_before>#!/usr/bin/env node

(function() {
  "use strict";

  const fs = require('fs');
  const Path = require('path');
  const CONFIG_FILE = "package.json";
  const OUTPUT_FILE = "DEPENDENCIES.md";
  const TEMPLATES = loadTemplates(__dirname + "/templates");

  (function() {
    let file = readFile(CONFIG_FILE);

    let dependencies = getDependencies(file);

    writeDependencies(dependencies, TEMPLATES["dependency"], OUTPUT_FILE);
  })();

  function writeDependencies(dependencies, template, file) {
    let output = "";

    Object.keys(dependencies).forEach(function (key) {
      let name = key;
      let version = dependencies[key];
      let url = "https://www.npmjs.com/package/" + name;

      let line = template
                  .replace("{{package_name}}", name)
                  .replace("{{package_url}}", url)
                  .replace("{{package_version}}", version);

      output = output + line;
    });

    fs.writeFile(file, output, 'utf8', function (err) {
      console.log("Write complete");
    });
  }

  function loadTemplates(path) {
    let files = fs.readdirSync(path);
    let output = {};

    for (let f of files) {
      // Construct the full path of the file
      let fullPath = Path.join(path, f);

      // Read the contents of the file
      let contents = fs.readFileSync(fullPath);

      // Parse the name (without extension) from the file
      let fileName = Path.parse(f).name;

      // Conver the contents to utf-8 and store
      output[fileName] = contents.toString('utf8');
    }

    return output;
  }

  function getDependencies(file) {
    let dependencies = file.dependencies;

    if (dependencies === undefined
      || dependencies === null) {
        dependencies = {};
    }

    return dependencies;
  }

  function readFile(path) {
    let contents = fs.readFileSync(path);
    return JSON.parse(contents);
  }
})();
<commit_msg>Check readability of package.json before starting<commit_after>#!/usr/bin/env node

(function() {
  "use strict";

  const fs = require('fs');
  const Path = require('path');
  const CONFIG_FILE = "package.json";
  const OUTPUT_FILE = "DEPENDENCIES.md";
  const TEMPLATES = loadTemplates(__dirname + "/templates");

  (function() {
    if (!canReadFile(CONFIG_FILE)) {
      console.log("Unable to start dependument, unable to read package.json");
      return;
    }

    let file = readFile(CONFIG_FILE);

    let dependencies = getDependencies(file);

    writeDependencies(dependencies, TEMPLATES["dependency"], OUTPUT_FILE);
  })();

  function canReadFile(path) {
    let canRead = false;

    fs.access(path, fs.R_OK, function (err) {
      canRead = !err;
    });

    return canRead;
  }

  function writeDependencies(dependencies, template, file) {
    let output = "";

    Object.keys(dependencies).forEach(function (key) {
      let name = key;
      let version = dependencies[key];
      let url = "https://www.npmjs.com/package/" + name;

      let line = template
                  .replace("{{package_name}}", name)
                  .replace("{{package_url}}", url)
                  .replace("{{package_version}}", version);

      output = output + line;
    });

    fs.writeFile(file, output, 'utf8', function (err) {
      console.log("Write complete");
    });
  }

  function loadTemplates(path) {
    let files = fs.readdirSync(path);
    let output = {};

    for (let f of files) {
      // Construct the full path of the file
      let fullPath = Path.join(path, f);

      // Read the contents of the file
      let contents = fs.readFileSync(fullPath);

      // Parse the name (without extension) from the file
      let fileName = Path.parse(f).name;

      // Conver the contents to utf-8 and store
      output[fileName] = contents.toString('utf8');
    }

    return output;
  }

  function getDependencies(file) {
    let dependencies = file.dependencies;

    if (dependencies === undefined
      || dependencies === null) {
        dependencies = {};
    }

    return dependencies;
  }

  function readFile(path) {
    let contents = fs.readFileSync(path);
    return JSON.parse(contents);
  }
})();
<|endoftext|>


<commit_before>'use strict';

var State = require('./state');
var inherits = require('util').inherits;
var Replicator = require('./replicator');

module.exports = Leader;

function Leader(node, options) {
  var self = this;

  State.call(this);

  this.node = node;
  this.options = options;

  this.interval = undefined;
  this.peers = {};

  node.peers.forEach(function(peer) {
    self.peers[peer.id] = {
      meta: peer,
      nextIndex: node.commonState.persisted.log.length + 1,
      matchIndex: 0
    };
  });

  this.replicator = new Replicator(node, this.peers, options);
  this.replicator.on('error', function(err) {
    self.emit('error', err);
  });
  this.once('stopped',  function stopped() {
    self.replicator.stop();
  });
  this.replicator.on('response', onReplicateResponse);

  function onReplicateResponse(peerId, logIndex, entryCount, err, args) {
    if (err) self.emit('err');
    else if (args && args.term > self.node.currentTerm()) {
      self.node.currentTerm(args.term);
      self.node.save(function(err) {
        if (err) self.emit('error', err);
        self.node.toState('follower');
      });
    }
    else if (args && args.success) {
      self.peers[peerId].nextIndex = logIndex + entryCount;
      if (entryCount) self.emit('replication success', peerId, logIndex);
    }
    else {
      self.peers[peerId].nextIndex = Math.max(
        self.peers[peerId].nextIndex - 1, 0);
      self.replicator.retry(peerId);
    }
  }
}

inherits(Leader, State);

var L = Leader.prototype;

L.name = 'leader';

L.replicate = function replicate(logIndex, cb) {
  var self = this;

  var yep = 1; // count self
  var replied = false;

  this.on('replication success', onReplicationSuccess);

  function onReplicationSuccess(peerId, peerLogIndex) {
    if (peerLogIndex == logIndex) {
      yep ++;
      if (! replied && self.node.isMajority(yep)) {
        replied = true;
        self.removeListener('replication success', onReplicationSuccess);
        cb();
      }
    }
  }

};
<commit_msg>fixed replication success check<commit_after>'use strict';

var State = require('./state');
var inherits = require('util').inherits;
var Replicator = require('./replicator');

module.exports = Leader;

function Leader(node, options) {
  var self = this;

  State.call(this);

  this.node = node;
  this.options = options;

  this.interval = undefined;
  this.peers = {};

  node.peers.forEach(function(peer) {
    self.peers[peer.id] = {
      meta: peer,
      nextIndex: node.commonState.persisted.log.length + 1,
      matchIndex: 0
    };
  });

  this.replicator = new Replicator(node, this.peers, options);
  this.replicator.on('error', function(err) {
    self.emit('error', err);
  });
  this.once('stopped',  function stopped() {
    self.replicator.stop();
  });
  this.replicator.on('response', onReplicateResponse);

  function onReplicateResponse(peerId, logIndex, entryCount, err, args) {
    if (err) self.emit('err');
    else if (args && args.term > self.node.currentTerm()) {
      self.node.currentTerm(args.term);
      self.node.save(function(err) {
        if (err) self.emit('error', err);
        self.node.toState('follower');
      });
    }
    else if (args && args.success) {
      self.peers[peerId].nextIndex = logIndex + entryCount;
      if (entryCount) self.emit('replication success', peerId, logIndex);
    }
    else {
      self.peers[peerId].nextIndex = Math.max(
        self.peers[peerId].nextIndex - 1, 0);
      self.replicator.retry(peerId);
    }
  }
}

inherits(Leader, State);

var L = Leader.prototype;

L.name = 'leader';

L.replicate = function replicate(logIndex, cb) {
  var self = this;

  var yep = 1; // count self
  var replied = false;
  var done = {};

  this.on('replication success', onReplicationSuccess);

  function onReplicationSuccess(peerId, peerLogIndex) {
    if (! replied && ! done[peerId] && peerLogIndex == logIndex) {
      done[peerId] = true;
      yep ++;
      if (! replied && self.node.isMajority(yep)) {
        replied = true;
        self.removeListener('replication success', onReplicationSuccess);
        cb();
      }
    }
  }

};
<|endoftext|>


<commit_before>import _ from '../../wrap/lodash'
import create from '../create'
import isMatcher from '../is-matcher'

export default create({
  name: 'contains',
  matches (containings, actualArg) {
    if (containings.length === 0) return false

    return _.every(containings, (containing) => {
      if (_.isArray(containing)) {
        return _.some(actualArg, actualElement => _.isEqual(actualElement, containing))
      } else if (_.isRegExp(containing)) {
        return containing.test(actualArg)
      } else if (_.isObjectLike(containing) && _.isObjectLike(actualArg)) {
        return containsAllSpecified(containing, actualArg)
      } else {
        return _.includes(actualArg, containing)
      }
    })
  }
})

var containsAllSpecified = (containing, actual) => {
  if (_.isArray(actual) && !_.isArray(containing)) {
    return _.some(actual, el => {
      if (isMatcher(containing)) {
        return containing.__matches(el)
      }
      return containsAllSpecified([containing], el)
    })
  }
  return actual != null && _.every(containing, (val, key) => {
    if (isMatcher(val)) {
      return val.__matches(actual[key])
    }
    if (_.isArray(containing)) {
      return containsAllSpecified(val, actual)
    }
    if (_.isObjectLike(val)) {
      return containsAllSpecified(val, actual[key])
    } else {
      return _.isEqual(val, actual[key])
    }
  })
}<commit_msg>add back the removed end of file new line<commit_after>import _ from '../../wrap/lodash'
import create from '../create'
import isMatcher from '../is-matcher'

export default create({
  name: 'contains',
  matches (containings, actualArg) {
    if (containings.length === 0) return false

    return _.every(containings, (containing) => {
      if (_.isArray(containing)) {
        return _.some(actualArg, actualElement => _.isEqual(actualElement, containing))
      } else if (_.isRegExp(containing)) {
        return containing.test(actualArg)
      } else if (_.isObjectLike(containing) && _.isObjectLike(actualArg)) {
        return containsAllSpecified(containing, actualArg)
      } else {
        return _.includes(actualArg, containing)
      }
    })
  }
})

var containsAllSpecified = (containing, actual) => {
  if (_.isArray(actual) && !_.isArray(containing)) {
    return _.some(actual, el => {
      if (isMatcher(containing)) {
        return containing.__matches(el)
      }
      return containsAllSpecified([containing], el)
    })
  }
  return actual != null && _.every(containing, (val, key) => {
    if (isMatcher(val)) {
      return val.__matches(actual[key])
    }
    if (_.isArray(containing)) {
      return containsAllSpecified(val, actual)
    }
    if (_.isObjectLike(val)) {
      return containsAllSpecified(val, actual[key])
    } else {
      return _.isEqual(val, actual[key])
    }
  })
}
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

/* eslint-disable no-underscore-dangle */

'use strict';

// MODULES //

var logger = require( 'debug' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var isArrayLike = require( '@stdlib/assert/is-array-like-object' );
var isRegExp = require( '@stdlib/assert/is-regexp' );
var isReadableProperty = require( '@stdlib/assert/is-readable-property' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var properties = require( '@stdlib/utils/properties' );
var typeOf = require( '@stdlib/utils/type-of' );
var setdiff = require( './../setdiff.js' );

// VARIABLES //

var debug = logger( 'repl:command:vars_workspace' );

// MAIN //

/**
* Returns a callback to be invoked upon calling the `varsWorkspace` command.
*
* @private
* @param {REPL} repl - REPL instance
* @returns {Function} callback
*/
function command( repl ) {
	return onCommand;

	/**
	* Returns a list of variable names in a specified workspace.
	*
	* @private
	* @param {string} [name] - workspace name
	* @param {Options} [options] - function options
	* @param {RegExp} [options.include] - name inclusion filter
	* @param {RegExp} [options.exclude] - name exclusion filter
	* @param {ArrayLikeObject} [options.types] - type inclusion filter(s)
	* @param {boolean} [options.details] - boolean indicating whether to include additional variable details, such as variable type, contents, etc
	* @returns {(Array|void)} workspace variable names
	*/
	function onCommand( name, options ) {
		var opts;
		var list;
		var type;
		var err;
		var tmp;
		var out;
		var FLG;
		var v;
		var n;
		var i;
		var j;

		if ( arguments.length === 0 ) {
			return setdiff( repl._workspace, properties( repl._context ) );
		}
		if ( arguments.length === 1 ) {
			if ( isString( name ) ) {
				n = name;
				opts = {};
			} else if ( isPlainObject( name ) ) {
				opts = name;
			} else {
				err = new TypeError( 'invalid argument. Must provide either an options object or a workspace name. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
		} else {
			if ( !isString( name ) ) {
				err = new TypeError( 'invalid argument. First argument must be a string. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			n = name;
			if ( !isPlainObject( options ) ) {
				err = new TypeError( 'invalid argument. `options` argument must be an object. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			opts = options;
		}
		if ( hasOwnProp( opts, 'include' ) && !isRegExp( opts.include ) ) {
			err = new TypeError( 'invalid option. `include` option must be a regular expression. Option: `' + opts.include + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'exclude' ) && !isRegExp( opts.exclude ) ) {
			err = new TypeError( 'invalid option. `exclude` option must be a regular expression. Option: `' + opts.include + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'types' ) && !isArrayLike( opts.types ) ) {
			err = new TypeError( 'invalid option. `types` option must be an array-like object. Option: `' + opts.types + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'details' ) && !isBoolean( opts.details ) ) {
			err = new TypeError( 'invalid option. `details` option must be a boolean. Option: `' + opts.details + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( n === void 0 || n === repl._currentWorkspace ) {
			tmp = setdiff( repl._workspace, properties( repl._context ) );
			list = [];
			for ( i = 0; i < tmp.length; i++ ) {
				if ( isReadableProperty( repl._context, tmp[ i ] ) ) {
					list.push( tmp[ i ], repl._context[ tmp[ i ] ] );
				} else {
					// The variable can be set, but not retrieved (i.e., is write-only), so value inspection is not possible without triggering an error...
					list.push( tmp[ i ], void 0 );
				}
			}
		} else {
			if ( !hasOwnProp( repl._workspaces, n ) ) {
				err = new Error( 'invalid argument. Unrecognized workspace name. Value: `' + n + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			list = repl._workspaces[ n ].slice();
			for ( i = 1; i < list.length; i += 2 ) {
				if ( typeof list[ i ].get === 'function' ) {
					// WARNING: the `this` context is not defined, as the variable is not actually bound to a global instance!
					list[ i ] = list[ i ].get.call( null );
				} else if ( typeof list[ i ].set === 'function' ) {
					// The variable can be set, but not retrieved (i.e., is write-only), so value inspection is not possible without triggering an error...
					list[ i ] = void 0;
				} else {
					list[ i ] = list[ i ].value;
				}
			}
		}
		out = [];
		for ( i = 0; i < list.length; i += 2 ) {
			v = list[ i ];
			FLG = false;
			type = '';
			if ( opts.include && !opts.include.test( v ) ) {
				continue;
			}
			if ( opts.exclude && opts.exclude.test( v ) ) {
				continue;
			}
			if ( opts.types ) {
				type = typeOf( list[ i+1 ] );
				for ( j = 0; j < opts.types.length; j++ ) {
					if ( type === opts.types[ j ] ) {
						FLG = true;
						break;
					}
				}
				if ( FLG === false ) {
					continue;
				}
			}
			// If we've made it this far, the variable should have passed all filters...
			out.push( v );
			if ( opts.details ) {
				j = out.length - 1;
				out[ j ] = {
					'name': out[ j ],
					'type': type || typeOf( list[ i+1 ] ),
					'data': String( list[ i+1 ] ) // WARNING: for large datasets, this could be expensive!!! TODO: may want to consider alternative strategies for serialization based on a value's type.
				};
				v = out[ j ].data;
				if ( v.length > 20 ) {
					out[ j ].data = v.slice( 0, 9 ) + '...' + v.slice( v.length-8 );
				}
			}
		}
		return out;
	}
}

// EXPORTS //

module.exports = command;
<commit_msg>Sort properties to ensure symbols are sorted after strings<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

/* eslint-disable no-underscore-dangle */

'use strict';

// MODULES //

var logger = require( 'debug' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var isArrayLike = require( '@stdlib/assert/is-array-like-object' );
var isRegExp = require( '@stdlib/assert/is-regexp' );
var isReadableProperty = require( '@stdlib/assert/is-readable-property' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var properties = require( '@stdlib/utils/properties' );
var typeOf = require( '@stdlib/utils/type-of' );
var setdiff = require( './../setdiff.js' );
var propertyComparator = require( './../property_comparator.js' );

// VARIABLES //

var debug = logger( 'repl:command:vars_workspace' );

// MAIN //

/**
* Returns a callback to be invoked upon calling the `varsWorkspace` command.
*
* @private
* @param {REPL} repl - REPL instance
* @returns {Function} callback
*/
function command( repl ) {
	return onCommand;

	/**
	* Returns a list of variable names in a specified workspace.
	*
	* @private
	* @param {string} [name] - workspace name
	* @param {Options} [options] - function options
	* @param {RegExp} [options.include] - name inclusion filter
	* @param {RegExp} [options.exclude] - name exclusion filter
	* @param {ArrayLikeObject} [options.types] - type inclusion filter(s)
	* @param {boolean} [options.details] - boolean indicating whether to include additional variable details, such as variable type, contents, etc
	* @returns {(Array|void)} workspace variable names
	*/
	function onCommand( name, options ) {
		var opts;
		var list;
		var type;
		var err;
		var tmp;
		var out;
		var FLG;
		var v;
		var n;
		var i;
		var j;

		if ( arguments.length === 0 ) {
			return setdiff( repl._workspace, properties( repl._context ) );
		}
		if ( arguments.length === 1 ) {
			if ( isString( name ) ) {
				n = name;
				opts = {};
			} else if ( isPlainObject( name ) ) {
				opts = name;
			} else {
				err = new TypeError( 'invalid argument. Must provide either an options object or a workspace name. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
		} else {
			if ( !isString( name ) ) {
				err = new TypeError( 'invalid argument. First argument must be a string. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			n = name;
			if ( !isPlainObject( options ) ) {
				err = new TypeError( 'invalid argument. `options` argument must be an object. Value: `' + name + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			opts = options;
		}
		if ( hasOwnProp( opts, 'include' ) && !isRegExp( opts.include ) ) {
			err = new TypeError( 'invalid option. `include` option must be a regular expression. Option: `' + opts.include + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'exclude' ) && !isRegExp( opts.exclude ) ) {
			err = new TypeError( 'invalid option. `exclude` option must be a regular expression. Option: `' + opts.include + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'types' ) && !isArrayLike( opts.types ) ) {
			err = new TypeError( 'invalid option. `types` option must be an array-like object. Option: `' + opts.types + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( hasOwnProp( opts, 'details' ) && !isBoolean( opts.details ) ) {
			err = new TypeError( 'invalid option. `details` option must be a boolean. Option: `' + opts.details + '`.' );
			debug( 'Error: %s', err.message );
			repl._ostream.write( 'Error: '+err.message+'\n' );
			return;
		}
		if ( n === void 0 || n === repl._currentWorkspace ) {
			tmp = properties( repl._context ).sort( propertyComparator );
			tmp = setdiff( repl._workspace, tmp );
			list = [];
			for ( i = 0; i < tmp.length; i++ ) {
				if ( isReadableProperty( repl._context, tmp[ i ] ) ) {
					list.push( tmp[ i ], repl._context[ tmp[ i ] ] );
				} else {
					// The variable can be set, but not retrieved (i.e., is write-only), so value inspection is not possible without triggering an error...
					list.push( tmp[ i ], void 0 );
				}
			}
		} else {
			if ( !hasOwnProp( repl._workspaces, n ) ) {
				err = new Error( 'invalid argument. Unrecognized workspace name. Value: `' + n + '`.' );
				debug( 'Error: %s', err.message );
				repl._ostream.write( 'Error: '+err.message+'\n' );
				return;
			}
			list = repl._workspaces[ n ].slice();
			for ( i = 1; i < list.length; i += 2 ) {
				if ( typeof list[ i ].get === 'function' ) {
					// WARNING: the `this` context is not defined, as the variable is not actually bound to a global instance!
					list[ i ] = list[ i ].get.call( null );
				} else if ( typeof list[ i ].set === 'function' ) {
					// The variable can be set, but not retrieved (i.e., is write-only), so value inspection is not possible without triggering an error...
					list[ i ] = void 0;
				} else {
					list[ i ] = list[ i ].value;
				}
			}
		}
		out = [];
		for ( i = 0; i < list.length; i += 2 ) {
			v = list[ i ];
			FLG = false;
			type = '';
			if ( opts.include && !opts.include.test( v ) ) {
				continue;
			}
			if ( opts.exclude && opts.exclude.test( v ) ) {
				continue;
			}
			if ( opts.types ) {
				type = typeOf( list[ i+1 ] );
				for ( j = 0; j < opts.types.length; j++ ) {
					if ( type === opts.types[ j ] ) {
						FLG = true;
						break;
					}
				}
				if ( FLG === false ) {
					continue;
				}
			}
			// If we've made it this far, the variable should have passed all filters...
			out.push( v );
			if ( opts.details ) {
				j = out.length - 1;
				out[ j ] = {
					'name': out[ j ],
					'type': type || typeOf( list[ i+1 ] ),
					'data': String( list[ i+1 ] ) // WARNING: for large datasets, this could be expensive!!! TODO: may want to consider alternative strategies for serialization based on a value's type.
				};
				v = out[ j ].data;
				if ( v.length > 20 ) {
					out[ j ].data = v.slice( 0, 9 ) + '...' + v.slice( v.length-8 );
				}
			}
		}
		return out;
	}
}

// EXPORTS //

module.exports = command;
<|endoftext|>


<commit_before>var styleSettings = {
	defaultStyle: [{
		title: undefined,
		minScale: undefined,
		maxScale: undefined,
		stroke: {
			color: 'rgba(0,0,0,1.0)',
			lineDash: undefined,
			width: 2
		},
		fill: {
			color: 'rgba(0,0,0,0.5)',
		},
		icon: {
			src: undefined,
			scale: undefined
		},
		circle: {
			stroke: 'rgba(0,0,0,1.0)',
			fill: 'rgba(0,0,0,0.5)',
			radius: 10
		}
	}], //end defaultStyle
	mask: [
		[{
			stroke: {
				color: 'rgba(0,0,0,1.0)'
			},
			fill: {
				color: 'rgba(0,0,0,1.0)'
			}
		}]
	],
	pagaende_detaljplaner: [
		[{
			maxScale: 10000,
			stroke: {
				color: 'rgba(255,0,0,1.0)',
				width: 3,
				lineDash: [10, 10],
			},
			fill: {
				color: 'rgba(255,255,255,0.1)'
			}
		}],[{
			minScale: 10000,
			stroke: {
				color: 'rgba(255,0,0,1.0)',
				width: 4,
				lineDash: [10, 10]
			},
			fill: {
				color: 'rgba(255,255,255,0.1)'
			}
		}]
	],
	gallande_detaljplaner: [
		[{
			maxScale: 10000,
			stroke: {
				color: 'rgba(0,132,168,1.0)',
				width: 2
			},
			fill: {
				color: 'rgba(190,210,255,0.5)'
			}
		}],[{
			minScale: 10000,
			stroke: {
				color: 'rgba(0,132,168,1.0)',
				width: 4
			},
			fill: {
				color: 'rgba(190,210,255,0.5)'
			}
		}]
	],
	ledig_naringsmark: [
		[{
			fill: {
				color: 'rgba(56,168,0,0.7)'
			},
			stroke: {
				color: 'rgba(38,115,0,1.0)',
				width: 2
			},
			filter: '[typ] != ""'
		}]
	],
	etableringsomraden: [
		[{
			stroke: {
				color: 'rgba(24,69,1,1.0)',
				lineDash: [10, 10],
				width: 4
			},
			fill: {
				color: 'rgba(24,69,1,0.2)'
			}
		}]
	],
	cykelvagar: [
		[{
			stroke: {
				color: 'rgba(219,117,49,1.0)',
				lineDash: [7,3],
				width: 3
			}
		}]
	],
	fmis_punkt: [
		[{
			icon: {
				size: [32,32],
				src: 'data/svg/fornlamning.svg',
			}
		}]
	],
	fmis_linje: [
		[{
			stroke: {
				color: 'rgba(147,126,28,0.9)',
				width: 3
			}
		}]
	],
	fmis_polygon: [
		[{
			fill: {
				color: 'rgba(147,126,28,0.5)',
			}
		}]
	],
	karta_gra: [
		[{
			image: {
				src: 'data/png/gra.png'
			}
		}]
	],
	karta_farg: [
		[{
			image: {
				src: 'data/png/farg.png'
			}
		}]
	],
	orto: [
		[{
			image: {
				src: 'data/png/orto.png'
			}
		}]
	]

} //end styleSettings<commit_msg>Added circle style<commit_after>var styleSettings = {
	defaultStyle: [{
		title: undefined,
		minScale: undefined,
		maxScale: undefined,
		stroke: {
			color: 'rgba(0,0,0,1.0)',
			lineDash: undefined,
			width: 2
		},
		fill: {
			color: 'rgba(0,0,0,0.5)',
		},
		icon: {
			src: undefined,
			scale: undefined
		},
		circle: {
			stroke: 'rgba(0,0,0,1.0)',
			fill: 'rgba(0,0,0,0.5)',
			radius: 10
		}
	}], //end defaultStyle
	mask: [
		[{
			stroke: {
				color: 'rgba(0,0,0,1.0)'
			},
			fill: {
				color: 'rgba(0,0,0,1.0)'
			}
		}]
	],
	cirkel: [
		[{
			circle: {
				radius: 5,
				stroke: {
					color: 'rgba(0,0,0,1)',
					width: 2
				},
				fill: {
					color: 'rgba(255,255,255,1)'
				}
			}
		}]
	],
	pagaende_detaljplaner: [
		[{
			maxScale: 10000,
			stroke: {
				color: 'rgba(255,0,0,1.0)',
				width: 3,
				lineDash: [10, 10],
			},
			fill: {
				color: 'rgba(255,255,255,0.1)'
			}
		}],[{
			minScale: 10000,
			stroke: {
				color: 'rgba(255,0,0,1.0)',
				width: 4,
				lineDash: [10, 10]
			},
			fill: {
				color: 'rgba(255,255,255,0.1)'
			}
		}]
	],
	gallande_detaljplaner: [
		[{
			maxScale: 10000,
			stroke: {
				color: 'rgba(0,132,168,1.0)',
				width: 2
			},
			fill: {
				color: 'rgba(190,210,255,0.5)'
			}
		}],[{
			minScale: 10000,
			stroke: {
				color: 'rgba(0,132,168,1.0)',
				width: 4
			},
			fill: {
				color: 'rgba(190,210,255,0.5)'
			}
		}]
	],
	ledig_naringsmark: [
		[{
			fill: {
				color: 'rgba(56,168,0,0.7)'
			},
			stroke: {
				color: 'rgba(38,115,0,1.0)',
				width: 2
			},
			filter: '[typ] != ""'
		}]
	],
	etableringsomraden: [
		[{
			stroke: {
				color: 'rgba(24,69,1,1.0)',
				lineDash: [10, 10],
				width: 4
			},
			fill: {
				color: 'rgba(24,69,1,0.2)'
			}
		}]
	],
	cykelvagar: [
		[{
			stroke: {
				color: 'rgba(219,117,49,1.0)',
				lineDash: [7,3],
				width: 3
			}
		}]
	],
	fmis_punkt: [
		[{
			icon: {
				size: [32,32],
				src: 'data/svg/fornlamning.svg',
			}
		}]
	],
	fmis_linje: [
		[{
			stroke: {
				color: 'rgba(147,126,28,0.9)',
				width: 3
			}
		}]
	],
	fmis_polygon: [
		[{
			fill: {
				color: 'rgba(147,126,28,0.5)',
			}
		}]
	],
	karta_gra: [
		[{
			image: {
				src: 'data/png/gra.png'
			}
		}]
	],
	karta_farg: [
		[{
			image: {
				src: 'data/png/farg.png'
			}
		}]
	],
	orto: [
		[{
			image: {
				src: 'data/png/orto.png'
			}
		}]
	]

} //end styleSettings<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else
if (myDate.getHours() <=8  || myDate.getHours() > 20 )
{
  groet = 'Goedenavond, bedankt voor je bezoek. Op dit moment is Independer echter gesloten. Uiteraard kun je met onze IndyBot praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen naar info@independer. Dan komt het altijd goed.';
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
      //prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)

          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Huis](postback:hypotheekkeuze_huis) %[Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheek_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja - graag](postback:update_ja) %[Nee,bedankt](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja - graag':
            return bot.say(`Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, bedankt':
              receive: () => 'bye'
              break;
          default:
            return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
              .then(() => 'processing')
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailVisitor=message.text.trim();
          return bot.setProp('emailVisitor', emailVisitor)
              .then(()  => bot.say(`Ok - dan hou ik je via ${emailVisitor} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekkeuze_appartement: {
receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
}
},
hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

askName: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case 'Huis':
          return bot.say(`Leuk :)`)
          .then(() => 'vervolgVragen')
          break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...'),
  receive: (bot, message) => {
      const name = message.text;
      return bot.setProp('name', name)
          .then(() => bot.say(`Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.`))
          .then(() => 'lastCheck');
    }
},

lastCheck: {
    prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen?  %[Ja](postback:speak) %[Nee](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ja':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>dv<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else
if (myDate.getHours() <=8  || myDate.getHours() > 20 )
{
  groet = 'Goedenavond, bedankt voor je bezoek. Op dit moment is Independer echter gesloten. Uiteraard kun je met onze IndyBot praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen naar info@independer. Dan komt het altijd goed.';
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheek_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say('http://www.bieg.nl/beeld/woning.jpg)'))
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja - graag](postback:update_ja) %[Nee,bedankt](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja - graag':
            return bot.say(`Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, bedankt':
              receive: () => 'bye'
              break;
          default:
            return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
              .then(() => 'processing')
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailVisitor=message.text.trim();
          return bot.setProp('emailVisitor', emailVisitor)
              .then(()  => bot.say(`Ok - dan hou ik je via ${emailVisitor} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekkeuze_appartement: {
receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
}
},
hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

askName: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case 'Huis':
          return bot.say(`Leuk :)`)
          .then(() => 'vervolgVragen')
          break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...'),
  receive: (bot, message) => {
      const name = message.text;
      return bot.setProp('name', name)
          .then(() => bot.say(`Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.`))
          .then(() => 'lastCheck');
    }
},

lastCheck: {
    prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen?  %[Ja](postback:speak) %[Nee](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ja':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>